//------------------------------------------------------------------------------------------- // レイを追跡します. //------------------------------------------------------------------------------------------- void trace( const Ray &r, int dpt, bool m, const Vector3 &fl, const Vector3 &adj, int i ) { double t; int id; dpt++; if (!intersect(r, t, id) || (dpt >= 20)) return; auto d3 = dpt * 3; const auto &obj = sph[ id ]; auto x = r.pos + r.dir*t, n = normalize( x - obj.pos ); auto f = obj.color; auto nl = ( dot(n, r.dir ) < 0 ) ? n : n*-1; auto p = ( f.x > f.y && f.x > f.z ) ? f.x : ( f.y > f.z ) ? f.y : f.z; if ( obj.type == MaterialType::Matte ) { if (m) { // eye ray // store the measurment point auto hp = new HitRecord; hp->f = mul(f,adj); hp->pos = x; hp->nrm = n; hp->idx = i; hitpoints.push_back( hp ); // find the bounding box of all the measurement points hpbbox.merge( x ); } else { // photon ray // find neighboring measurement points and accumulate flux via progressive density estimation auto hh = (x - hpbbox.mini) * hash_s; auto ix = abs(int(hh.x)); auto iy = abs(int(hh.y)); auto iz = abs(int(hh.z)); // strictly speaking, we should use #pragma omp critical here. // it usually works without an artifact due to the fact that photons are // rarely accumulated to the same measurement points at the same time (especially with QMC). // it is also significantly faster. { auto list = hash_grid[ hash( ix, iy, iz ) ]; for( auto itr = list.begin(); itr != list.end(); itr++ ) { auto hp = (*itr); auto v = hp->pos - x; // check normals to be closer than 90 degree (avoids some edge brightning) if ((dot(hp->nrm,n) > 1e-3) && (dot(v,v) <= hp->r2)) { // unlike N in the paper, hp->n stores "N / ALPHA" to make it an integer value auto g = (hp->n * ALPHA + ALPHA ) / ( hp->n * ALPHA + 1.0 ); hp->r2 = hp->r2 * g; hp->n++; hp->flux = ( hp->flux + mul( hp->f, fl ) / D_PI ) * g; } } } // use QMC to sample the next direction auto r1 = 2.0 * D_PI * halton( d3 - 1, i ); auto r2 = halton( d3 + 0, i ); auto r2s = sqrt( r2 ); auto w = nl; auto u = normalize(cross((fabs(w.x) > .1 ? Vector3(0, 1, 0) : Vector3(1, 0, 0)), w)); auto v = cross( w, u ); auto d = normalize( u * cos( r1 ) * r2s + v * sin( r1 ) * r2s + w * sqrt( 1 - r2 )); if ( halton( d3 + 1, i ) < p ) trace(Ray(x, d), dpt, m, mul(f,fl)*(1. / p), mul(f, adj), i); } } else if ( obj.type == MaterialType::Mirror ) { trace(Ray(x, reflect(r.dir, n)), dpt, m, mul(f,fl), mul(f,adj), i); } else { Ray lr( x, reflect( r.dir, n ) ); auto into = dot(n, nl ) > 0.0; auto nc = 1.0; auto nt = 1.5; auto nnt = (into) ? nc / nt : nt / nc; auto ddn = dot( r.dir, nl ); auto cos2t = 1 - nnt * nnt * ( 1 - ddn * ddn ); // total internal reflection if (cos2t < 0) return trace(lr, dpt, m, mul(f, fl), mul(f, adj), i); auto td = normalize(r.dir * nnt - n * ( ( into ? 1 : -1 ) * ( ddn * nnt + sqrt( cos2t )))); auto a = nt - nc; auto b = nt + nc; auto R0 = a * a / ( b * b ); auto c = 1 - (into ? -ddn : dot(td, n)); auto Re = R0 + (1 - R0) * c * c * c * c * c; auto P = Re; Ray rr(x, td); auto fa = mul( f, adj ); auto ffl = mul( f, fl ); if (m) { // eye ray (trace both rays) trace( lr, dpt, m, ffl, fa * Re, i ); trace( rr, dpt, m, ffl, fa * (1.0 - Re), i ); } else { // photon ray (pick one via Russian roulette) ( halton( d3 - 1, i ) < P ) ? trace( lr, dpt, m, ffl, fa * Re, i ) : trace( rr, dpt, m, ffl, fa * (1.0 - Re), i ); } } }
bool openFileSelectionDialog( bx::FilePath& _inOutFilePath , FileSelectionDialogType::Enum _type , const bx::StringView& _title , const bx::StringView& _filter ) { #if BX_PLATFORM_LINUX char tmp[4096]; bx::StaticMemoryBlockWriter writer(tmp, sizeof(tmp) ); bx::Error err; bx::write(&writer, &err , "--file-selection%s --title \"%.*s\" --filename \"%s\"" , FileSelectionDialogType::Save == _type ? " --save" : "" , _title.getLength() , _title.getPtr() , _inOutFilePath.getCPtr() ); for (bx::LineReader lr(_filter); !lr.isDone();) { const bx::StringView line = lr.next(); bx::write(&writer, &err , " --file-filter \"%.*s\"" , line.getLength() , line.getPtr() ); } if (err.isOk() ) { bx::ProcessReader pr; if (bx::open(&pr, "zenity", tmp, &err) ) { char buffer[1024]; int32_t total = bx::read(&pr, buffer, sizeof(buffer), &err); bx::close(&pr); if (0 == pr.getExitCode() ) { _inOutFilePath.set(bx::strRTrim(bx::StringView(buffer, total), "\n\r") ); return true; } } } #elif BX_PLATFORM_WINDOWS BX_UNUSED(_type); char out[bx::kMaxFilePath] = { '\0' }; OPENFILENAMEA ofn; bx::memSet(&ofn, 0, sizeof(ofn) ); ofn.structSize = sizeof(OPENFILENAMEA); ofn.initialDir = _inOutFilePath.getCPtr(); ofn.file = out; ofn.maxFile = sizeof(out); ofn.flags = 0 | /* OFN_EXPLORER */ 0x00080000 | /* OFN_FILEMUSTEXIST */ 0x00001000 | /* OFN_DONTADDTORECENT */ 0x02000000 ; char tmp[4096]; bx::StaticMemoryBlockWriter writer(tmp, sizeof(tmp) ); bx::Error err; ofn.title = tmp; bx::write(&writer, &err, "%.*s", _title.getLength(), _title.getPtr() ); bx::write(&writer, '\0', &err); ofn.filter = tmp + uint32_t(bx::seek(&writer) ); for (bx::LineReader lr(_filter); !lr.isDone() && err.isOk();) { const bx::StringView line = lr.next(); const bx::StringView sep = bx::strFind(line, '|'); if (!sep.isEmpty() ) { bx::write(&writer, bx::strTrim(bx::StringView(line.getPtr(), sep.getPtr() ), " "), &err); bx::write(&writer, '\0', &err); bool first = true; for (Split split(bx::strTrim(bx::StringView(sep.getPtr()+1, line.getTerm() ), " "), ' '); !split.isDone() && err.isOk();) { const bx::StringView token = split.next(); if (!first) { bx::write(&writer, ';', &err); } first = false; bx::write(&writer, token, &err); } bx::write(&writer, '\0', &err); } else { bx::write(&writer, line, &err); bx::write(&writer, '\0', &err); bx::write(&writer, '\0', &err); } } bx::write(&writer, '\0', &err); if (err.isOk() && GetOpenFileNameA(&ofn) ) { _inOutFilePath.set(ofn.file); return true; } #else BX_UNUSED(_inOutFilePath, _type, _title, _filter); #endif // BX_PLATFORM_LINUX return false; }
bool SceneCullingState::isOccludedByTerrain( SceneObject* object ) const { PROFILE_SCOPE( SceneCullingState_isOccludedByTerrain ); // Don't try to occlude globally bounded objects. if( object->isGlobalBounds() ) return false; const Vector< SceneObject* >& terrains = getSceneManager()->getContainer()->getTerrains(); const U32 numTerrains = terrains.size(); for( U32 terrainIdx = 0; terrainIdx < numTerrains; ++ terrainIdx ) { TerrainBlock* terrain = dynamic_cast< TerrainBlock* >( terrains[ terrainIdx ] ); if( !terrain ) continue; MatrixF terrWorldTransform = terrain->getWorldTransform(); Point3F localCamPos = getCameraState().getViewPosition(); terrWorldTransform.mulP(localCamPos); F32 height; terrain->getHeight( Point2F( localCamPos.x, localCamPos.y ), &height ); bool aboveTerrain = ( height <= localCamPos.z ); // Don't occlude if we're below the terrain. This prevents problems when // looking out from underground bases... if( !aboveTerrain ) continue; const Box3F& oBox = object->getObjBox(); F32 minSide = getMin(oBox.len_x(), oBox.len_y()); if (minSide > 85.0f) continue; const Box3F& rBox = object->getWorldBox(); Point3F ul(rBox.minExtents.x, rBox.minExtents.y, rBox.maxExtents.z); Point3F ur(rBox.minExtents.x, rBox.maxExtents.y, rBox.maxExtents.z); Point3F ll(rBox.maxExtents.x, rBox.minExtents.y, rBox.maxExtents.z); Point3F lr(rBox.maxExtents.x, rBox.maxExtents.y, rBox.maxExtents.z); terrWorldTransform.mulP(ul); terrWorldTransform.mulP(ur); terrWorldTransform.mulP(ll); terrWorldTransform.mulP(lr); Point3F xBaseL0_s = ul - localCamPos; Point3F xBaseL0_e = lr - localCamPos; Point3F xBaseL1_s = ur - localCamPos; Point3F xBaseL1_e = ll - localCamPos; static F32 checkPoints[3] = {0.75, 0.5, 0.25}; RayInfo rinfo; for( U32 i = 0; i < 3; i ++ ) { Point3F start = (xBaseL0_s * checkPoints[i]) + localCamPos; Point3F end = (xBaseL0_e * checkPoints[i]) + localCamPos; if (terrain->castRay(start, end, &rinfo)) continue; terrain->getHeight(Point2F(start.x, start.y), &height); if ((height <= start.z) == aboveTerrain) continue; start = (xBaseL1_s * checkPoints[i]) + localCamPos; end = (xBaseL1_e * checkPoints[i]) + localCamPos; if (terrain->castRay(start, end, &rinfo)) continue; Point3F test = (start + end) * 0.5; if (terrain->castRay(localCamPos, test, &rinfo) == false) continue; return true; } } return false; }
//! Chargement des paramètres de calibration depuis le fichier "config.xml" void CalibrationUtils::loadXMLSettings(){ bGoToNextStep = false; // Can this load via http? if( calibrationXML.loadFile("calibration.xml")){ //WOOT! message = "Calibration Loaded!"; }else{ //FAIL! message = "No calibration Found..."; // GENERATE DEFAULT XML DATA WHICH WILL BE SAVED INTO THE CONFIG } bool bboxRoot = true; bool screenRoot = true; bCalibrating = false; calibrationStep = 0; //Set grid and init everything that relates to teh grid GRID_X = calibrationXML.getValue("SCREEN:GRIDMESH:GRIDX", 50); GRID_Y = calibrationXML.getValue("SCREEN:GRIDMESH:GRIDY", 50); //setGrid(GRID_X, GRID_Y); setGrid(GRID_X, GRID_Y); //Bounding Box Points if(bboxRoot){ vector2df ul(calibrationXML.getValue("SCREEN:BOUNDINGBOX:ulx", 0.000000),calibrationXML.getValue("SCREEN:BOUNDINGBOX:uly", 0.000000)); vector2df lr(calibrationXML.getValue("SCREEN:BOUNDINGBOX:lrx", 1.000000),calibrationXML.getValue("SCREEN:BOUNDINGBOX:lry", 1.000000)); rect2df boundingbox(ul, lr); setScreenBBox(boundingbox); }else{ setScreenScale(1.0f); } //Calibration Points if(screenRoot) { //lets see how many <STROKE> </STROKE> tags there are in the xml file int numDragTags = calibrationXML.getNumTags("SCREEN:POINT"); //if there is at least one <POINT> tag we can read the list of points if(numDragTags > 0){ //we push into the last POINT tag this temporarirly treats the tag as the document root. calibrationXML.pushTag("SCREEN:POINT", numDragTags-1); //we see how many points we have stored in <POINT> tags int numPtTags = calibrationXML.getNumTags("POINT"); if(numPtTags > 0){ //We then read those x y values into our array for(int i = 0; i < numPtTags; i++){ //the last argument of getValue can be used to specify //which tag out of multiple tags you are refering to. int x = calibrationXML.getValue("POINT:X", 0.000000, i); int y = calibrationXML.getValue("POINT:Y", 0.000000, i); cameraPoints[i].coord = vector2df(x,y); printf("Calibration: %f, %f\n", cameraPoints[i].coord.X, cameraPoints[i].coord.Y); bscreenPoints = true; bcameraPoints = true; } } calibrationXML.popTag(); //Set XML root back to highest level } } //End calibrationXML Calibration Settings //Set the camera calibated box. calculateBox(); computeCameraToScreenMap(); }
void initVAO(void) { const int fw_1 = field_width-1; const int fh_1 = field_height-1; int num_verts = field_width*field_height; int num_faces = fw_1*fh_1; GLfloat *vertices = new GLfloat[2*num_verts]; GLfloat *texcoords = new GLfloat[2*num_verts]; GLfloat *bodies = new GLfloat[4*(N_FOR_VIS+1)]; GLuint *indices = new GLuint[6*num_faces]; GLuint *bindices = new GLuint[N_FOR_VIS+1]; glm::vec4 ul(-1.0,-1.0,1.0,1.0); glm::vec4 lr(1.0,1.0,0.0,0.0); for(int i = 0; i < field_width; ++i) { for(int j = 0; j < field_height; ++j) { float alpha = float(i) / float(fw_1); float beta = float(j) / float(fh_1); vertices[(j*field_width + i)*2 ] = alpha*lr.x + (1-alpha)*ul.x; vertices[(j*field_width + i)*2+1] = beta*lr.y + (1-beta)*ul.y; texcoords[(j*field_width + i)*2 ] = alpha*lr.z + (1-alpha)*ul.z; texcoords[(j*field_width + i)*2+1] = beta*lr.w + (1-beta)*ul.w; } } for(int i = 0; i < fw_1; ++i) { for(int j = 0; j < fh_1; ++j) { indices[6*(i+(j*fw_1)) ] = field_width*j + i; indices[6*(i+(j*fw_1)) + 1] = field_width*j + i + 1; indices[6*(i+(j*fw_1)) + 2] = field_width*(j+1) + i; indices[6*(i+(j*fw_1)) + 3] = field_width*(j+1) + i; indices[6*(i+(j*fw_1)) + 4] = field_width*(j+1) + i + 1; indices[6*(i+(j*fw_1)) + 5] = field_width*j + i + 1; } } for(int i = 0; i < N_FOR_VIS+1; i++) { bodies[4*i+0] = 0.0f; bodies[4*i+1] = 0.0f; bodies[4*i+2] = 0.0f; bodies[4*i+3] = 1.0f; bindices[i] = i; } glGenBuffers(1, &planeVBO); glGenBuffers(1, &planeTBO); glGenBuffers(1, &planeIBO); glGenBuffers(1, &planetVBO); glGenBuffers(1, &planetIBO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBufferData(GL_ARRAY_BUFFER, 2*num_verts*sizeof(GLfloat), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, planeTBO); glBufferData(GL_ARRAY_BUFFER, 2*num_verts*sizeof(GLfloat), texcoords, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, planeIBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6*num_faces*sizeof(GLuint), indices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, planetVBO); glBufferData(GL_ARRAY_BUFFER, 4*(N_FOR_VIS+1)*sizeof(GLfloat), bodies, GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, planetIBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (N_FOR_VIS+1)*sizeof(GLuint), bindices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); delete[] vertices; delete[] texcoords; delete[] bodies; delete[] indices; delete[] bindices; }
/** * Raytraces some portion of the scene. Should raytrace for about * max_time duration and then return, even if the raytrace is not complete. * The results should be placed in the given buffer. * @param buffer The buffer into which to place the color data. It is * 32-bit RGBA (4 bytes per pixel), in row-major order. * @param max_time, If non-null, the maximum suggested time this * function raytrace before returning, in seconds. If null, the raytrace * should run to completion. * @return true if the raytrace is complete, false if there is more * work to be done. */ bool Raytracer::raytrace(unsigned char *buffer, real_t* max_time, int numthreads) { (void) max_time; // unused parameter std::thread *thread = new std::thread[numthreads]; tsqueue<PacketRegion> packet_queue; double tot_start = CycleTimer::currentSeconds(); for (size_t y = 0; y < height; y += packet_dim) { size_t ymax = y + packet_dim - 1; if (ymax >= height) { ymax = height - 1; } for (size_t x = 0; x < width; x += packet_dim ) { size_t xmax = x + packet_dim - 1; if (xmax >= width) { xmax = width - 1; } Int2 ll(x, y); Int2 lr(xmax, y); Int2 ul(x, ymax); Int2 ur(xmax, ymax); PacketRegion packet(ll, lr, ul, ur); packet_queue.Push(packet); } } double push_duration = CycleTimer::currentSeconds() - tot_start; double thread_start = CycleTimer::currentSeconds(); for (int i = 0; i < numthreads; i++) { //cout << "Launching thread " << i << endl; thread[i] = std::thread(&Raytracer::trace_packet_worker, this, &packet_queue, buffer); } for (int i = 0; i < numthreads; i++) { //cout << "Joining thread " << i << endl; thread[i].join(); } double thread_duration = CycleTimer::currentSeconds() - thread_start; double tot_duration = CycleTimer::currentSeconds() - tot_start; cout << numthreads << " Total time: " << tot_duration << endl << numthreads << " Push time: " << push_duration << endl << numthreads << " Thread time: " << thread_duration << endl; delete [] thread; return true; }
void PCLoaderDlrNavteq::loadPolyFile(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, PCTypeMap& tm) { // get the defaults RGBColor c = RGBColor::parseColor(oc.getString("color")); // attributes of the poly // parse int l = 0; LineReader lr(file); while (lr.hasMore()) { std::string line = lr.readLine(); ++l; // skip invalid/empty lines if (line.length() == 0 || line.find("#") != std::string::npos) { continue; } if (StringUtils::prune(line) == "") { continue; } // parse the poi StringTokenizer st(line, "\t"); std::vector<std::string> values = st.getVector(); if (values.size() < 6 || values.size() % 2 != 0) { throw ProcessError("Invalid dlr-navteq-polygon - line: '" + line + "'."); } std::string id = values[0]; std::string ort = values[1]; std::string type = values[2]; std::string name = values[3]; PositionVector vec; size_t index = 4; // now collect the positions while (values.size() > index) { std::string xpos = values[index]; std::string ypos = values[index + 1]; index += 2; SUMOReal x = TplConvert::_2SUMOReal(xpos.c_str()); SUMOReal y = TplConvert::_2SUMOReal(ypos.c_str()); Position pos(x, y); if (!GeoConvHelper::getProcessing().x2cartesian(pos)) { WRITE_WARNING("Unable to project coordinates for polygon '" + id + "'."); } vec.push_back(pos); } name = StringUtils::convertUmlaute(name); if (name == "noname" || toFill.containsPolygon(name)) { name = name + "#" + toString(toFill.getEnumIDFor(name)); } // check the polygon if (vec.size() == 0) { WRITE_WARNING("The polygon '" + id + "' is empty."); continue; } if (id == "") { WRITE_WARNING("The name of a polygon is missing; it will be discarded."); continue; } // patch the values bool fill = vec.front() == vec.back(); bool discard = oc.getBool("discard"); int layer = oc.getInt("layer"); RGBColor color; if (tm.has(type)) { const PCTypeMap::TypeDef& def = tm.get(type); name = def.prefix + name; type = def.id; color = def.color; fill = fill && def.allowFill; discard = def.discard; layer = def.layer; } else { name = oc.getString("prefix") + name; type = oc.getString("type"); color = c; } if (!discard) { Polygon* poly = new Polygon(name, type, color, vec, fill, (SUMOReal)layer); toFill.insert(name, poly, layer); } vec.clear(); } }
int main(int argc, char** argv) { time_t currentTime = time(0); fprintf(stderr, "Analysis started at: %s", ctime(¤tTime)); PARSE_PARAMETER(argc, argv); PARAMETER_STATUS(); if (FLAG_REMAIN_ARG.size() > 0) { fprintf(stderr, "Unparsed arguments: "); for (unsigned int i = 0; i < FLAG_REMAIN_ARG.size(); i++) { fprintf(stderr, " %s", FLAG_REMAIN_ARG[i].c_str()); } fprintf(stderr, "\n"); abort(); } REQUIRE_STRING_PARAMETER(FLAG_inVcf, "Please provide input file using: --inVcf"); const char defaultDbSnp[] = "/net/fantasia/home/zhanxw/amd/data/umake-resources/dbSNP/" "dbsnp_129_b37.rod.map"; if (FLAG_snp == "") { FLAG_snp = defaultDbSnp; fprintf(stderr, "Use default dbsnp: [ %s ]\n", defaultDbSnp); } SiteSet snpSet; snpSet.loadRodFile(FLAG_snp); fprintf(stderr, "%zu dbSNP sites loaded.\n", snpSet.getTotalSite()); const char defaultHM3[] = "/net/fantasia/home/zhanxw/amd/data/umake-resources/HapMap3/" "hapmap3_r3_b37_fwd.consensus.qc.poly.bim"; if (FLAG_hapmap == "") { FLAG_hapmap = defaultHM3; fprintf(stderr, "Use default HapMap: [ %s ]\n", defaultHM3); } SiteSet hmSet; hmSet.loadBimFile(FLAG_hapmap); fprintf(stderr, "%zu Hapmap sites loaded.\n", hmSet.getTotalSite()); const char* fn = FLAG_inVcf.c_str(); LineReader lr(fn); // // set range filters here // // e.g. // // vin.setRangeList("1:69500-69600"); // vin.setRangeList(FLAG_rangeList.c_str()); // vin.setRangeFile(FLAG_rangeFile.c_str()); std::map<std::string, Variant> freq; std::string chrom; int pos; // std::string filt; // std::string anno; std::string numVariant; char ref, alt; bool inDbSnp; bool inHapmap; int lineNo = 0; std::vector<std::string> fd; while (lr.readLineBySep(&fd, " \t")) { lineNo++; if (fd[0][0] == '#') continue; // skip header chrom = fd[0]; // ref is on column 0 (0-based) pos = atoi(fd[1]); // ref is on column 1 (0-based) ref = fd[3][0]; // ref is on column 3 (0-based) alt = fd[4][0]; // ref is on column 4 (0-based) // filt = fd[6]; // filt is on column 6 (0-based) // anno = extractAnno(fd[7]); // info is on column 7 (0-based), we will // extract ANNO= // obtain number of variants if (fd.size() <= 9) { // first 9 columns are not individuals numVariant = toString(0); } else { int numVar = 0; for (size_t i = 9; i < fd.size(); ++i) { int varCount = countVariant(fd[i]); if (varCount > 0) numVar += varCount; } numVariant = toString(numVar); } inDbSnp = snpSet.isIncluded(chrom.c_str(), pos); inHapmap = hmSet.isIncluded(chrom.c_str(), pos); Variant& v = freq[numVariant]; v.total++; if (isTs(ref, alt)) { v.ts++; if (inDbSnp) { v.tsInDbSnp++; v.dbSnp++; } } else if (isTv(ref, alt)) { v.tv++; if (inDbSnp) { v.tvInDbSnp++; v.dbSnp++; } }; if (inHapmap) v.hapmap++; if (lineNo % 10000 == 0) { fprintf(stderr, "\rProcessed %d lines...\r", lineNo); } }; fprintf(stdout, "Total %d VCF records have been read successfully\n", lineNo); ////////////////////////////////////////////////////////////////////// std::string title = "Summarize per annotation type"; int pad = (170 - title.size()) / 2; std::string outTitle = std::string(pad, '-') + title + std::string(pad, '-'); puts(outTitle.c_str()); printf("%40s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\n", "Filter", "#SNPs", "#dbSNP", "%dbSNP", "Known Ts/Tv", "Novel Ts/Tv", "Overall", "%TotalHM3", "%HMCalled"); std::map<std::string, Variant> indvFreq; Variant total; // to sort variants by its integer order, we use a temporary map std::map<int, Variant> tmp; for (std::map<std::string, Variant>::iterator i = freq.begin(); i != freq.end(); ++i) { tmp[atoi(i->first)] = i->second; }; for (std::map<int, Variant>::iterator i = tmp.begin(); i != tmp.end(); ++i) { i->second.print(toString(i->first), hmSet); total += i->second; }; total.print("TOTAL", hmSet); currentTime = time(0); fprintf(stderr, "Analysis end at: %s", ctime(¤tTime)); return 0; };
void mtsTeleOperationECM::RunEnabled(void) { if (mIsClutched) { return; } /* --- Forces on MTMs --- */ const vct3 frictionForceCoeff(-10.0, -10.0, -40.0); const double distanceForceCoeff = 150.0; //-1- vector between MTMs vct3 vectorLR; vectorLR.DifferenceOf(mMTMR.PositionCartesianCurrent.Position().Translation(), mMTML.PositionCartesianCurrent.Position().Translation()); // -2- mid-point, aka center of image vct3 c; c.SumOf(mMTMR.PositionCartesianCurrent.Position().Translation(), mMTML.PositionCartesianCurrent.Position().Translation()); c.Multiply(0.5); vct3 directionC = c.Normalized(); // -3- image up vector vct3 up; up.CrossProductOf(vectorLR, c); up.NormalizedSelf(); // -4- Width of image vct3 side; side.CrossProductOf(c, up); side.NormalizedSelf(); // -5- find desired position for L and R vct3 goalL(c); goalL.AddProductOf(-mInitial.w, side); goalL.AddProductOf(-mInitial.d, directionC); vct3 goalR(c); goalR.AddProductOf(mInitial.w, side); goalR.AddProductOf(mInitial.d, directionC); // compute forces on L and R based on error in position vct3 forceFriction; vct3 force; prmForceCartesianSet wrenchR, wrenchL; // MTMR // apply force force.DifferenceOf(goalR, mMTMR.PositionCartesianCurrent.Position().Translation()); force.Multiply(distanceForceCoeff); wrenchR.Force().Ref<3>(0).Assign(force); // add friction force forceFriction.ElementwiseProductOf(frictionForceCoeff, mMTMR.VelocityCartesianCurrent.VelocityLinear()); wrenchR.Force().Ref<3>(0).Add(forceFriction); // apply mMTMR.SetWrenchBody(wrenchR); // MTML // apply force force.DifferenceOf(goalL, mMTML.PositionCartesianCurrent.Position().Translation()); force.Multiply(distanceForceCoeff); wrenchL.Force().Ref<3>(0).Assign(force); // add friction force forceFriction.ElementwiseProductOf(frictionForceCoeff, mMTML.VelocityCartesianCurrent.VelocityLinear()); wrenchL.Force().Ref<3>(0).Add(forceFriction); // apply mMTML.SetWrenchBody(wrenchL); /* --- Joint Control --- */ static const vct3 normXZ(0.0, 1.0, 0.0); static const vct3 normYZ(1.0, 0.0, 0.0); static const vct3 normXY(0.0, 0.0, 1.0); // Initial ECM joints vctVec goalJoints(mInitial.ECMPositionJoint); // Change in directions and joints vctVec changeJoints(4); vctVec changeDir(4); vct3 crossN; // normal to direction of motion // - Direction 0 - left/right, movement in the XZ plane vct3 lr(c[0], 0.0, c[2]); lr.NormalizedSelf(); if (mInitial.Lr.AlmostEqual(lr)) { changeDir[0] = 0.0; } else { changeDir[0] = -acos(vctDotProduct(mInitial.Lr, lr)); crossN = vctCrossProduct(mInitial.Lr, lr); if (vctDotProduct(normXZ, crossN) < 0.0) { changeDir[0] = -changeDir[0]; } } // - Direction 1 - up/down, movement in the YZ plane vct3 ud(0.0, c[1], c[2]); ud.NormalizedSelf(); if (mInitial.Ud.AlmostEqual(ud)) { changeDir[1] = 0.0; } else { changeDir[1] = acos(vctDotProduct(mInitial.Ud, ud)); crossN = vctCrossProduct(mInitial.Ud, ud); if (vctDotProduct(normYZ, crossN) < 0.0) { changeDir[1] = -changeDir[1]; } } // - Direction 2 - in/out changeDir[2] = mScale * (mInitial.C.Norm() - c.Norm()); // - Direction 3 - cc/ccw, movement in the XY plane vct3 cw(up[0], up[1], 0); cw.NormalizedSelf(); if (mInitial.Cw.AlmostEqual(cw)) { changeDir[3] = 0.0; } else { changeDir[3] = -acos(vctDotProduct(mInitial.Cw, cw)); crossN = vctCrossProduct(mInitial.Cw, cw); if (vctDotProduct(normXY, crossN) < 0) { changeDir[3] = -changeDir[3]; } } // adjusting movement for camera orientation double totalChangeJoint3 = changeDir[3] + mInitial.ECMPositionJoint[3]; changeJoints[0] = changeDir[0] * cos(totalChangeJoint3) - changeDir[1] * sin(totalChangeJoint3); changeJoints[1] = changeDir[1] * cos(totalChangeJoint3) + changeDir[0] * sin(totalChangeJoint3); changeJoints[2] = changeDir[2]; changeJoints[3] = changeDir[3]; goalJoints.Add(changeJoints); mECM.PositionJointSet.Goal().ForceAssign(goalJoints); mECM.SetPositionJoint(mECM.PositionJointSet); /* --- Lock Orientation --- */ //Calculate new rotations of MTMs vctMatRot3 currMTMLRot; vctMatRot3 currMTMRRot; // Current ECM Rotation vctEulerZYXRotation3 finalEulerAngles; vctMatrixRotation3<double> currECMRot; vctMatrixRotation3<double> finalECMRot; finalEulerAngles.Assign(goalJoints[3], goalJoints[0], goalJoints[1]); vctEulerToMatrixRotation3(finalEulerAngles, finalECMRot); currECMRot = finalECMRot * mInitial.ECMRotEuler.Inverse(); // Set MTM Orientation currMTMLRot = currECMRot.Inverse() * mInitial.MTMLRot; currMTMRRot = currECMRot.Inverse() * mInitial.MTMRRot; // set cartesian effort parameters mMTML.SetWrenchBodyOrientationAbsolute(true); mMTML.LockOrientation(currMTMLRot); mMTMR.SetWrenchBodyOrientationAbsolute(true); mMTMR.LockOrientation(currMTMRRot); }
void IntroScreen::DoLayout() { m_splash->Resize(this->Size()); m_logo->Resize(GG::Pt(this->Width(), this->Height() / 10)); m_version->MoveTo(GG::Pt(this->Width() - m_version->Width(), this->Height() - m_version->Height())); //size calculation consts and variables const GG::X MIN_BUTTON_WIDTH(160); const GG::Y MIN_BUTTON_HEIGHT(40); GG::X button_width(0); //width of the buttons GG::Y button_cell_height(0); //height of the buttons const GG::X H_MAINMENU_MARGIN(40); //horizontal empty space const GG::Y V_MAINMENU_MARGIN(40); //vertical empty space GG::X mainmenu_width(0); //width of the mainmenu GG::Y mainmenu_height(0); //height of the mainmenu //calculate necessary button width button_width = std::max(button_width, m_single_player->MinUsableSize().x); button_width = std::max(button_width, m_quick_start->MinUsableSize().x); button_width = std::max(button_width, m_multi_player->MinUsableSize().x); button_width = std::max(button_width, m_load_game->MinUsableSize().x); button_width = std::max(button_width, m_options->MinUsableSize().x); button_width = std::max(button_width, m_pedia->MinUsableSize().x); button_width = std::max(button_width, m_about->MinUsableSize().x); button_width = std::max(button_width, m_website->MinUsableSize().x); button_width = std::max(button_width, m_credits->MinUsableSize().x); button_width = std::max(button_width, m_exit_game->MinUsableSize().x); button_width = std::max(MIN_BUTTON_WIDTH, button_width); //calculate necessary button height button_cell_height = std::max(MIN_BUTTON_HEIGHT, m_exit_game->MinUsableSize().y); //culate window width and height mainmenu_width = button_width + H_MAINMENU_MARGIN; mainmenu_height = 10.75 * button_cell_height + V_MAINMENU_MARGIN; // 10 rows + 0.75 before exit button // place buttons GG::Pt button_ul(GG::X(15), GG::Y(12)); GG::Pt button_lr(button_width, m_exit_game->MinUsableSize().y); button_lr += button_ul; m_single_player->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_quick_start->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_multi_player->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_load_game->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_options->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_pedia->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_about->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_website->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height); button_lr.y += GG::Y(button_cell_height); m_credits->SizeMove(button_ul, button_lr); button_ul.y += GG::Y(button_cell_height) * 1.75; button_lr.y += GG::Y(button_cell_height) * 1.75; m_exit_game->SizeMove(button_ul, button_lr); // position menu window GG::Pt ul(Width() * GetOptionsDB().Get<double>("UI.main-menu.x") - mainmenu_width/2, Height() * GetOptionsDB().Get<double>("UI.main-menu.y") - mainmenu_height/2); GG::Pt lr(Width() * GetOptionsDB().Get<double>("UI.main-menu.x") + mainmenu_width/2, Height() * GetOptionsDB().Get<double>("UI.main-menu.y") + mainmenu_height/2); m_menu->SizeMove(ul, lr); }
int main(){ cache::lru<int, int> lr(10); }
BundleCompiler::BundleCompiler(const char* source_dir, const char* bundle_dir) : _source_fs(default_allocator(), source_dir) , _bundle_fs(default_allocator(), bundle_dir) , _compilers(default_allocator()) , _files(default_allocator()) , _globs(default_allocator()) { namespace pcr = physics_config_resource; namespace phr = physics_resource; namespace pkr = package_resource; namespace sdr = sound_resource; namespace mhr = mesh_resource; namespace utr = unit_resource; namespace txr = texture_resource; namespace mtr = material_resource; namespace lur = lua_resource; namespace ftr = font_resource; namespace lvr = level_resource; namespace spr = sprite_resource; namespace shr = shader_resource; namespace sar = sprite_animation_resource; namespace cor = config_resource; register_resource_compiler(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, lur::compile); register_resource_compiler(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::compile); register_resource_compiler(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::compile); register_resource_compiler(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, sdr::compile); register_resource_compiler(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, utr::compile); register_resource_compiler(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, spr::compile); register_resource_compiler(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, pkr::compile); register_resource_compiler(RESOURCE_TYPE_PHYSICS, RESOURCE_VERSION_PHYSICS, phr::compile); register_resource_compiler(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, mtr::compile); register_resource_compiler(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, pcr::compile); register_resource_compiler(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, ftr::compile); register_resource_compiler(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, lvr::compile); register_resource_compiler(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::compile); register_resource_compiler(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, sar::compile); register_resource_compiler(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::compile); _bundle_fs.create_directory(bundle_dir); if (!_bundle_fs.exists(CROWN_DATA_DIRECTORY)) _bundle_fs.create_directory(CROWN_DATA_DIRECTORY); scan_source_dir(""); TempAllocator512 ta; vector::push_back(_globs, DynamicString("*.tmp", ta)); vector::push_back(_globs, DynamicString("*.wav", ta)); vector::push_back(_globs, DynamicString("*.ogg", ta)); vector::push_back(_globs, DynamicString("*.png", ta)); vector::push_back(_globs, DynamicString("*.tga", ta)); vector::push_back(_globs, DynamicString("*.dds", ta)); vector::push_back(_globs, DynamicString("*.ktx", ta)); vector::push_back(_globs, DynamicString("*.pvr", ta)); vector::push_back(_globs, DynamicString("*.swn", ta)); // VIM swap file. vector::push_back(_globs, DynamicString("*.swo", ta)); // VIM swap file. vector::push_back(_globs, DynamicString("*.swp", ta)); // VIM swap file. vector::push_back(_globs, DynamicString("*~", ta)); vector::push_back(_globs, DynamicString(".*", ta)); if (_source_fs.exists(CROWN_BUNDLEIGNORE)) { File& file = *_source_fs.open(CROWN_BUNDLEIGNORE, FileOpenMode::READ); const u32 size = file.size(); char* data = (char*)default_allocator().allocate(size + 1); file.read(data, size); data[size] = '\0'; _source_fs.close(file); LineReader lr(data); while (!lr.eof()) { TempAllocator512 ta; DynamicString line(ta); lr.read_line(line); line.trim(); if (line.empty() || line.starts_with("#")) continue; vector::push_back(_globs, line); } default_allocator().deallocate(data); } }
int main(int argc, char** argv) { time_t currentTime = time(0); fprintf(stderr, "Analysis started at: %s", ctime(¤tTime)); PARSE_PARAMETER(argc, argv); PARAMETER_STATUS(); if (FLAG_REMAIN_ARG.size() > 0) { fprintf(stderr, "Unparsed arguments: "); for (unsigned int i = 0; i < FLAG_REMAIN_ARG.size(); i++) { fprintf(stderr, " %s", FLAG_REMAIN_ARG[i].c_str()); } fprintf(stderr, "\n"); abort(); } REQUIRE_STRING_PARAMETER(FLAG_inVcf, "Please provide input file using: --inVcf"); const char* fn = FLAG_inVcf.c_str(); VCFInputFile vin(fn); // set range filters here // e.g. // vin.setRangeList("1:69500-69600"); vin.setRangeList(FLAG_rangeList.c_str()); vin.setRangeFile(FLAG_rangeFile.c_str()); // set people filters here if (FLAG_peopleIncludeID.size() || FLAG_peopleIncludeFile.size()) { vin.excludeAllPeople(); vin.includePeople(FLAG_peopleIncludeID.c_str()); vin.includePeopleFromFile(FLAG_peopleIncludeFile.c_str()); } vin.excludePeople(FLAG_peopleExcludeID.c_str()); vin.excludePeopleFromFile(FLAG_peopleExcludeFile.c_str()); // let's write it out. if (FLAG_updateId != "") { int ret = vin.updateId(FLAG_updateId.c_str()); fprintf(stdout, "%d samples have updated id.\n", ret); } // load gene ranges std::map<std::string, std::string> geneRange; if (FLAG_geneName.size()) { if (FLAG_geneFile.size() == 0) { fprintf(stderr, "Have to provide --geneFile to extract by gene.\n"); abort(); } LineReader lr(FLAG_geneFile); std::vector<std::string> fd; while (lr.readLineBySep(&fd, "\t ")) { if (FLAG_geneName != fd[0]) continue; fd[2] = chopChr(fd[2]); // chop "chr1" to "1" if (geneRange.find(fd[0]) == geneRange.end()) { geneRange[fd[0]] = fd[2] + ":" + fd[4] + "-" + fd[5]; } else { geneRange[fd[0]] += "," + fd[2] + ":" + fd[4] + "-" + fd[5]; } }; } std::string range; for (std::map<std::string, std::string>::iterator it = geneRange.begin(); it != geneRange.end(); it++) { if (range.size() > 0) { range += ","; } range += it->second; }; fprintf(stderr, "range = %s\n", range.c_str()); vin.setRangeList(range.c_str()); Regex regex; if (FLAG_annoType.size()) { regex.readPattern(FLAG_annoType); } // print header std::vector<std::string> names; vin.getVCFHeader()->getPeopleName(&names); printf("CHROM\tPOS"); for (unsigned int i = 0; i < names.size(); i++) { printf("\t%s", names[i].c_str()); } printf("\n"); // real working part int nonVariantSite = 0; while (vin.readRecord()) { VCFRecord& r = vin.getVCFRecord(); VCFPeople& people = r.getPeople(); VCFIndividual* indv; if (FLAG_variantOnly) { bool hasVariant = false; int geno; int GTidx = r.getFormatIndex("GT"); for (size_t i = 0; i < people.size(); i++) { indv = people[i]; geno = indv->justGet(GTidx).getGenotype(); if (geno != 0 && geno != MISSING_GENOTYPE) hasVariant = true; } if (!hasVariant) { nonVariantSite++; continue; } } if (FLAG_annoType.size()) { bool isMissing = false; const char* tag = r.getInfoTag("ANNO", &isMissing).toStr(); if (isMissing) continue; // fprintf(stdout, "ANNO = %s", tag); bool match = regex.match(tag); // fprintf(stdout, " %s \t", match ? "match": "noMatch"); // fprintf(stdout, " %s \n", exists ? "exists": "missing"); if (!match) { continue; } } fprintf(stdout, "%s\t%s", r.getChrom(), r.getPosStr()); for (size_t i = 0; i < people.size(); i++) { indv = people[i]; fprintf(stdout, "\t%d", indv->justGet(0).getGenotype()); } fprintf(stdout, "\n"); }; currentTime = time(0); fprintf(stderr, "Analysis ends at: %s", ctime(¤tTime)); return 0; };
TImageP ImageLoader::build(int imFlags, void *extData) { assert(extData); // Extract external data BuildExtData *data = static_cast<BuildExtData *>(extData); int subsampling = buildSubsampling(imFlags, data); try { // Initialize level reader TLevelReaderP lr(m_path); if (!lr) return TImageP(); // Load info in cases where it's required first lr->doReadPalette(false); if ((m_path.getType() == "pli") || (m_path.getType() == "svg") || (m_path.getType() == "psd")) lr->loadInfo(); lr->doReadPalette(true); // Allow palette loading TImageReaderP ir = lr->getFrameReader(m_fid); bool enable64bit = (imFlags & ImageManager::is64bitEnabled); ir->enable16BitRead(enable64bit); // Set 64-bit loading if required // Load the image TImageP img; if (data->m_icon && m_path.getType() == "tlv") img = ir->loadIcon(); // TODO: Why just in the tlv case?? else { ir->setShrink(subsampling); img = ir->load(); } ir->enable16BitRead(false); if (!img) return img; // There was an error loading the image. TPalette *palette = data->m_sl->getPalette(); if (palette) img->setPalette(palette); if (subsampling > 1) { // Store the subsampling info in the image if (TRasterImageP ri = img) ri->setSubsampling(subsampling); else if (TToonzImageP ti = img) ti->setSubsampling(subsampling); } // In case the image will be cached, store its subsampling and 64 bit compatibility if (!(imFlags & ImageManager::dontPutInCache)) { m_subsampling = subsampling; m_64bitCompatible = data->m_sl->is16BitChannelLevel() ? enable64bit : true; } return img; } catch (...) { return TImageP(); } }
unsigned Stream::ReadAt(void *buffer, uint64_t pos, size_t len, size_t *pread) { /** @todo Isn't thread-safe like the other ReadAt's. Add a mutex. */ LOG(HTTP) << "hs" << this << ".ReadAt(" << pos << ",+" << len << ") lastpos=" << m_last_pos << "\n"; if (!m_need_fetch && pos != m_last_pos) { m_socket.Close(); m_socket.Open(); m_need_fetch = true; Seek(pos); } if (m_len && pos == m_len) { *pread = 0; return 0; } if (m_need_fetch) { m_socket.SetNonBlocking(false); LOG(HTTP) << "hs" << this << ": synchronous connect\n"; unsigned int rc = m_socket.Connect(m_ipe); if (rc != 0) { LOG(HTTP) << "hs" << this << " can't connect: " << rc << "\n"; return rc; } std::string headers = "GET"; headers += " " + m_path + " HTTP/1.1\r\n"; headers += "Host: " + m_host + "\r\n"; if (pos) { if (m_len) { headers += util::Printf() << "Range: bytes=" << pos << "-" << (m_len-1) << "\r\n"; } else { /* This is a bit nasty. Some "traditional" Receiver * servers (in particular, Jupiter) don't like * one-ended ranges. All such servers are on the * "traditional" Receiver port of 12078; all such * servers don't deal with >4GB files anyway. They do, * however, deal with clipping large ranges to the * actual size. */ if (m_ipe.port == 12078) { headers += util::Printf() << "Range: bytes=" << pos << "-4294967295\r\n"; } else { headers += util::Printf() << "Range: bytes=" << pos << "-\r\n"; } } } headers += "User-Agent: " PACKAGE_NAME "/" PACKAGE_VERSION "\r\n"; headers += "\r\n"; rc = m_socket.WriteAll(headers.c_str(), headers.length()); if (rc != 0) { TRACE << "Can't even write headers: " << rc << "\n"; return rc; } LOG(HTTP) << "hs" << this << " sent headers:\n" << headers; rc = m_socket.SetNonBlocking(true); if (rc != 0) { TRACE << "Can't set non-blocking: " << rc << "\n"; return rc; } util::GreedyLineReader lr(&m_socket); http::Parser hp(&lr); bool is_error = false; for (;;) { unsigned int httpcode; rc = hp.GetResponseLine(&httpcode, NULL); LOG(HTTP) << "GetResponseLine returned " << rc << "\n"; if (rc == 0) { is_error = (httpcode != 206 && httpcode != 200); break; } if (rc != EWOULDBLOCK) { TRACE << "GetLine failed " << rc << "\n"; return rc; } if (rc == EWOULDBLOCK) { rc = m_socket.WaitForRead(30000); if (rc != 0) { TRACE << "hs" << this << " socket won't come ready " << rc << "\n"; return rc; } } } m_socket.SetNonBlocking(false); bool got_range = false; uint64_t clen = 0; for (;;) { std::string key, value; rc = hp.GetHeaderLine(&key, &value); // Note that PeekingLineReader uses ReadPeek which doesn't use // the internal timeout. if (rc == EWOULDBLOCK) { rc = m_socket.WaitForRead(5000); if (rc != 0) { TRACE << "hs" << this << " socket won't come ready in headers " << rc << "\n"; return rc; } continue; } if (rc) { TRACE << "GetHeaderLine says " << rc << ", bailing\n"; return rc; } if (key.empty()) break; LOG(HTTP) << "hs" << this << " " << key << ": " << value << "\n"; if (!strcasecmp(key.c_str(), "Content-Range")) { uint64_t rmin, rmax, elen = 0; /* HTTP/1.1 says "Content-Range: bytes X-Y/Z" * but traditional Receiver servers send * "Content-Range: bytes=X-Y" */ if (util::Scanf64(value.c_str(), "bytes %llu-%llu/%llu", &rmin, &rmax, &elen) == 3 || util::Scanf64(value.c_str(), "bytes=%llu-%llu/%llu", &rmin, &rmax, &elen) == 3 || util::Scanf64(value.c_str(), "bytes %llu-%llu", &rmin, &rmax) == 2 || util::Scanf64(value.c_str(), "bytes=%llu-%llu", &rmin, &rmax) == 2) { if (elen) m_len = elen; else m_len = rmax + 1; got_range = true; } } else if (!strcasecmp(key.c_str(), "Content-Length")) { util::Scanf64(value.c_str(), "%llu", &clen); } } if (!got_range) m_len = clen; if (is_error) { std::unique_ptr<util::Stream> epage(CreatePartialStream(&m_socket, 0, clen)); StringStream ssp; CopyStream(epage.get(), &ssp); TRACE << "HTTP error page: " << ssp.str() << "\n"; return EINVAL; } m_need_fetch = false; m_last_pos = pos; lr.ReadLeftovers(buffer, len, pread); if (*pread) { m_last_pos += *pread; return 0; } } unsigned int rc = m_socket.Read(buffer, len, pread); if (!rc) { m_last_pos += *pread; LOG(HTTP) << "hs" << this << " socket read " << *pread << " bytes\n"; } else { LOG(HTTP) << "hs" << this << " socket read error " << rc << "\n"; } return rc; }
void PCLoaderVisum::load(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, PCTypeMap& tm) { GeoConvHelper& geoConvHelper = GeoConvHelper::getProcessing(); std::string what; std::map<long, Position> punkte; std::map<long, PositionVector> kanten; std::map<long, PositionVector> teilflaechen; std::map<long, long> flaechenelemente; NamedColumnsParser lineParser; LineReader lr(file); while (lr.hasMore()) { std::string line = lr.readLine(); // reset if current is over if (line.length() == 0 || line[0] == '*' || line[0] == '$') { what = ""; } // read items if (what == "$PUNKT") { lineParser.parseLine(line); long id = TplConvert<char>::_2long(lineParser.get("ID").c_str()); SUMOReal x = TplConvert<char>::_2SUMOReal(lineParser.get("XKOORD").c_str()); SUMOReal y = TplConvert<char>::_2SUMOReal(lineParser.get("YKOORD").c_str()); Position pos(x, y); if (!geoConvHelper.x2cartesian(pos)) { WRITE_WARNING("Unable to project coordinates for point '" + toString(id) + "'."); } punkte[id] = pos; continue; } else if (what == "$KANTE") { lineParser.parseLine(line); long id = TplConvert<char>::_2long(lineParser.get("ID").c_str()); long fromID = TplConvert<char>::_2long(lineParser.get("VONPUNKTID").c_str()); long toID = TplConvert<char>::_2long(lineParser.get("NACHPUNKTID").c_str()); PositionVector vec; vec.push_back(punkte[fromID]); vec.push_back(punkte[toID]); kanten[id] = vec; continue; } else if (what == "$ZWISCHENPUNKT") { lineParser.parseLine(line); long id = TplConvert<char>::_2long(lineParser.get("KANTEID").c_str()); int index = TplConvert<char>::_2int(lineParser.get("INDEX").c_str()); SUMOReal x = TplConvert<char>::_2SUMOReal(lineParser.get("XKOORD").c_str()); SUMOReal y = TplConvert<char>::_2SUMOReal(lineParser.get("YKOORD").c_str()); Position pos(x, y); if (!geoConvHelper.x2cartesian(pos)) { WRITE_WARNING("Unable to project coordinates for edge '" + toString(id) + "'."); } kanten[id].insertAt(index, pos); continue; } else if (what == "$TEILFLAECHENELEMENT") { lineParser.parseLine(line); long id = TplConvert<char>::_2long(lineParser.get("TFLAECHEID").c_str()); int index = TplConvert<char>::_2int(lineParser.get("INDEX").c_str()); index = 0; /// hmmmm - assume it's sorted... long kid = TplConvert<char>::_2long(lineParser.get("KANTEID").c_str()); int dir = TplConvert<char>::_2int(lineParser.get("RICHTUNG").c_str()); if (teilflaechen.find(id) == teilflaechen.end()) { teilflaechen[id] = PositionVector(); } if (dir == 0) { for (int i = 0; i < (int) kanten[kid].size(); ++i) { teilflaechen[id].push_back_noDoublePos(kanten[kid][i]); } } else { for (int i = (int) kanten[kid].size() - 1; i >= 0; --i) { teilflaechen[id].push_back_noDoublePos(kanten[kid][i]); } } continue; } else if (what == "$FLAECHENELEMENT") { lineParser.parseLine(line); long id = TplConvert<char>::_2long(lineParser.get("FLAECHEID").c_str()); long tid = TplConvert<char>::_2long(lineParser.get("TFLAECHEID").c_str()); int enklave = TplConvert<char>::_2int(lineParser.get("ENKLAVE").c_str()); // !!! unused enklave = 0; flaechenelemente[id] = tid; continue; } // set if read if (line[0] == '$') { what = ""; if (line.find("$PUNKT") == 0) { what = "$PUNKT"; } else if (line.find("$KANTE") == 0) { what = "$KANTE"; } else if (line.find("$ZWISCHENPUNKT") == 0) { what = "$ZWISCHENPUNKT"; } else if (line.find("$TEILFLAECHENELEMENT") == 0) { what = "$TEILFLAECHENELEMENT"; } else if (line.find("$FLAECHENELEMENT") == 0) { what = "$FLAECHENELEMENT"; } if (what != "") { lineParser.reinit(line.substr(what.length() + 1)); } } } // do some more sane job... RGBColor c = RGBColor::parseColor(oc.getString("color")); std::map<std::string, std::string> typemap; // load the pois/polys lr.reinit(); bool parsingCategories = false; bool parsingPOIs = false; bool parsingDistrictsDirectly = false; PositionVector vec; std::string polyType, lastID; bool first = true; while (lr.hasMore()) { std::string line = lr.readLine(); // do not parse empty lines if (line.length() == 0) { continue; } // do not parse comment lines if (line[0] == '*') { continue; } if (line[0] == '$') { // reset parsing on new entry type parsingCategories = false; parsingPOIs = false; parsingDistrictsDirectly = false; polyType = ""; } if (parsingCategories) { // parse the category StringTokenizer st(line, ";"); std::string catid = st.next(); std::string catname = st.next(); typemap[catid] = catname; } if (parsingPOIs) { // parse the poi // $POI:Nr;CATID;CODE;NAME;Kommentar;XKoord;YKoord; StringTokenizer st(line, ";"); std::string num = st.next(); std::string catid = st.next(); std::string code = st.next(); std::string name = st.next(); std::string comment = st.next(); std::string xpos = st.next(); std::string ypos = st.next(); // process read values SUMOReal x = TplConvert<char>::_2SUMOReal(xpos.c_str()); SUMOReal y = TplConvert<char>::_2SUMOReal(ypos.c_str()); Position pos(x, y); if (!geoConvHelper.x2cartesian(pos)) { WRITE_WARNING("Unable to project coordinates for POI '" + num + "'."); } std::string type = typemap[catid]; // check the poi name = num; // patch the values bool discard = oc.getBool("discard"); int layer = oc.getInt("layer"); RGBColor color; if (tm.has(type)) { const PCTypeMap::TypeDef& def = tm.get(type); name = def.prefix + name; type = def.id; color = RGBColor::parseColor(def.color); discard = def.discard; layer = def.layer; } else { name = oc.getString("prefix") + name; type = oc.getString("type"); color = c; } if (!discard) { PointOfInterest* poi = new PointOfInterest(name, type, pos, color); if (!toFill.insert(name, poi, layer)) { WRITE_ERROR("POI '" + name + "' could not been added."); delete poi; } } } // poly if (polyType != "") { StringTokenizer st(line, ";"); std::string id = st.next(); std::string type; if (!first && lastID != id) { // we have parsed a polygon completely RGBColor color; int layer = oc.getInt("layer"); bool discard = oc.getBool("discard"); if (tm.has(polyType)) { const PCTypeMap::TypeDef& def = tm.get(polyType); id = def.prefix + id; type = def.id; color = RGBColor::parseColor(def.color); discard = def.discard; layer = def.layer; } else { id = oc.getString("prefix") + id; type = oc.getString("type"); color = c; } if (!discard) { Polygon* poly = new Polygon(id, type, color, vec, false); if (!toFill.insert(id, poly, 1)) { WRITE_ERROR("Polygon '" + id + "' could not been added."); delete poly; } } vec.clear(); } lastID = id; first = false; // parse current poly std::string index = st.next(); std::string xpos = st.next(); std::string ypos = st.next(); Position pos2D((SUMOReal) atof(xpos.c_str()), (SUMOReal) atof(ypos.c_str())); if (!geoConvHelper.x2cartesian(pos2D)) { WRITE_WARNING("Unable to project coordinates for polygon '" + id + "'."); } vec.push_back(pos2D); } // district refering a shape if (parsingDistrictsDirectly) { //$BEZIRK:NR CODE NAME TYPNR XKOORD YKOORD FLAECHEID BEZART IVANTEIL_Q IVANTEIL_Z OEVANTEIL METHODEANBANTEILE ZWERT1 ZWERT2 ZWERT3 ISTINAUSWAHL OBEZNR NOM_COM COD_COM StringTokenizer st(line, ";"); std::string num = st.next(); std::string code = st.next(); std::string name = st.next(); st.next(); // typntr std::string xpos = st.next(); std::string ypos = st.next(); long id = TplConvert<char>::_2long(st.next().c_str()); // patch the values std::string type = "district"; name = num; bool discard = oc.getBool("discard"); int layer = oc.getInt("layer"); RGBColor color; if (tm.has(type)) { const PCTypeMap::TypeDef& def = tm.get(type); name = def.prefix + name; type = def.id; color = RGBColor::parseColor(def.color); discard = def.discard; layer = def.layer; } else { name = oc.getString("prefix") + name; type = oc.getString("type"); color = c; } if (!discard) { if (teilflaechen[flaechenelemente[id]].size() > 0) { Polygon* poly = new Polygon(name, type, color, teilflaechen[flaechenelemente[id]], false); if (!toFill.insert(name, poly, layer)) { WRITE_ERROR("Polygon '" + name + "' could not been added."); delete poly; } } else { SUMOReal x = TplConvert<char>::_2SUMOReal(xpos.c_str()); SUMOReal y = TplConvert<char>::_2SUMOReal(ypos.c_str()); Position pos(x, y); if (!geoConvHelper.x2cartesian(pos)) { WRITE_WARNING("Unable to project coordinates for POI '" + name + "'."); } PointOfInterest* poi = new PointOfInterest(name, type, pos, color); if (!toFill.insert(name, poi, layer)) { WRITE_ERROR("POI '" + name + "' could not been added."); delete poi; } } } } if (line.find("$POIKATEGORIEDEF:") == 0 || line.find("$POIKATEGORIE:") == 0) { // ok, got categories, begin parsing from next line parsingCategories = true; } if (line.find("$POI:") == 0) { // ok, got pois, begin parsing from next line parsingPOIs = true; } if (line.find("$BEZIRK") == 0 && line.find("FLAECHEID") != std::string::npos) { // ok, have a district header, and it seems like districts would reference shapes... parsingDistrictsDirectly = true; } if (line.find("$BEZIRKPOLY") != std::string::npos) { polyType = "district"; } if (line.find("$GEBIETPOLY") != std::string::npos) { polyType = "area"; } } }
//=========================================================================== ScriptRef* ScriptInt::script_op(const ScriptAuth& auth, const ScriptRef& ref, const ScriptOp& op, const ScriptRef* right) { if (right) { // binary ops const ScriptInt* rnum = dynamic_cast<const ScriptInt*> (right->object()); if (rnum) { // Int x Int ops int rvalue = rnum->get_int(); switch (op.type()) { case ScriptOp::Add: return ScriptInt::new_ref(m_value + rvalue); case ScriptOp::Subtract: return ScriptInt::new_ref(m_value - rvalue); case ScriptOp::Multiply: return ScriptInt::new_ref(m_value * rvalue); case ScriptOp::Divide: if (rvalue != 0) { return ScriptInt::new_ref(m_value / rvalue); } else { return ScriptError::new_ref("Divide by zero"); } case ScriptOp::Power: return ScriptInt::new_ref((int)pow(m_value,rvalue)); case ScriptOp::Modulus: if (rvalue != 0) { return ScriptInt::new_ref(m_value % rvalue); } else { return ScriptError::new_ref("Divide by zero"); } case ScriptOp::BitOr: return ScriptInt::new_ref(m_value | rvalue); case ScriptOp::BitXor: return ScriptInt::new_ref(m_value ^ rvalue); case ScriptOp::BitAnd: return ScriptInt::new_ref(m_value & rvalue); case ScriptOp::LeftShift: return ScriptInt::new_ref(m_value << rvalue); case ScriptOp::RightShift: return ScriptInt::new_ref(m_value >> rvalue); case ScriptOp::Assign: if (!ref.is_const()) { m_value = rvalue; } return ref.ref_copy(); case ScriptOp::AddAssign: if (!ref.is_const()) { m_value += rvalue; } return ref.ref_copy(); case ScriptOp::SubtractAssign: if (!ref.is_const()) { m_value -= rvalue; } return ref.ref_copy(); case ScriptOp::MultiplyAssign: if (!ref.is_const()) { m_value *= rvalue; } return ref.ref_copy(); case ScriptOp::DivideAssign: if (!ref.is_const()) { m_value /= rvalue; } return ref.ref_copy(); default: break; } } else if (dynamic_cast<const ScriptReal*>(right->object())) { // Promote to real and use real ops ScriptReal lr((double)m_value); return lr.script_op(auth,ref,op,right); } } else { // prefix or postfix ops
int main(int argc, char** argv){ time_t currentTime = time(0); fprintf(stderr, "Analysis started at: %s", ctime(¤tTime)); //////////////////////////////////////////////// BEGIN_PARAMETER_LIST(pl) ADD_PARAMETER_GROUP(pl, "Input/Output") ADD_STRING_PARAMETER(pl, inVcf, "--inVcf", "input VCF File") ADD_STRING_PARAMETER(pl, snp, "--snp", "input dbSNP File (.rod)") ADD_STRING_PARAMETER(pl, hapmap, "--hapmap", "input HapMap File (.bim)") ADD_PARAMETER_GROUP(pl, "Site Filter") ADD_STRING_PARAMETER(pl, rangeList, "--rangeList", "Specify some ranges to use, please use chr:begin-end format.") ADD_STRING_PARAMETER(pl, rangeFile, "--rangeFile", "Specify the file containing ranges, please use chr:begin-end format.") END_PARAMETER_LIST(pl) ; pl.Read(argc, argv); pl.Status(); if (FLAG_REMAIN_ARG.size() > 0){ fprintf(stderr, "Unparsed arguments: "); for (unsigned int i = 0; i < FLAG_REMAIN_ARG.size(); i++){ fprintf(stderr, " %s", FLAG_REMAIN_ARG[i].c_str()); } fprintf(stderr, "\n"); abort(); } REQUIRE_STRING_PARAMETER(FLAG_inVcf, "Please provide input file using: --inVcf"); const char defaultDbSnp[] = "/net/fantasia/home/zhanxw/amd/data/umake-resources/dbSNP/dbsnp_129_b37.rod.map"; if (FLAG_snp == "") { FLAG_snp = defaultDbSnp; fprintf(stderr, "Use default dbsnp: [ %s ]\n", defaultDbSnp); } SiteSet snpSet; snpSet.loadRodFile(FLAG_snp); fprintf(stderr, "%zu dbSNP sites loaded.\n", snpSet.getTotalSite()); const char defaultHM3[] = "/net/fantasia/home/zhanxw/amd/data/umake-resources/HapMap3/hapmap3_r3_b37_fwd.consensus.qc.poly.bim"; if (FLAG_hapmap == "") { FLAG_hapmap = defaultHM3; fprintf(stderr, "Use default HapMap: [ %s ]\n", defaultHM3); } SiteSet hmSet; hmSet.loadBimFile(FLAG_hapmap); fprintf(stderr, "%zu Hapmap sites loaded.\n", hmSet.getTotalSite()); const char* fn = FLAG_inVcf.c_str(); LineReader lr(fn); // // set range filters here // // e.g. // // vin.setRangeList("1:69500-69600"); // vin.setRangeList(FLAG_rangeList.c_str()); // vin.setRangeFile(FLAG_rangeFile.c_str()); std::map<std::string, Variant> freq; std::string chrom; int pos; // std::string filt; std::string anno; char ref, alt; bool inDbSnp; bool inHapmap; int lineNo = 0; std::vector<std::string> fd; while(lr.readLineBySep(&fd, " \t")){ lineNo ++; if (fd[0][0] == '#') continue; // skip header chrom = fd[0]; // ref is on column 0 (0-based) pos = atoi(fd[1]); // ref is on column 1 (0-based) ref = fd[3][0]; // ref is on column 3 (0-based) alt = fd[4][0]; // ref is on column 4 (0-based) // filt = fd[6]; // filt is on column 6 (0-based) anno = extractAnno(fd[7]); // info is on column 7 (0-based), we will extract ANNO= inDbSnp = snpSet.isIncluded(chrom.c_str(), pos); inHapmap = hmSet.isIncluded(chrom.c_str(), pos); Variant& v = freq[anno]; v.total++; if ( isTs(ref, alt) ) { v.ts ++; if (inDbSnp) { v.tsInDbSnp ++; v.dbSnp ++; } } else if (isTv(ref, alt)) { v.tv ++; if (inDbSnp) { v.tvInDbSnp ++; v.dbSnp ++; } }; if (inHapmap) v.hapmap ++; if (lineNo % 10000 == 0) { fprintf(stderr, "\rProcessed %d lines...\r", lineNo); } }; fprintf(stdout, "Total %d VCF records have been read successfully\n", lineNo); ////////////////////////////////////////////////////////////////////// std::string title = "Summarize per annotation type"; int pad = (170 - title.size() ) /2 ; std::string outTitle = std::string(pad, '-') + title + std::string(pad, '-'); puts(outTitle.c_str()); printf("%40s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\n", "Filter", "#SNPs", "#dbSNP", "%dbSNP", "Known Ts/Tv", "Novel Ts/Tv", "Overall", "%TotalHM3", "%HMCalled"); std::map<std::string, Variant> indvFreq; Variant total; for (std::map<std::string, Variant>::iterator i = freq.begin() ; i != freq.end(); ++i ){ i->second.print(i->first, hmSet); total += i->second; }; total.print("TOTAL", hmSet); currentTime = time(0); fprintf(stderr, "Analysis end at: %s", ctime(¤tTime)); return 0; };
void PCLoaderDlrNavteq::loadPOIFile(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, PCTypeMap& tm) { // get the defaults RGBColor c = RGBColor::parseColor(oc.getString("color")); // parse int l = 0; LineReader lr(file); while (lr.hasMore()) { std::string line = lr.readLine(); ++l; // skip invalid/empty lines if (line.length() == 0 || line.find("#") != std::string::npos) { continue; } if (StringUtils::prune(line) == "") { continue; } // parse the poi std::istringstream stream(line); // attributes of the poi std::string name, skip, type, desc; std::getline(stream, name, '\t'); std::getline(stream, skip, '\t'); std::getline(stream, type, '\t'); std::getline(stream, desc, '\t'); if (stream.fail()) { throw ProcessError("Invalid dlr-navteq-poi in line " + toString(l) + ":\n" + line); } double x, y; stream >> x; if (stream.fail()) { throw ProcessError("Invalid x coordinate for POI '" + name + "'."); } stream >> y; if (stream.fail()) { throw ProcessError("Invalid y coordinate for POI '" + name + "'."); } Position pos(x, y); // check the poi if (name == "") { throw ProcessError("The name of a POI is missing."); } if (!GeoConvHelper::getProcessing().x2cartesian(pos, true)) { throw ProcessError("Unable to project coordinates for POI '" + name + "'."); } // patch the values bool discard = oc.getBool("discard"); int layer = oc.getInt("layer"); RGBColor color; if (tm.has(type)) { const PCTypeMap::TypeDef& def = tm.get(type); name = def.prefix + name; type = def.id; color = def.color; discard = def.discard; layer = def.layer; } else { name = oc.getString("prefix") + name; type = oc.getString("type"); color = c; } if (!discard) { bool ignorePrunning = false; if (OptionsCont::getOptions().isInStringVector("prune.keep-list", name)) { ignorePrunning = true; } PointOfInterest* poi = new PointOfInterest(name, type, color, pos, (SUMOReal)layer); toFill.insert(name, poi, layer, ignorePrunning); } } }
int main(int argc, char** argv) { time_t currentTime = time(0); fprintf(stderr, "Analysis started at: %s", ctime(¤tTime)); PARSE_PARAMETER(argc, argv); PARAMETER_STATUS(); if (FLAG_REMAIN_ARG.size() > 0) { fprintf(stderr, "Unparsed arguments: "); for (unsigned int i = 0; i < FLAG_REMAIN_ARG.size(); i++) { fprintf(stderr, " %s", FLAG_REMAIN_ARG[i].c_str()); } fprintf(stderr, "\n"); abort(); } REQUIRE_STRING_PARAMETER(FLAG_inVcf, "Please provide input file using: --inVcf"); const char defaultDbSnp[] = "/net/fantasia/home/zhanxw/amd/data/umake-resources/dbSNP/" "dbsnp_129_b37.rod.map"; if (FLAG_snp == "") { FLAG_snp = defaultDbSnp; fprintf(stderr, "Use default dbsnp: [ %s ]\n", defaultDbSnp); } SiteSet snpSet; snpSet.loadRodFile(FLAG_snp); fprintf(stderr, "%zu dbSNP sites loaded.\n", snpSet.getTotalSite()); const char defaultHM3[] = "/net/fantasia/home/zhanxw/amd/data/umake-resources/HapMap3/" "hapmap3_r3_b37_fwd.consensus.qc.poly.bim"; if (FLAG_hapmap == "") { FLAG_hapmap = defaultHM3; fprintf(stderr, "Use default HapMap: [ %s ]\n", defaultHM3); } SiteSet hmSet; hmSet.loadBimFile(FLAG_hapmap); fprintf(stderr, "%zu Hapmap sites loaded.\n", hmSet.getTotalSite()); const char* fn = FLAG_inVcf.c_str(); LineReader lr(fn); // // set range filters here // // e.g. // // vin.setRangeList("1:69500-69600"); // vin.setRangeList(FLAG_rangeList.c_str()); // vin.setRangeFile(FLAG_rangeFile.c_str()); std::map<std::string, Variant> freq; std::string chrom; int pos; std::string filt; char ref, alt; bool inDbSnp; bool inHapmap; int lineNo = 0; std::vector<std::string> fd; while (lr.readLineBySep(&fd, " \t")) { lineNo++; if (fd[0][0] == '#') continue; // skip header chrom = fd[0]; // ref is on column 0 (0-based) pos = atoi(fd[1]); // ref is on column 1 (0-based) ref = fd[3][0]; // ref is on column 3 (0-based) alt = fd[4][0]; // ref is on column 4 (0-based) filt = fd[6]; // filt is on column 6 (0-based) inDbSnp = snpSet.isIncluded(chrom.c_str(), pos); inHapmap = hmSet.isIncluded(chrom.c_str(), pos); Variant& v = freq[filt]; v.total++; if (isTs(ref, alt)) { v.ts++; if (inDbSnp) { v.tsInDbSnp++; v.dbSnp++; } } else if (isTv(ref, alt)) { v.tv++; if (inDbSnp) { v.tvInDbSnp++; v.dbSnp++; } }; if (inHapmap) v.hapmap++; }; fprintf(stdout, "Total %d VCF records have converted successfully\n", lineNo); ////////////////////////////////////////////////////////////////////// std::string title = "Summarize per combined filter"; int pad = (170 - title.size()) / 2; std::string outTitle = std::string(pad, '-') + title + std::string(pad, '-'); puts(outTitle.c_str()); printf("%40s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\n", "Filter", "#SNPs", "#dbSNP", "%dbSNP", "Known Ts/Tv", "Novel Ts/Tv", "Overall", "%TotalHM3", "%HMCalled"); std::map<std::string, Variant> indvFreq; Variant pass; Variant fail; Variant total; std::vector<std::string> filters; // individual filter for (std::map<std::string, Variant>::iterator i = freq.begin(); i != freq.end(); ++i) { const std::string& filt = i->first; const Variant& v = i->second; v.print(filt, hmSet); // calculate indvFreq, pass, fail and total stringTokenize(filt, ';', &filters); for (unsigned int j = 0; j < filters.size(); j++) { const std::string& filt = filters[j]; indvFreq[filt] += v; } if (filt == "PASS") pass += v; else fail += v; total += v; }; ////////////////////////////////////////////////////////////////////// title = "Summarize per individual filter"; pad = (170 - title.size()) / 2; outTitle = std::string(pad, '-') + title + std::string(pad, '-'); puts(outTitle.c_str()); printf("%40s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\n", "Filter", "#SNPs", "#dbSNP", "%dbSNP", "Known Ts/Tv", "Novel Ts/Tv", "Overall", "%TotalHM3", "%HMCalled"); for (std::map<std::string, Variant>::iterator i = indvFreq.begin(); i != indvFreq.end(); ++i) { const std::string& filt = i->first; const Variant& v = i->second; v.print(filt, hmSet); } ////////////////////////////////////////////////////////////////////// title = "Summarize per pass/fail filter"; pad = (170 - title.size()) / 2; outTitle = std::string(pad, '-') + title + std::string(pad, '-'); puts(outTitle.c_str()); printf("%40s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\t%10s\n", "Filter", "#SNPs", "#dbSNP", "%dbSNP", "Known Ts/Tv", "Novel Ts/Tv", "Overall", "%TotalHM3", "%HMCalled"); pass.print("PASS", hmSet); fail.print("FAIL", hmSet); total.print("TOTAL", hmSet); currentTime = time(0); fprintf(stderr, "Analysis end at: %s", ctime(¤tTime)); return 0; };
float Ship::iE(){ float c1 = - pow(v.Lpp / v.B, 0.80856) * pow(1 - Cw(), 0.30484) * pow(1 - Cp() - 0.0225 * lcb(), 0.6367) * pow(lr() / v.B, 0.34574) * pow(100 * Vol() / pow(v.Lpp, 3.), 0.16302); return 1 + 89 * exp(c1); }
int main(int argc, char** argv) { ros::init(argc, argv, "base_planner_node", ros::init_options::NoSigintHandler); signal(SIGINT, ctrl_C_Handler); ros::NodeHandle nh; tf::TransformListener lr(ros::Duration(3)); listener = &lr; ros::ServiceClient controller_srv_client = nh.serviceClient<std_srvs::SetBool>("controller_cmd"); ros::ServiceServer set_position = nh.advertiseService("give_goal", giveGoal); ros::param::param<double>("~time_step" , path_t_step , 0.1); ros::param::param<double>("~target_speed", target_speed, 0.01); ros::param::param<double>("~target_accel", target_accel, 0.02); ros::param::param<double>("~probe_offset", probe_offset, 0.525); ros::Duration time_step(path_t_step); ros::Subscriber cmd_pose_sub = nh.subscribe("/move_base_simple/goal", 1, moveBaseSimpleCallback); ros::Subscriber phase_space_sub = nh.subscribe("map_to_cepheus", 1, PhaseSpaceCallback); ros::Publisher path_pub = nh.advertise<nav_msgs::Path>("path", 1000); geometry_msgs::PoseStamped cmd_pos; geometry_msgs::TwistStamped cmd_vel; cmd_pos.header.frame_id = "drogue"; cmd_vel.header.frame_id = "drogue"; geometry_msgs::Vector3 cmd_acc; ros::Publisher pos_pub = nh.advertise<geometry_msgs::PoseStamped>("planner_pos", 1); ros::Publisher vel_pub = nh.advertise<geometry_msgs::TwistStamped>("planner_vel", 1); ros::Publisher acc_pub = nh.advertise<geometry_msgs::Vector3>("planner_acc", 1); bool path_running=false; int cnt; while(!g_request_shutdown) { if (new_path) { ROS_INFO("New Path calculated"); new_path=false; path_running=true; cnt = 0; //path_pub.publish(path); //request to enable controller std_srvs::SetBool srv; srv.request.data = true; if (controller_srv_client.call(srv)) { ROS_INFO_STREAM("Controller response: " << srv.response.message); } else{ ROS_ERROR("Failed to call Controller"); } } if(path_running) { cmd_pos.pose.position.x = path_matrix(0,cnt); cmd_pos.pose.position.y = path_matrix(1,cnt); cmd_pos.pose.position.z =0.0; cmd_pos.pose.orientation = tf::createQuaternionMsgFromYaw(path_matrix(2,cnt)); cmd_vel.twist.linear.x = path_matrix(3,cnt); cmd_vel.twist.linear.y = path_matrix(4,cnt); cmd_vel.twist.angular.z = path_matrix(5,cnt); cmd_acc.x = path_matrix(6,cnt); cmd_acc.y = path_matrix(7,cnt); cmd_acc.z = path_matrix(8,cnt); pos_pub.publish(cmd_pos); vel_pub.publish(cmd_vel); acc_pub.publish(cmd_acc); cnt++; if(cnt >= path_matrix.cols()) { path_running = false; //request to disable controller std_srvs::SetBool srv; srv.request.data = false; if (controller_srv_client.call(srv)) { ROS_INFO_STREAM("Controller response: " << srv.response.message); } else{ ROS_ERROR("Failed to call Controller"); } } } ros::spinOnce(); //wait one time step time_step.sleep(); } return 0; }
//#define GHOSTS void NodeBase::operator()(Invalid& invalid,Window& window,Display* display,GC& gc,Pixmap& bitmap) { XSetForeground(display,gc,0X777777); while(!linecovers.empty()) { pointpairs p(linecovers); XDrawLine(display,bitmap,gc,p.first.first,p.first.second,p.second.first,p.second.second); } SetFont(display,gc); //invalid.SetTrace(true); moved=false; pair<double,double> D(motion.next(X,Y)); if ((D.first) or (D.second)) moved=true; { pair<double,double> ul(X-(DCW/2)-1,Y-(DCH/2)-1); pair<double,double> lr(ul.first+DCW+2,ul.second+DCH+2); Rect iv(ul.first,ul.second,lr.first,lr.second); #ifdef GHOSTS if (Remove) if (Removing<0X88) {Removed=true; return;} invalid.insert(iv); #else invalid.expand(iv); #endif if (Remove) { if (Removing<=0X77) { Removed=true; moved=false; XSetForeground(display,gc,0X777777); } else { unsigned long color((Removing<<0) | (Removing<<8) | (Removing)); moved=true; XSetForeground(display,gc,color); } XPoint& points(iv); XFillPolygon(display,bitmap, gc,&points, 4, Complex, CoordModeOrigin); if (!Removed) { XSetForeground(display,gc,0XFFFFFF); int yoff(CH); XDrawString(display,bitmap,gc,ul.first,ul.second+yoff-2,text.c_str(),text.size()); } Removing-=10; return; } } DCH=CH+(size()*CH); DCW=CW; if (size()) DCW=CW*2; X+=D.first; Y+=D.second; { pair<double,double> ul(X-(DCW/2),Y-(DCH/2)); pair<double,double> lr(ul.first+DCW,ul.second+DCH); Rect iv(ul.first,ul.second,lr.first,lr.second); #ifdef GHOSTS invalid.insert(iv); #else invalid.expand(iv); #endif XSetForeground(display,gc,0XFFFFFF); XPoint& points(iv); XPoint* pt=&points; //for (int j=0;j<4;j++,pt++) lastpoints.push_back(*pt); XSetForeground(display,gc,color); XFillPolygon(display,bitmap, gc,&points, 4, Complex, CoordModeOrigin); XSetForeground(display,gc,0XFFFFFF); int yoff(CH); XDrawString(display,bitmap,gc,ul.first,ul.second+yoff-2,text.c_str(),text.size()); for (iterator it=begin();it!=end();it++) { yoff+=CH; stringstream ss; ss<<it->first<<" : "<<it->second; XDrawString(display,bitmap,gc,ul.first,ul.second+yoff-2,ss.str().c_str(),ss.str().size()); } { XSetForeground(display,gc,(Remove or (!parented) ) ? 0X777777 : 0XAAAACC); XDrawLine(display,bitmap,gc,X,Y,PX,PY); linecovers(X,Y,PX,PY); } } }
/** * Extract covaraite from file @param fn. * Only samples included in @param includedSample will be processed * If some samples appear more than once, only the first appearance will be * readed * Only covaraites provided in @param covNameToUse will be included * Missing values will be imputed to the mean columnwise. * Result will be put to @param mat (sample by covariate) and @param * sampleToDrop * @return number of sample loaded (>=0); or a minus number meaning error * @param sampleToDrop: store samples that are not found in covariate. */ int extractCovariate(const std::string& fn, const std::vector<std::string>& sampleToInclude, const std::vector<std::string>& covNameToUse, DataLoader::HandleMissingCov handleMissingCov, SimpleMatrix* mat, std::set<std::string>* sampleToDrop) { std::set<std::string> includeSampleSet; makeSet(sampleToInclude, &includeSampleSet); if (includeSampleSet.size() != sampleToInclude.size()) { logger->warn( "Some samples have appeared more than once, and we record covariate " "for its first appearance"); } std::vector<std::string> noPhenotypeSample; std::map<std::string, int> processed; // record how many times a sample is processed std::set<std::pair<int, int> > missing; // record which number is covaraite is missing. int missingCovariateWarning = 0; // record how many times a missing warning is geneated. bool missingValueInLine; // record whether there is missing value in the // line int missingLines = 0; // record how many lines has missing values std::vector<int> columnToExtract; std::vector<std::string> extractColumnName; std::vector<std::string> fd; LineReader lr(fn); int lineNo = 0; int fieldLen = 0; while (lr.readLineBySep(&fd, "\t ")) { ++lineNo; if (lineNo == 1) { // header line fieldLen = fd.size(); if (fieldLen < 2) { logger->error( "Insufficient column number (<2) in the first line of covariate " "file!"); return -1; }; if (tolower(fd[0]) != "fid" || tolower(fd[1]) != "iid") { logger->error("Covariate file header should begin with \"FID IID\"!"); return -1; } std::map<std::string, int> headerMap; makeMap(fd, &headerMap); if (fd.size() != headerMap.size()) { logger->error("Covariate file have duplicated header!"); return -1; } // specify which covariates to extract if (covNameToUse.size()) { for (size_t i = 0; i < covNameToUse.size(); ++i) { if (headerMap.count(covNameToUse[i]) == 0) { logger->error( "The covariate [ %s ] you specified cannot be found from " "covariate file!", covNameToUse[i].c_str()); continue; } columnToExtract.push_back(headerMap[covNameToUse[i]]); extractColumnName.push_back(covNameToUse[i]); } } else { for (size_t i = 2; i < fd.size(); ++i) { columnToExtract.push_back(headerMap[fd[i]]); extractColumnName.push_back(fd[i]); } } } else { // body lines if (fd.empty() || (fd[0].empty() && fd.size() == 1)) { // skip empty lines continue; } if ((int)fd.size() != fieldLen) { logger->error( "Inconsistent column number in covariate file line [ %d ] - skip " "this file!", lineNo); return -1; } if (includeSampleSet.find(fd[1]) == includeSampleSet.end()) { // does not have phenotype noPhenotypeSample.push_back(fd[1]); continue; }; processed[fd[1]]++; if (processed[fd[1]] > 1) { logger->info("Duplicate sample [ %s ] in covariate file, skipping", fd[1].c_str()); continue; }; int idx = (*mat).nrow(); (*mat).resize(idx + 1, columnToExtract.size()); (*mat).setRowName(idx, fd[1]); missingValueInLine = false; for (int i = 0; i < (int)columnToExtract.size(); ++i) { double d; if (str2double(fd[columnToExtract[i]], &d)) { (*mat)[idx][i] = d; } else { // found missing missingValueInLine = true; ++missingCovariateWarning; if (missingCovariateWarning <= 10) { if (handleMissingCov == DataLoader::COVARIATE_IMPUTE) { logger->warn( "Covariate file line [ %d ] has non-numerical value [ %s " "], " "we will impute to its mean", lineNo, fd[columnToExtract[i]].c_str()); } else if (handleMissingCov == DataLoader::COVARIATE_DROP) { logger->warn( "Covariate file line [ %d ] has non-numerical value [ %s " "], " "we will skip this sample", lineNo, fd[columnToExtract[i]].c_str()); } } (*mat)[idx][i] = 0.0; // will later be updated missing.insert(std::make_pair(idx, i)); }; } if (!missing.empty() && handleMissingCov == DataLoader::COVARIATE_DROP) { // drop row and row name (*mat).deleteRow((*mat).nrow() - 1); missing.clear(); } missingLines += missingValueInLine ? 1 : 0; } } if (missingCovariateWarning > 10) { if (handleMissingCov == DataLoader::COVARIATE_IMPUTE) { logger->warn( "Total [ %d ] lines in covariate file contain non-numerical " "values, " "we will impute these to their mean", missingLines); } else if (handleMissingCov == DataLoader::COVARIATE_DROP) { logger->warn( "Total [ %d ] lines in covariate file contain non-numerical " "values, " "we will skip these lines", missingLines); } } // output samples in covaraite but without phenotype for (size_t i = 0; i < noPhenotypeSample.size(); ++i) { if (i == 0) logger->warn( "Total [ %zu ] samples are skipped from covariate file due to " "missing phenotype", noPhenotypeSample.size()); if (i > 10) { logger->warn( "Skip outputting additional [ %d ] samples from covariate file " "with " "missing phenotypes", ((int)noPhenotypeSample.size() - 10)); break; } logger->warn( "Skip sample [ %s ] from covariate file due to missing phenotype", (noPhenotypeSample)[i].c_str()); } // set up labels for (size_t i = 0; i < extractColumnName.size(); ++i) { mat->setColName(i, extractColumnName[i]); } for (size_t i = 0; i < sampleToInclude.size(); i++) { if (processed.find(sampleToInclude[i]) == processed.end()) { logger->warn("Covariate file does not contain sample [ %s ]", sampleToInclude[i].c_str()); sampleToDrop->insert(sampleToInclude[i]); }; } if (handleMissingCov == DataLoader::COVARIATE_DROP) { assert(missing.empty()); return (*mat).nrow(); } // impute missing covariates to mean by column for (int col = 0; col < mat->ncol(); ++col) { double sum = 0; int nonZero = 0; for (int row = 0; row < (*mat).nrow(); ++row) { if (missing.count(std::make_pair(row, col))) continue; // missing sum += (*mat)[row][col]; ++nonZero; } if (nonZero == 0) { // all column are missing, drop column logger->info( "Covariate [ %s ] is missing for all samples. Exclude please " "before " "continue!", mat->getColName()[col].c_str()); return -1; } // some elements are missing double mean = sum / nonZero; for (int row = 0; row < (*mat).nrow(); ++row) { if (missing.count(std::make_pair(row, col))) { (*mat)[row][col] = mean; } } } return (*mat).nrow(); } // end extractCovariate
int main( int argc, char **argv ) { FILE* fin = NULL; FILE* fout= NULL; size_t line_len = 1024; char *line = new char[line_len]; bool show_input = false; bool show_slope = false; bool show_headers = false; int samples; if( argc == 3 ) { fin = stdin; fout= stdout; } else if( argc == 4 ) { fin = fopen( argv[1], "r" ); fout= stdout; } else if( argc > 5 ) { fin = fopen( argv[1], "r" ); fout= fopen( argv[2], "w" ); } else { printf( "%s : -[i = show input data too | s = show slope of curve | h = print headers ] -[number of samples]\n", argv[0] ); exit(-1); } if( argv[1][0] == '-' ) { int len = 0; if( (len = strlen( argv[1] ) ) > 1 ) { for( int i = len; i > 0; i-- ) { switch( argv[1][i] ) { case 'i': show_input = true; break; case 's': show_slope = true; break; case 'h': show_headers = true; break; } } } } if( argv[2][0] == '-' ) { int len = 0; if( (len = strlen( argv[1] ) ) > 1 ) { samples = atoi( &(argv[2][1]) ); } } linear_regression lr(samples); if( fin == NULL || fout == NULL ) exit(1); for( double x = 1.0; getline( &line, &line_len, fin ) >= 0; x += 1.0 ) { //fprintf( fout, "%f\n", atof(line) ); lr.log_entry( x, atof(line) ); lr.calc(); if( show_input && show_slope ) fprintf( fout, "%f,%f\n", atof(line), lr.calc(), lr.slope() ); else if( show_input ) fprintf( fout, "%f,%f\n", atof(line), lr.calc() ); else if( show_slope ) fprintf( fout, "%f,%f\n", lr.calc(), lr.slope() ); else fprintf( fout, "%f\n", lr.calc() ); } exit(0); }
/** * @return number of phenotypes read. -1 if errors * @param phenoCol, which phenotype column to use, similar to plink, it should * be the order of phenotype, e.g. phenoCol = 2, meaning the second phenotype * @param phenoName, which phenotype header to use. */ int loadPedPhenotypeByColumn(const char* fn, std::map<std::string, double>* p, int phenoCol) { if (phenoCol < 0) { logger->error("Phenotype column cannot be negative: [ %d ]", phenoCol); return -1; }; std::map<std::string, double>& pheno = *p; std::map<std::string, int> dup; // duplicates std::string line; std::vector<std::string> fd; LineReader lr(fn); int lineNo = 0; double v; int numMissingPhenotype = 0; while (lr.readLine(&line)) { stringNaturalTokenize(line, "\t ", &fd); ++lineNo; if ((int)fd.size() < 5 + phenoCol) { logger->warn("Skip line %d (short of columns) in phenotype file [ %s ]", lineNo, fn); continue; } if (toupper(fd[0]) == "FID" && toupper(fd[1]) == "IID") { if (lineNo == 1) { // skip header line continue; } else { logger->warn( "SKip line %d because the abnormal family and individual ids [ " "FID " "] and [ IID ]", lineNo); continue; } } std::string& pid = fd[1]; if (pheno.count(pid) == 0) { // check missing if (str2double(fd[5 + phenoCol - 1].c_str(), &v)) { pheno[pid] = v; } else { ++numMissingPhenotype; if (numMissingPhenotype <= 10) { logger->warn( "Skip: Missing or invalid phenotype type, skipping line %d [ " "%s " "] ... ", lineNo, line.c_str()); } continue; } } else { // logger->warn("line %s have duplicated id, skipped..", pid.c_str()); dup[pid]++; continue; } } if (numMissingPhenotype > 10) { logger->warn( "Skip: Additional [ %d ] lines have missing or invalid phenotype " "type", numMissingPhenotype - 10); } for (std::map<std::string, int>::iterator iter = dup.begin(); iter != dup.end(); ++iter) { logger->warn( "Sample [ %s ] removed from phenotype file [ %s ] for its duplicity " "[ " "%d ]", iter->first.c_str(), fn, iter->second + 1); pheno.erase(iter->first); }; return pheno.size(); };
void ViewPort::SetBoxes( void ) { // In the case where canvas rotation is applied, we need to define a larger "virtual" pixel window size to ensure that // enough chart data is fatched and available to fill the rotated screen. rv_rect = wxRect( 0, 0, pix_width, pix_height ); // Specify the minimum required rectangle in unrotated screen space which will supply full screen data after specified rotation if( ( g_bskew_comp && ( fabs( skew ) > .001 ) ) || ( fabs( rotation ) > .001 ) ) { double rotator = rotation; if(g_bskew_comp) rotator -= skew; int dy = wxRound( fabs( pix_height * cos( rotator ) ) + fabs( pix_width * sin( rotator ) ) ); int dx = wxRound( fabs( pix_width * cos( rotator ) ) + fabs( pix_height * sin( rotator ) ) ); // It is important for MSW build that viewport pixel dimensions be multiples of 4..... if( dy % 4 ) dy += 4 - ( dy % 4 ); if( dx % 4 ) dx += 4 - ( dx % 4 ); int inflate_x = wxMax(( dx - pix_width ) / 2, 0); int inflate_y = wxMax(( dy - pix_height ) / 2, 0); // Grow the source rectangle appropriately if( fabs( rotator ) > .001 ) rv_rect.Inflate( inflate_x, inflate_y ); } // Compute Viewport lat/lon reference points for co-ordinate hit testing // This must be done in unrotated space with respect to full unrotated screen space calculated above double rotation_save = rotation; SetRotationAngle( 0. ); wxPoint ul( rv_rect.x, rv_rect.y ), lr( rv_rect.x + rv_rect.width, rv_rect.y + rv_rect.height ); double dlat_min, dlat_max, dlon_min, dlon_max; bool hourglass = false; switch(m_projection_type) { case PROJECTION_TRANSVERSE_MERCATOR: case PROJECTION_STEREOGRAPHIC: case PROJECTION_GNOMONIC: hourglass = true; case PROJECTION_POLYCONIC: case PROJECTION_POLAR: case PROJECTION_ORTHOGRAPHIC: { double d; if( clat > 0 ) { // north polar wxPoint u( rv_rect.x + rv_rect.width/2, rv_rect.y ); wxPoint ur( rv_rect.x + rv_rect.width, rv_rect.y ); GetLLFromPix( ul, &d, &dlon_min ); GetLLFromPix( ur, &d, &dlon_max ); GetLLFromPix( lr, &dlat_min, &d ); GetLLFromPix( u, &dlat_max, &d ); if(fabs(fabs(d - clon) - 180) < 1) { // the pole is onscreen dlat_max = 90; dlon_min = -180; dlon_max = 180; } else if(wxIsNaN(dlat_max)) dlat_max = 90; if(hourglass) { // near equator, center may be less wxPoint l( rv_rect.x + rv_rect.width/2, rv_rect.y + rv_rect.height ); double dlat_min2; GetLLFromPix( l, &dlat_min2, &d ); dlat_min = wxMin(dlat_min, dlat_min2); } if(wxIsNaN(dlat_min)) // world is off-screen dlat_min = clat - 90; } else { // south polar wxPoint l( rv_rect.x + rv_rect.width/2, rv_rect.y + rv_rect.height ); wxPoint ll( rv_rect.x, rv_rect.y + rv_rect.height ); GetLLFromPix( ul, &dlat_max, &d ); GetLLFromPix( lr, &d, &dlon_max ); GetLLFromPix( ll, &d, &dlon_min ); GetLLFromPix( l, &dlat_min, &d ); if(fabs(fabs(d - clon) - 180) < 1) { // the pole is onscreen dlat_min = -90; dlon_min = -180; dlon_max = 180; } else if(wxIsNaN(dlat_min)) dlat_min = -90; if(hourglass) { // near equator, center may be less wxPoint u( rv_rect.x + rv_rect.width/2, rv_rect.y ); double dlat_max2; GetLLFromPix( u, &dlat_max2, &d ); dlat_max = wxMax(dlat_max, dlat_max2); } if(wxIsNaN(dlat_max)) // world is off-screen dlat_max = clat + 90; } if(wxIsNaN(dlon_min)) { // if neither pole is visible, but left and right of the screen are in space // we can avoid drawing the far side of the earth if(dlat_max < 90 && dlat_min > -90) { dlon_min = clon - 90 - fabs(clat); // this logic is not optimal, is it always correct? dlon_max = clon + 90 + fabs(clat); } else { dlon_min = -180; dlon_max = 180; } } } break; default: // works for mercator and equirectangular { GetLLFromPix( ul, &dlat_max, &dlon_min ); GetLLFromPix( lr, &dlat_min, &dlon_max ); } } if( clon < dlon_min ) dlon_min -= 360; else if(clon > dlon_max) dlon_max += 360; // Set the viewport lat/lon bounding box appropriately vpBBox.SetMin( dlon_min, dlat_min ); vpBBox.SetMax( dlon_max, dlat_max ); // Restore the rotation angle SetRotationAngle( rotation_save ); }
///////////////////////////////// // IntroScreen ///////////////////////////////// IntroScreen::IntroScreen() : GG::Wnd(GG::X0, GG::Y0, GG::GUI::GetGUI()->AppWidth(), GG::GUI::GetGUI()->AppHeight(), GG::Flags<GG::WndFlag>()), m_single_player(0), m_quick_start(0), m_multi_player(0), m_load_game(0), m_options(0), m_about(0), m_credits(0), m_exit_game(0), m_credits_wnd(0), m_menu(0), m_splash(0), m_logo(0), m_version(0) { m_menu = new CUIWnd(UserString("INTRO_WINDOW_TITLE"), GG::X1, GG::Y1, MAIN_MENU_WIDTH, MAIN_MENU_HEIGHT, GG::ONTOP | GG::INTERACTIVE); m_splash = new GG::StaticGraphic(GG::X0, GG::Y0, Width(), Height(), ClientUI::GetTexture(ClientUI::ArtDir() / "splash.png"), GG::GRAPHIC_FITGRAPHIC, GG::INTERACTIVE); m_logo = new GG::StaticGraphic(GG::X0, GG::Y0, Width(), Height() / 10, ClientUI::GetTexture(ClientUI::ArtDir() / "logo.png"), GG::GRAPHIC_FITGRAPHIC | GG::GRAPHIC_PROPSCALE); m_version = new GG::TextControl(GG::X0, GG::Y0, FreeOrionVersionString(), ClientUI::GetFont(), ClientUI::TextColor()); m_version->MoveTo(GG::Pt(Width() - m_version->Width(), Height() - m_version->Height())); AttachChild(m_splash); m_splash->AttachChild(m_logo); m_splash->AttachChild(m_menu); m_splash->AttachChild(m_version); //size calculation consts and variables const GG::X MIN_BUTTON_WIDTH(160); const GG::Y MIN_BUTTON_HEIGHT(40); const GG::X H_BUTTON_MARGIN(16); //horizontal empty space const GG::Y V_BUTTON_MARGIN(16); //vertical empty space GG::X button_width(0); //width of the buttons GG::Y button_height(0); //height of the buttons const GG::X H_MAINMENU_MARGIN(40); //horizontal empty space const GG::Y V_MAINMENU_MARGIN(40); //vertical empty space GG::X mainmenu_width(0); //width of the mainmenu GG::Y mainmenu_height(0); //height of the mainmenu //calculate necessary button width boost::shared_ptr<GG::Font> font = ClientUI::GetFont(); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_SINGLE_PLAYER")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_QUICK_START")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_MULTI_PLAYER")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_LOAD_GAME")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_OPTIONS")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_ABOUT")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_CREDITS")).x, button_width); button_width = std::max(font->TextExtent(UserString("INTRO_BTN_EXIT")).x, button_width); button_width += H_BUTTON_MARGIN; button_width = std::max(MIN_BUTTON_WIDTH, button_width); //calculate necessary button height button_height = std::max(MIN_BUTTON_HEIGHT, font->Height() + V_BUTTON_MARGIN); //culate window width and height mainmenu_width = button_width + H_MAINMENU_MARGIN; mainmenu_height = 8.75 * button_height + V_MAINMENU_MARGIN; // 8 rows + 0.75 before exit button // position menu window GG::Pt ul(Width() * GetOptionsDB().Get<double>("UI.main-menu.x") - mainmenu_width/2, Height() * GetOptionsDB().Get<double>("UI.main-menu.y") - mainmenu_height/2); GG::Pt lr(Width() * GetOptionsDB().Get<double>("UI.main-menu.x") + mainmenu_width/2, Height() * GetOptionsDB().Get<double>("UI.main-menu.y") + mainmenu_height/2); m_menu->SizeMove(ul, lr); //create buttons GG::Y button_y(12); //relativ buttonlocation GG::X button_x(15); m_single_player = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_SINGLE_PLAYER")); button_y += button_height; m_quick_start = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_QUICK_START")); button_y += button_height; m_multi_player = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_MULTI_PLAYER")); button_y += button_height; m_load_game = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_LOAD_GAME")); button_y += button_height; m_options = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_OPTIONS")); button_y += button_height; m_about = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_ABOUT")); button_y += button_height; m_credits = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_CREDITS")); button_y += 1.75 * button_height; m_exit_game = new CUIButton(button_x, button_y, button_width, UserString("INTRO_BTN_EXIT")); //attach buttons m_menu->AttachChild(m_single_player); m_menu->AttachChild(m_quick_start); m_menu->AttachChild(m_multi_player); m_menu->AttachChild(m_load_game); m_menu->AttachChild(m_options); m_menu->AttachChild(m_about); m_menu->AttachChild(m_credits); m_menu->AttachChild(m_exit_game); //connect signals and slots GG::Connect(m_single_player->ClickedSignal, &IntroScreen::OnSinglePlayer, this); GG::Connect(m_quick_start->ClickedSignal, &IntroScreen::OnQuickStart, this); GG::Connect(m_multi_player->ClickedSignal, &IntroScreen::OnMultiPlayer, this); GG::Connect(m_load_game->ClickedSignal, &IntroScreen::OnLoadGame, this); GG::Connect(m_options->ClickedSignal, &IntroScreen::OnOptions, this); GG::Connect(m_about->ClickedSignal, &IntroScreen::OnAbout, this); GG::Connect(m_credits->ClickedSignal, &IntroScreen::OnCredits, this); GG::Connect(m_exit_game->ClickedSignal, &IntroScreen::OnExitGame, this); }
int init_engine() { int x,y; int rays_size = RAYSX * RAYSY * sizeof(t_rayinfo); int ray_size = RAYSX * RAYSY * sizeof(t_raystate); int traverser_size = RAYSX * RAYSY * sizeof(t_traverserstate); int intersector_size = RAYSX * RAYSY * sizeof(t_intersectorstate); int framebuffer_size = RAYSX * RAYSY * sizeof(t_framebufferstate); int dispatcher_size = RAYSX * RAYSY * sizeof(t_dispatcherstate); Vector3f cdir, cup, cright; // alloc output_rayinfo output_rayinfo = (t_rayinfo*)malloc(rays_size); // alloc input_rayinfo input_rayinfo = (t_rayinfo*)malloc(rays_size); cdir = Vector3f(scene_camera->dir.x, scene_camera->dir.y, scene_camera->dir.z); cup = Vector3f(0,0,1); cright = cdir.Cross(cup); Matrix3f hrot; Matrix3f vrot; float hfov = scene_camera->fov.x; float vfov = scene_camera->fov.y; /* Matrix3f hrotpos; Matrix3f hrotneg; Matrix3f vrotpos; Matrix3f vrotneg; hrotpos.FromAxisAngle(cup, Mathf::DEG_TO_RAD*hfov); hrotneg.FromAxisAngle(cup, Mathf::DEG_TO_RAD*-hfov); vrotpos.FromAxisAngle(cright, Mathf::DEG_TO_RAD*vfov); vrotneg.FromAxisAngle(cright, Mathf::DEG_TO_RAD*-vfov); Vector3f ul = hrotneg*vrotneg*cdir; Vector3f ur = hrotpos*vrotneg*cdir; Vector3f ll = hrotneg*vrotpos*cdir; Vector3f lr = hrotpos*vrotpos*cdir; */ float front = 5; float w = (float)(tan(hfov*0.5)*front); float h = (float)(tan(vfov*0.5)*front); Vector3f tv(0, 0, -front); Vector3f ul(w, -h, -front); Vector3f ur(-w, -h, -front); Vector3f ll(w, h, -front); Vector3f lr(-w, h, -front); Quaternionf q(-scene_camera->quat.w, scene_camera->quat.x, scene_camera->quat.y, scene_camera->quat.z); tv = q * tv; ul = q * ul; ur = q * ur; ll = q * ll; lr = q * lr; Vector3f tul = Vector3f(scene_camera->pos.x, scene_camera->pos.y, scene_camera->pos.z) + ul;; Vector3f tur = Vector3f(scene_camera->pos.x, scene_camera->pos.y, scene_camera->pos.z) + ur;; Vector3f tll = Vector3f(scene_camera->pos.x, scene_camera->pos.y, scene_camera->pos.z) + ll;; Vector3f tlr = Vector3f(scene_camera->pos.x, scene_camera->pos.y, scene_camera->pos.z) + lr;; for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { // input_rayinfo[RAYADDR(x,y)].origin = float3((float)(((x+0.5)/(float)RAYSX)*VOXELSIZEX*VOXELSX), (float)(((y+0.5)/(float)RAYSY)*VOXELSIZEY*VOXELSY), -25.0); // input_rayinfo[RAYADDR(x,y)].direction = float3(0.0, 0.0, 1); // NOTE: avoid division by zero ? /* // interpolation of angles float xc = -((float)(x / (float)RAYSX) - 0.5f) * 2.0f; // range -1 .. 1 float yc = -((float)(y / (float)RAYSY) - 0.5f) * 2.0f; // range -1 .. 1 hrot.FromAxisAngle(cup, Mathf::DEG_TO_RAD*hfov*xc); vrot.FromAxisAngle(cright, Mathf::DEG_TO_RAD*vfov*yc); Vector3f ray = hrot*vrot*cdir; ray.Normalize(); */ // printf("[%d,%d] %02.2f, %02.2f, %02.2f\n", x,y, ray.X(), ray.Y(), ray.Z()); // interpolation of points float xc = ((float)(x / (float)RAYSX)); // range 0 .. 1 float yc = ((float)(y / (float)RAYSY)); // range 0 .. 1 Vector3f up = xc*ul + (1-xc)*ur; Vector3f lp = xc*ll + (1-xc)*lr; Vector3f ray = yc*up + (1-yc)*lp; ray.Normalize(); // printf("[%d,%d] %02.2f, %02.2f, %02.2f\n", x,y, ray.X(), ray.Y(), ray.Z()); input_rayinfo[RAYADDR(x,y)].info = float4((float)x,(float)y, (float)CG_FLT_MAX, 1.0f); input_rayinfo[RAYADDR(x,y)].origin = scene_camera->pos; input_rayinfo[RAYADDR(x,y)].direction = float3(ray.X(), ray.Y(), ray.Z()); } } // alloc output_raystate output_raystate = (t_raystate*)malloc(ray_size); for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { // output_raystate[RAYADDR(x,y)].state = float3(RAYSTATE_TRAVERSING, 0, 0); } } // alloc output_traverserstate output_traverserstate = (t_traverserstate*)malloc(traverser_size); for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { // output_traverserstate[RAYADDR(x,y)].voxel = float3(0, 0, 0); // output_traverserstate[RAYADDR(x,y)].tmax = float3(0, 0, 0); } } // alloc output_intersectorstate output_intersectorstate = (t_intersectorstate*)malloc(intersector_size); for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { // output_intersectorstate[RAYADDR(x,y)].tripos = float3(0, 0, 0); } } // alloc output_framebufferstate output_framebufferstate = (t_framebufferstate*)malloc(framebuffer_size); // alloc input_framebufferstate input_framebufferstate = (t_framebufferstate*)malloc(framebuffer_size); for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { input_framebufferstate[RAYADDR(x,y)].color = float3(0, 0, 0); // init framebufer to black } } // alloc output_dispatcherstate output_dispatcherstate = (t_dispatcherstate*)malloc(dispatcher_size); // alloc input_dispatcherstate input_dispatcherstate = (t_dispatcherstate*)malloc(dispatcher_size); for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { input_dispatcherstate[RAYADDR(x,y)].phase = float3(0, 0, 0); // samplephase, shadowphase, ? input_dispatcherstate[RAYADDR(x,y)].hitinfo = float4(-1, 0, 0, 0); // raystatus, u, v, weight input_dispatcherstate[RAYADDR(x,y)].hitdirection = input_rayinfo[RAYADDR(x,y)].direction; } } // alloc input_raystate input_raystate = (t_raystate*)malloc(ray_size); for (y=0; y<RAYSY; y++) { for (x=0; x<RAYSX; x++) { input_raystate[RAYADDR(x,y)].state = float4(RAYSTATE_SETUP, 0, 0, 0); // SETUP is important here } } return 0; }
void Tri2dFCBlockSolver::gradSetupQuadratic() { // form quadratic sub elements int nElemQ = 3*nElem; int nneQ = 6; //quadratic elements int nngQ = 4; //quadratic elements Array2D<int> elemQ(nElemQ,nneQ),gNode(nElemQ,nngQ); int m=0; for (int n=0; n<nElem; n++){ elemQ(m ,0) = elem(n,0); elemQ(m ,1) = elem(n,4); elemQ(m ,2) = elem(n,7); elemQ(m ,3) = elem(n,3); elemQ(m ,4) = elem(n,9); elemQ(m ,5) = elem(n,8); gNode(m ,0) = 0; gNode(m ,1) = 3; gNode(m ,2) = 4; gNode(m++,3) = 5; elemQ(m ,0) = elem(n,3); elemQ(m ,1) = elem(n,1); elemQ(m ,2) = elem(n,6); elemQ(m ,3) = elem(n,4); elemQ(m ,4) = elem(n,5); elemQ(m ,5) = elem(n,9); gNode(m ,0) = 1; gNode(m ,1) = 4; gNode(m ,2) = 5; gNode(m++,3) = 3; elemQ(m ,0) = elem(n,8); elemQ(m ,1) = elem(n,5); elemQ(m ,2) = elem(n,2); elemQ(m ,3) = elem(n,9); elemQ(m ,4) = elem(n,6); elemQ(m ,5) = elem(n,7); gNode(m ,0) = 2; gNode(m ,1) = 5; gNode(m ,2) = 3; gNode(m++,3) = 4; } /* for (int n=0; n<nElemQ; n++){ cout << n << " "; for (int j=0; j<nneQ; j++) cout << elemQ(n,j) << " "; cout << endl; } exit(0); */ // Jacobian terms Array2D <double> xr(nElemQ,nngQ),yr(nElemQ,nngQ),xs(nElemQ,nngQ), ys(nElemQ,nngQ),jac(nElemQ,nngQ),rs(nneQ,3),lc(nneQ,nneQ); xr.set(0.); yr.set(0.); xs.set(0.); ys.set(0.); jac.set(0.); int orderE=2; //quadratic elements solutionPoints(orderE, spacing, &rs(0,0)); bool test=true; lagrangePoly(test, orderE, &rs(0,0), &lc(0,0)); int j,km,lm; double lrm,lsm,ri,si; for (int n=0; n<nElemQ; n++){ // evaluate the Jacobian terms at the mesh points for (int i=0; i<nngQ; i++){ //ith mesh point ri = rs(gNode(n,i),0); si = rs(gNode(n,i),1); for (int m=0; m<nneQ; m++){ //mth Lagrange polynomial j = 0; lrm = 0.; lsm = 0.; for (int k=0; k<=orderE; k++) for (int l=0; l<=orderE-k; l++){ km = max(0,k-1); lm = max(0,l-1); lrm +=((double)k)*pow(ri,km)*pow(si,l )*lc(m,j ); lsm +=((double)l)*pow(ri,k )*pow(si,lm)*lc(m,j++); } xr(n,i) += lrm*x(elemQ(n,m),0); yr(n,i) += lrm*x(elemQ(n,m),1); xs(n,i) += lsm*x(elemQ(n,m),0); ys(n,i) += lsm*x(elemQ(n,m),1); } jac(n,i) = xr(n,i)*ys(n,i)-yr(n,i)*xs(n,i); }} // lr(i,j) = (dl_j/dr)_i (a row is all Lagrange polynomials (derivatives) // evaluated at a single mesh point i, same with the other derivatives) Array2D<double> lr(nneQ,nneQ),ls(nneQ,nneQ),lrr(nneQ,nneQ), lss(nneQ,nneQ),lrs(nneQ,nneQ); lr.set(0.); ls.set(0.); lrr.set(0.); lss.set(0.); lrs.set(0.); int kmm,lmm; for (int n=0; n<nneQ; n++) // nth Lagrange polynomial for (int i=0; i<nneQ; i++){ // ith mesh point j = 0; ri = rs(i,0); si = rs(i,1); for (int k=0; k<=orderE; k++) for (int l=0; l<=orderE-k; l++){ km = max(0,k-1); lm = max(0,l-1); kmm = max(0,k-2); lmm = max(0,l-2); lr (i,n) +=((double)k)*pow(ri,km)*pow(si,l )*lc(n,j); ls (i,n) +=((double)l)*pow(ri,k )*pow(si,lm)*lc(n,j); lrr(i,n) +=((double)(k*km))*pow(ri,kmm)*pow(si,l )*lc(n,j ); lss(i,n) +=((double)(l*lm))*pow(ri,k )*pow(si,lmm)*lc(n,j ); lrs(i,n) +=((double)(k*l ))*pow(ri,km )*pow(si,lm )*lc(n,j++); }} // compute averaged quadratic FEM gradient coefficients Array1D<double> sumj(nNode); sumj.set(0.); for (int n=0; n<nElemQ; n++) for (int i=0; i<nngQ; i++){ m = gNode(n,i); sumj(elemQ(n,m)) += jac(n,i); } for (int n=0; n<nNode; n++) sumj(n) = 1./sumj(n); int k1,k2; double xri,yri,xsi,ysi; Array2D<double> ax(nNode,2); ax.set(0.); gxQ.set(0.); for (int n=0; n<nElemQ; n++) for (int i=0; i<nngQ; i++){ m = gNode(n,i); k1 = elemQ(n,m); xri = xr(n,i); yri = yr(n,i); xsi = xs(n,i); ysi = ys(n,i); for (int j=0; j<nneQ; j++){ k2 = elemQ(n,j); ax(k2,0) = lr(m,j)*ysi-ls(m,j)*yri; ax(k2,1) =-lr(m,j)*xsi+ls(m,j)*xri; } for(int j=psp2(k1); j<psp2(k1+1); j++){ k2 = psp1(j); gxQ(j,0) += ax(k2,0); gxQ(j,1) += ax(k2,1); } for (int j=0; j<nneQ; j++){ k2 = elemQ(n,j); ax(k2,0) = 0.; ax(k2,1) = 0.; }} for (int n=0; n<nNode; n++) for (int i=psp2(n); i<psp2(n+1); i++){ gxQ(i,0) *= sumj(n); gxQ(i,1) *= sumj(n); } // deallocate work arrays elemQ.deallocate(); gNode.deallocate(); xr.deallocate(); yr.deallocate(); xs.deallocate(); ys.deallocate(); jac.deallocate(); rs.deallocate(); lc.deallocate(); lr.deallocate(); ls.deallocate(); lrr.deallocate(); lss.deallocate(); lrs.deallocate(); sumj.deallocate(); ax.deallocate(); }