Exemplo n.º 1
0
void doGsLogin(struct sqlConnection *conn)
/* Process user password post.
 * Log into GS 
 * if successful save gsToken 
 * else return to login page or to mainpage */
{
char *user = cloneString(cartUsualString(cart, hgtaGsUser, NULL));
char *password = cloneString(cartUsualString(cart, hgtaGsPassword, NULL));
// do not leave them in the cart
cartRemove(cart, hgtaGsUser);
cartRemove(cart, hgtaGsPassword);

if (!(user && password))
    errAbort("expecting GenomeSpace user and password");

char *gsToken = getAuthorizationToken(user, password);

if (gsToken)
    {
    cartSetString(cart, "gsToken", gsToken);
    }
else
    {
    cartRemove(cart, "gsToken");
    }

cartSetString(cart, hgtaDoTopSubmit, "get output");

}
Exemplo n.º 2
0
static void setDb(struct cartJson *cj, struct hash *paramHash)
/* Set taxId and genome according to db and return the info we'll need to fill in
 * the findPosition section. */
{
char *db = cartJsonRequiredParam(paramHash, "db", cj->jw, "setDb");
char *hubUrl = cartJsonOptionalParam(paramHash, "hubUrl");
int taxId = hTaxId(db);
writeFindPositionInfo(cj->jw, db, taxId, hubUrl, hDefaultPos(db));
cartSetString(cart, "db", db);
cartSetString(cart, "position", hDefaultPos(db));
}
void dispatchLocation()
/* When this is called no output has been written at all.  We
 * look at command variables in cart and figure out if we just
 * are going write an HTTP location line, which happens when we
 * want to invoke say the genome browser or gene sorter without 
 * another intermediate page.  If we need to do more than that
 * then we call hggDoUsualHttp. */
{
struct sqlConnection *conn = NULL;
getDbAndGenome(cart, &database, &genome, oldVars);
setUdcCacheDir();
cartSetString(cart, "db", database); /* Some custom tracks code needs this */
withLabels = cartUsualBoolean(cart, hggLabels, TRUE);
conn = hAllocConn(database);
getGenoGraphs(conn);

/* Handle cases that just want a HTTP Location line: */
if (cartVarExists(cart, hggClickX))
    {
    clickOnImage(conn);
    return;
    }

hFreeConn(&conn);

/* For other cases we want to print out some of the usual HTTP
 * lines including content-type */
hggDoUsualHttp();
}
Exemplo n.º 4
0
static void hubConnectRemakeTrackHubVar(struct cart *cart)
/* Remake trackHub cart variable if need be from various check box vars. */
{
if (cartVarExists(cart, hgHubConnectRemakeTrackHub))
    {
    struct slPair *hubVarList = cartVarsWithPrefix(cart, hgHubConnectHubVarPrefix);
    int prefixLength = strlen(hgHubConnectHubVarPrefix);
    struct dyString *trackHubs = dyStringNew(0);
    struct slPair *hubVar;
    boolean firstOne = TRUE;
    for (hubVar = hubVarList; hubVar != NULL; hubVar = hubVar->next)
        {
	if (cartBoolean(cart, hubVar->name))
	    {
	    if (firstOne)
		firstOne = FALSE;
	    else
		dyStringAppendC(trackHubs, ' ');
	    dyStringAppend(trackHubs, hubVar->name + prefixLength);
	    }
	}
    slPairFreeList(&hubVarList);
    cartSetString(cart, hubConnectTrackHubsVarName, trackHubs->string);
    dyStringFree(&trackHubs);
    cartRemove(cart, hgHubConnectRemakeTrackHub);
    }
}
Exemplo n.º 5
0
static void doBigSelectPage(char *db, char *table)
/* Put up big field selection page. Assumes html page open already*/
{
struct joiner *joiner = allJoiner;
struct dbTable *dtList, *dt;
char dbTableBuf[256];

cartSetString(cart, hgtaFieldSelectTable, getDbTable(db, table));
if (strchr(table, '.'))
    htmlOpen("Select Fields from %s", table);
else
    htmlOpen("Select Fields from %s.%s", db, table);
hPrintf("<FORM NAME=\"mainForm\" ACTION=\"%s\" METHOD=%s>\n", cgiScriptName(),
	cartUsualString(cart, "formMethod", "POST"));
cartSaveSession(cart);
cgiMakeHiddenVar(hgtaDatabase, db);
cgiMakeHiddenVar(hgtaTable, table);
dbOverrideFromTable(dbTableBuf, &db, &table);

showTableFields(db, table, TRUE);
dtList = extraTableList(selFieldLinkedTablePrefix());
showLinkedFields(dtList);
dt = dbTableNew(db, table);
slAddHead(&dtList, dt);
showLinkedTables(joiner, dtList, selFieldLinkedTablePrefix(),
	hgtaDoSelectFieldsMore, "allow selection from checked tables");

/* clean up. */
hPrintf("</FORM>");
cgiDown(0.9);
htmlClose();
joinerFree(&joiner);
}
Exemplo n.º 6
0
void doAdvFilterKeyPasted(struct sqlConnection *conn, struct column *colList, 
    struct column *col)
/* Handle submission in key-paste in form. */
{
char *pasteVarName = colVarName(col, keyWordPastedPrefix);
char *pasteVal = trimSpaces(cartString(cart, pasteVarName));
char *keyVarName = advFilterName(col, "keyFile");

if (pasteVal == NULL || pasteVal[0] == 0)
    {
    /* If string is empty then clear cart variable. */
    cartRemove(cart, keyVarName);
    }
else
    {
    /* Else write variable to temp file and save temp
     * file name. */
    struct tempName tn;
    FILE *f;
    makeTempName(&tn, "near", ".key");
    f = mustOpen(tn.forCgi, "w");
    mustWrite(f, pasteVal, strlen(pasteVal));
    carefulClose(&f);
    cartSetString(cart, keyVarName, tn.forCgi);
    }
cartRemovePrefix(cart, keyWordPastedPrefix);
doAdvFilter(conn, colList);
}
Exemplo n.º 7
0
void doMiddle(struct cart *theCart)
/* Write header and body of html page. */
{
char *userSeq;
char *db, *organism;
boolean clearUserSeq = cgiBoolean("Clear");

cart = theCart;
dnaUtilOpen();

orgChange = sameOk(cgiOptionalString("changeInfo"),"orgChange");
if (orgChange)
    {
    cgiVarSet("db", hDefaultDbForGenome(cgiOptionalString("org"))); 
    }
getDbAndGenome(cart, &db, &organism, oldVars);
char *oldDb = cloneString(db);
findClosestServer(&db, &organism);

/* Get sequence - from userSeq variable, or if 
 * that is empty from a file. */
if (clearUserSeq)
    {
    cartSetString(cart, "userSeq", "");
    cartSetString(cart, "seqFile", "");
    }
userSeq = cartUsualString(cart, "userSeq", "");
if (isEmpty(userSeq))
    {
    userSeq = cartOptionalString(cart, "seqFile");
    }
if (isEmpty(userSeq) || orgChange)
    {
    cartWebStart(theCart, db, "%s BLAT Search", trackHubSkipHubName(organism));
    if (differentString(oldDb, db))
	printf("<HR><P><EM><B>Note:</B> BLAT search is not available for %s %s; "
	       "defaulting to %s %s</EM></P><HR>\n",
	       hGenome(oldDb), hFreezeDate(oldDb), organism, hFreezeDate(db));
    askForSeq(organism,db);
    cartWebEnd();
    }
else 
    {
    blatSeq(skipLeadingSpaces(userSeq), organism);
    }
}
Exemplo n.º 8
0
static void setTaxId(struct cartJson *cj, struct hash *paramHash)
/* Set db and genome according to taxId (and/or db) and return the info we'll need
 * to fill in the findPosition section. */
{
char *taxIdStr = cartJsonRequiredParam(paramHash, "taxId", cj->jw, "setTaxId");
char *db = cartJsonOptionalParam(paramHash, "db");
int taxId = atoi(taxIdStr);
if (isEmpty(db))
    db = hDbForTaxon(taxId);
if (isEmpty(db))
    jsonWriteStringf(cj->jw, "error", "No db for taxId '%s'", taxIdStr);
else
    {
    writeFindPositionInfo(cj->jw, db, taxId, NULL, hDefaultPos(db));
    cartSetString(cart, "db", db);
    cartSetString(cart, "position", hDefaultPos(db));
    }
}
Exemplo n.º 9
0
void printGreatSubmitButtons()
/* print submit button to create data and then send query results to GREAT. */
{
cartSetString(cart, hgtaCompressType, textOutCompressNone);
cartSetString(cart, hgtaOutFileName, "");

cgiMakeHiddenVar(hgtaCompressType, textOutCompressNone);
cgiMakeHiddenVar(hgtaOutFileName, "");

cgiMakeHiddenVar(hgtaDoGreatOutput, "on");
cgiMakeHiddenVar(hgtaPrintCustomTrackHeaders, "on");
cgiMakeButton(hgtaDoGreatQuery, "Send query to GREAT");
hPrintf("</FORM>\n");
hPrintf(" ");
/* new form as action is different */
hPrintf("<FORM ACTION=\"%s\" METHOD=GET>\n", cgiScriptName());
cgiMakeButton(hgtaDoMainPage, "Cancel");
hPrintf("</FORM>\n");
}
Exemplo n.º 10
0
char *hubConnectLoadHubs(struct cart *cart)
/* load the track data hubs.  Set a static global to remember them */
{
char *newDatabase = checkForNew( cart);
cartSetString(cart, hgHubConnectRemakeTrackHub, "on");
struct hubConnectStatus  *hubList =  hubConnectStatusListFromCart(cart);
globalHubList = hubList;

return newDatabase;
}
Exemplo n.º 11
0
static void setCheckVarsForTable(char *dbTable, char *val)
/* Return list of check variables for this table. */
{
char prefix[128];
struct hashEl *varList, *var;
safef(prefix, sizeof(prefix), "%s%s.", checkVarPrefix(), dbTable);
varList = cartFindPrefix(cart, prefix);
for (var = varList; var != NULL; var = var->next)
    cartSetString(cart, var->name, val);
hashElFreeList(&varList);
}
Exemplo n.º 12
0
void copyCartVars(struct cart *cart, char **source, char **dest, int count)
/* Copy from source to dest. */
{
int i;
for (i=0; i<count; ++i)
    {
    char *s = cartOptionalString(cart, source[i]);
    if (s != NULL)
        cartSetString(cart, dest[i], s);
    else
        cartRemove(cart, dest[i]);
    }
}
Exemplo n.º 13
0
void writePcrResultTrack(struct gfPcrOutput *gpoList, char *db, char *target)
/* Write trash files and store their name in a cart variable. */
{
    char *cartVar = pcrResultCartVar(db);
    struct tempName bedTn, primerTn;
    char buf[2048];
    trashDirFile(&bedTn, "hgPcr", "hgPcr", ".psl");
    trashDirFile(&primerTn, "hgPcr", "hgPcr", ".txt");
    gfPcrOutputWriteAll(gpoList, "psl", NULL, bedTn.forCgi);
    writePrimers(gpoList, primerTn.forCgi);
    if (isNotEmpty(target))
        safef(buf, sizeof(buf), "%s %s %s", bedTn.forCgi, primerTn.forCgi, target);
    else
        safef(buf, sizeof(buf), "%s %s", bedTn.forCgi, primerTn.forCgi);
    cartSetString(cart, cartVar, buf);
}
Exemplo n.º 14
0
static void setIfUnset(struct cartJson *cj, struct hash *paramHash)
/* For each name in paramHash, if that cart variable doesn't already have a non-empty
 * value, set it to the value. */
{
struct hashCookie cookie = hashFirst(paramHash);
struct hashEl *hel;
while ((hel = hashNext(&cookie)) != NULL)
    {
    if (isEmpty(cartOptionalString(cj->cart, hel->name)))
	{
	char *val = jsonStringVal((struct jsonElement *)(hel->val), hel->name);
	if (val)
	    cartSetString(cj->cart, hel->name, val);
	}
    }
}
Exemplo n.º 15
0
static struct hubConnectStatus *getAndSetHubStatus( struct cart *cart, char *url, 
    boolean set)
/* make sure url is in hubStatus table, fetch the hub to get latest
 * labels and db information.
 * Set the cart variable to turn the hub on if set == TRUE.  
 */
{
char *errorMessage = NULL;
unsigned id;

/* first see if url is in hubStatus table */
if ((id = getHubId(url, &errorMessage)) == 0)
    {
    /* the url is not in the hubStatus table, add it */
    insertHubUrlInStatus(url);
    if ((id = getHubId(url, &errorMessage)) == 0)
	{
	errAbort("opened hub, but could not get it out of the hubStatus table");
	}
    }

/* allocate a hub */
struct hubConnectStatus *hub = NULL;

AllocVar(hub);
hub->id = id;
hub->hubUrl = cloneString(url);

/* new fetch the contents of the hub to fill in the status table */
struct trackHub *tHub = fetchHub( hub, &errorMessage);
if (tHub != NULL)
    hub->trackHub = tHub;

/* update the status table with the lastest label and database information */
hubUpdateStatus( errorMessage, hub);

/* if we're turning on the hub, set the cart variable */
if (set)
    {
    char hubName[32];
    safef(hubName, sizeof(hubName), "%s%u", hgHubConnectHubVarPrefix, id);
    cartSetString(cart, hubName, "1");
    }

return hub;
}
Exemplo n.º 16
0
void doId(struct sqlConnection *conn)
/* Set up Gene Pix on given ID. */
{
int id = cartInt(cart, hgpDoId);
struct slName *genes = visiGeneGeneName(conn, id);
if (genes == NULL)
    {
    cartRemove(cart, hgpListSpec);
    cartRemove(cart, hgpId);
    }
else
    {
    cartSetInt(cart, hgpId, id);
    cartSetString(cart, hgpListSpec, genes->name);
    }
slFreeList(&genes);
doDefault(conn, FALSE);
}
void userSettingsUseNamed(struct userSettings *us, char *setName)
/* Use named collection of settings. */
{
struct cart *cart = us->cart;
char *varName = settingsVarName(us->savePrefix, setName);
char *settings = cartOptionalString(cart, varName);
if (settings != NULL)
    {
    struct hash *hash = hashVarLine(settings, 1);
    struct hashEl *list = hashElListHash(hash);
    struct hashEl *el;
    for (el = list; el != NULL; el = el->next)
	cartSetString(cart, el->name, el->val);
    slFreeList(&list);
    hashFree(&hash);
    }
freez(&varName);
}
Exemplo n.º 18
0
static void activatePslTrackIfCgi(struct track *tg)
/* the publications hgc creates links back to the browser with 
 * the cgi param pubsFilterArticleId to show only a single type
 * of feature for the pubsBlatPsl track. 
 * If the parameter was supplied, we save it here 
 * into the cart and activate the track.
 */
{
char *articleId = cgiOptionalString(PUBSFILTERNAME);
//if (articleId==NULL) 
    //articleId = cartOptionalString(cart, PUBSFILTERNAME);

if (articleId!=NULL) 
{
    cartSetString(cart, PUBSFILTERNAME, articleId);
    tdbSetCartVisibility(tg->tdb, cart, hCarefulTrackOpenVis(database, tg->track));
    tg->visibility=tvPack;
}
}
static void saveSettings(struct userSettings *us, char *varName)
/* Save captured settings to varName. */
{
struct cart *cart = us->cart;
struct slName *capture;
struct dyString *dy = dyStringNew(4*1024);
for (capture = us->saveList; capture != NULL; capture = capture->next)
    {
    char *name = capture->name;
    char *val = cartOptionalString(cart, name);
    if (val != NULL)
        {
	dyStringPrintf(dy, "%s=", name);
	dyStringAppendQuoted(dy, val);
	}
    }
cartSetString(cart, varName, dy->string);
dyStringFree(&dy);
}
Exemplo n.º 20
0
static char * outMafTableDrop(struct cart *cart, struct sqlConnection *conn)
{
struct slName *list = hTrackTablesOfType(conn, "wigMaf%%");
int count = slCount(list);

if (count == 0)
    errAbort("There are no multiple alignments available for this genome.");

char **tables = needMem(sizeof(char *) * count);
char **tb = tables;
char *mafTable = cartOptionalString(cart, hgtaCGIGeneMafTable);

if (mafTable != NULL)
    {
    struct slName *l = list;
    for(; l; l=l->next)
	if (sameString(l->name, mafTable))
	    break;

    /* didn't find mafTable in list, reset it */
    if (l == NULL)
	mafTable = NULL;
    }

if (mafTable == NULL)
    {
    if ((mafTable = getConservationTrackName(conn)) == NULL)
	mafTable = list->name;

    cartSetString(cart, hgtaCGIGeneMafTable, mafTable);
    }

for(; list; list = list->next)
    *tb++ = list->name;

printf("<B>MAF table: </B>\n");
cgiMakeDropListFull(hgtaCGIGeneMafTable, tables, tables,
    count , mafTable, onChangeGenome());

return mafTable;
}
Exemplo n.º 21
0
static void changePosition(struct cartJson *cj, char *newPosition)
/* Update position in cart, after performing lookup if necessary.
 * Usually we don't report what we just changed, but since we might modify it,
 * print out the final value. */
{
char *db = cartString(cj->cart, "db");
char *chrom = NULL;
int start=0, end=0;
struct hgPositions *hgp = genomePosCJ(cj->jw, db, newPosition, &chrom, &start, &end, cj->cart);
// If it resolved to a single position, update the cart; otherwise the app can
// present the error (or list of matches) to the user.
if (hgp && hgp->singlePos)
    {
    char newPosBuf[128];
    safef(newPosBuf, sizeof(newPosBuf), "%s:%d-%d", chrom, start+1, end);
    cartSetString(cj->cart, "position", newPosBuf);
    jsonWriteString(cj->jw, "position", newPosBuf);
    }
else
    // Search failed; restore position from cart
    jsonWriteString(cj->jw, "position", cartUsualString(cj->cart, "position", hDefaultPos(db)));
}
struct hvGfx *oneTrackMakeTrackHvg(char *trackName, char *gifName)
/* Set up a single track, load it, draw it and return the graphics object: */
{
char *visStr = cloneString(
	cartUsualString(cart, trackName, hTrackOpenVis(trackName)) );
cartSetString(cart, trackName, visStr);
struct trackDb *tdb = hTrackDbForTrack(trackName);
tdbSortPrioritiesFromCart(cart, &tdb);
if(tdb->subtracks)
    tdbSortPrioritiesFromCart(cart, &(tdb->subtracks));
struct track *tg = trackFromTrackDb(tdb);
tg->visibility = hTvFromString(visStr);
trackList = tg;

tg->loadItems(tg);
limitVisibility(tg);
int height = tg->totalHeight(tg, tg->limitedVis);

struct hvGfx *hvg = hvGfxOpenGif(insideWidth, height, gifName, TRUE);
initColors(hvg);
findTrackColors(hvg, tg);

/* This is the only image we'll draw, so offset=(0,0). */
int xOff = 0, yOff = 0;
MgFont *font = tl.font;
hvGfxSetClip(hvg, xOff, yOff, insideWidth, tg->height);
tg->drawItems(tg, winStart, winEnd, hvg, xOff, yOff, insideWidth, font,
	      hvGfxFindRgb(hvg, &tg->color), tg->limitedVis);

/* MEMORY LEAK -- Freeing items slows hgTracks down unacceptably so we
 * don't do it, and it has become vestigial.  For example, wigFreeItems 
 * is a no-op because the author noted that it is never invoked. */
#ifdef SLOW
tg->freeItems(tg);
#endif /* SLOW */

return hvg;
}
void loadAffyTranscriptome(struct track *tg)
	/* Convert sample info in window to linked feature. */
{
	struct sqlConnection *conn = hAllocConn(database);
	struct sqlResult *sr;
	char **row;
	int rowOffset;
	struct sample *sample;
	struct linkedFeatures *lfList = NULL, *lf;
	char *hasDense = NULL;
	char *where = NULL;
	char query[256];
	char tableName[256];
	int zoom1 = 23924, zoom2 = 2991; /* bp per data point */
	float pixPerBase = 0;
	/* Set it up so we don't have linear interpretation.. */
	char *noLinearInterpString = wiggleEnumToString(wiggleNoInterpolation);
	cartSetString(cart, "affyTranscriptome.linear.interp", noLinearInterpString);

	if(tl.picWidth == 0)
		errAbort("hgTracks.c::loadAffyTranscriptome() - can't have pixel width of 0");
	pixPerBase = (winEnd - winStart)/ tl.picWidth;


	/* Determine zoom level. */
	if(pixPerBase >= zoom1)
		safef(tableName, sizeof(tableName), "%s_%s", "zoom1", tg->table);
	else if(pixPerBase >= zoom2)
		safef(tableName, sizeof(tableName), "%s_%s", "zoom2", tg->table);
	else 
		safef(tableName, sizeof(tableName), "%s", tg->table);

	/*see if we have a summary table*/
	if(hTableExists(database, tableName))
		safef(query, sizeof(query), "select name from %s where name = '%s' limit 1",  tableName, tg->shortLabel);
	else
	{
		warn("<p>Couldn't find table %s<br><br>", tableName);
		safef(query, sizeof(query), "select name from %s where name = '%s' limit 1",  tg->table, tg->shortLabel);
		safef(tableName, sizeof(tableName), "%s", tg->table);
	}

	hasDense = sqlQuickQuery(conn, query, query, sizeof(query));

	/* If we're in dense mode and have a summary table load it. */
	if(tg->visibility == tvDense)
	{
		if(hasDense != NULL)
		{
			safef(query, sizeof(query), " name = '%s' ", tg->shortLabel);
			where = cloneString(query);
		}
	}

	sr = hRangeQuery(conn, tableName, chromName, winStart, winEnd, where, &rowOffset);
	while ((row = sqlNextRow(sr)) != NULL)
	{
		sample = sampleLoad(row+rowOffset);
		lf = lfFromSample(sample);
		slAddHead(&lfList, lf);
		sampleFree(&sample);
	}
	if(where != NULL)
		freez(&where);
	sqlFreeResult(&sr);
	hFreeConn(&conn);
	slReverse(&lfList);

	/* sort to bring items with common names to the same line
	but only for tracks with a summary table (with name=shortLabel) in
	dense mode*/
	if( hasDense != NULL )
	{
		sortGroupList = tg; /* used to put track name at top of sorted list. */
		slSort(&lfList, lfNamePositionCmp);
		sortGroupList = NULL;
	}
	tg->items = lfList;
}
Exemplo n.º 24
0
static void doMainPage()
/* Send HTML with javascript to bootstrap the user interface. */
{
// Start web page with new banner
char *db = NULL, *genome = NULL, *clade = NULL;
getDbGenomeClade(cart, &db, &genome, &clade, oldVars);
// If CGI has &lastDbPos=..., handle that here and save position to cart so it's in place for
// future cartJson calls.
char *position = cartGetPosition(cart, db, NULL);
cartSetString(cart, "position", position);
webStartJWest(cart, db, "Genome Browser Gateway");

if (cgiIsOnWeb())
    checkForGeoMirrorRedirect(cart);

#define WARNING_BOX_START "<div id=\"previewWarningRow\" class=\"jwRow\">" \
         "<div id=\"previewWarningBox\" class=\"jwWarningBox\">"

#define UNDER_DEV "Data and tools on this site are under development, have not been reviewed " \
         "for quality, and are subject to change at any time. "

#define MAIN_SITE "The high-quality, reviewed public site of the UCSC Genome Browser is " \
         "available for use at <a href=\"http://genome.ucsc.edu/\">http://genome.ucsc.edu/</a>."

#define WARNING_BOX_END "</div></div>"

if (hIsPreviewHost())
    {
    puts(WARNING_BOX_START
         "WARNING: This is the UCSC Genome Browser preview site. "
         "This website is a weekly mirror of our internal development server for public access. "
         UNDER_DEV
         "We provide this site for early access, with the warning that it is less available "
         "and stable than our public site. "
         MAIN_SITE
         WARNING_BOX_END);
    }

if (hIsPrivateHost() && !hHostHasPrefix("hgwdev-demo6"))
    {
    puts(WARNING_BOX_START
         "WARNING: This is the UCSC Genome Browser development site. "
         "This website is used for testing purposes only and is not intended for general public "
         "use. "
         UNDER_DEV
         MAIN_SITE
         WARNING_BOX_END);
    }

// The visible page elements are all in ./hgGateway.html, which is transformed into a quoted .h
// file containing a string constant that we #include and print here (see makefile).
puts(
#include "hgGateway.html.h"
);

// Set global JS variables hgsid, activeGenomes, and survey* at page load time
// We can't just use "var hgsid = " or the other scripts won't see it -- it has to be
// "window.hgsid = ".
puts("<script>");
printf("window.%s = '%s';\n", cartSessionVarName(), cartSessionId(cart));
puts("window.activeGenomes =");
printActiveGenomes();
puts(";");
char *surveyLink = cfgOption("survey");
if (isNotEmpty(surveyLink) && !sameWord(surveyLink, "off"))
    {
    printf("window.surveyLink=\"%s\";\n", jsonStringEscape(surveyLink));
    char *surveyLabel = cfgOptionDefault("surveyLabel", "Please take our survey");
    printf("window.surveyLabel=\"%s\";\n", jsonStringEscape(surveyLabel));
    char *surveyLabelImage = cfgOption("surveyLabelImage");
    if (isNotEmpty(surveyLabelImage))
        printf("window.surveyLabelImage=\"%s\";\n", jsonStringEscape(surveyLabelImage));
    else
        puts("window.surveyLabelImage=null;");
    }
else
    {
    puts("window.surveyLink=null;");
    puts("window.surveyLabel=null;");
    puts("window.surveyLabelImage=null;");
    }
puts("</script>");

puts("<script src=\"../js/es5-shim.4.0.3.min.js\"></script>");
puts("<script src=\"../js/es5-sham.4.0.3.min.js\"></script>");
puts("<script src=\"../js/lodash.3.10.0.compat.min.js\"></script>");
puts("<script src=\"../js/cart.js\"></script>");

webIncludeResourceFile("jquery-ui.css");
jsIncludeFile("jquery-ui.js", NULL);
jsIncludeFile("jquery.watermarkinput.js", NULL);
jsIncludeFile("utils.js",NULL);

// Phylogenetic tree .js file, produced by dbDbTaxonomy.pl:
char *dbDbTree = cfgOptionDefault("hgGateway.dbDbTaxonomy", "../js/dbDbTaxonomy.js");
if (isNotEmpty(dbDbTree))
    printf("<script src=\"%s\"></script>\n", dbDbTree);

// Main JS for hgGateway:
puts("<script src=\"../js/hgGateway.js\"></script>");

webIncludeFile("inc/jWestFooter.html");

cartFlushHubWarnings();

webEndJWest();
}
void sortGenes(struct sqlConnection *conn)
/* Put up sort gene page. */
{
cartWebStart(cart, database, "Finding Candidate Genes for Gene Sorter");
if (!hgNearOk(database))
    errAbort("Sorry, gene sorter not available for this database.");

/* Get list of regions. */
struct genoGraph *gg = ggFirstVisible();
double threshold = getThreshold();
struct bed3 *bed, *bedList = regionsOverThreshold(gg);

/* Figure out what table and column are the sorter's main gene set. */
struct hash *genomeRa = hgReadRa(genome, database, "hgNearData", 
	"genome.ra", NULL);
char *geneTable = hashMustFindVal(genomeRa, "geneTable");
char *idColumn = hashMustFindVal(genomeRa, "idColumn");

/* if marker labels were present when the file was uploaded, they are saved here */
char cgmName[256];
safef(cgmName, sizeof(cgmName), "%s.cgm", gg->binFileName);
struct lineFile *m = lineFileMayOpen(cgmName, TRUE);
char *cgmRow[4];
cgmRow[0] = "";    /* dummy row */
cgmRow[1] = "";
cgmRow[2] = "0";
cgmRow[3] = "0";

FILE *g = NULL;
int markerCount = 0;
struct tempName snpTn;

if (m)
    {
    /* Create custom column output file. */
    trashDirFile(&snpTn, "hgg", "marker", ".mrk");  
    g = mustOpen(snpTn.forCgi, "w");
    fprintf(g, 
	"column name=\"%s Markers\" shortLabel=\"%s Markers over threshold\" longLabel=\"%s Markers in regions over threshold\" " 
	"visibility=on priority=99 "
        "\n"
        , gg->shortLabel
        , gg->shortLabel
        , gg->shortLabel
	);
    }

/*** Build up hash of all transcriptHash that are in region. */
struct hash *transcriptHash = hashNew(16);

/* This loop handles one chromosome at a time.  It depends on
 * the bedList being sorted by chromosome. */
for (bed = bedList; bed != NULL; )
    {

    /* Make binKeeper and stuff in all regions in this chromosome into it. */
    char *chrom = bed->chrom;
    int chromSize = hChromSize(database, chrom);
    struct binKeeper *bk = binKeeperNew(0, chromSize);
    while (bed != NULL && sameString(chrom, bed->chrom))
	{
	binKeeperAdd(bk, bed->chromStart, bed->chromEnd, bed);
	bed = bed->next;
	}

    struct binKeeper *bkGenes = NULL;
    if (m)
       bkGenes = binKeeperNew(0, chromSize);

    /* Query database to find out bounds of all genes on this chromosome
     * and if they overlap any of the regions then put them in the hash. */
    char query[512];
    safef(query, sizeof(query), 
    	"select name,txStart,txEnd from %s where chrom='%s'", geneTable, chrom);
    struct sqlResult *sr = sqlGetResult(conn, query);
    char **row;
    while ((row = sqlNextRow(sr)) != NULL)
        {
	char *name = row[0];
	int start = sqlUnsigned(row[1]);
	int end = sqlUnsigned(row[2]);
	if (binKeeperAnyOverlap(bk, start, end))
	    {
	    hashStore(transcriptHash, name);
	    if (m)
		binKeeperAdd(bkGenes, start, end, cloneString(name));
	    }
	}
    sqlFreeResult(&sr);

    if (m)
	{
	/* Read cgm file if it exists, looking at all markers on this chromosome
	 * and if they overlap any of the regions and genes then output them. */
	do 
	    {
	    // marker, chrom, chromStart, val
	    char *marker = cgmRow[0];
	    char *chr = cgmRow[1];
	    int start = sqlUnsigned(cgmRow[2]);
	    int end = start+1;
	    double val = sqlDouble(cgmRow[3]);
            int cmp = strcmp(chr,chrom);
            if (cmp > 0)
                break;
            if (cmp == 0)
		{
		if (val >= threshold)
		    {
		    struct binElement *el, *bkList = binKeeperFind(bkGenes, start, end);
		    for (el = bkList; el; el=el->next)
			{
			/* output to custom column trash file */
			fprintf(g, "%s %s\n", (char *)el->val, marker);
			}
		    if (bkList)
			{
			++markerCount;
			slFreeList(&bkList);
			}
		    }
		}
	    }
	while (lineFileRow(m, cgmRow));
	}

    /* Clean up for this chromosome. */
    binKeeperFree(&bk);

    if (m)
	{
	/* For speed, we do not free up the values (cloned the kg names earlier) */
	binKeeperFree(&bkGenes);  
	}

    }

/* Get list of all transcripts in regions. */
struct hashEl *el, *list = hashElListHash(transcriptHash);

/* Create file with all matching gene IDs. */
struct tempName keyTn;
trashDirFile(&keyTn, "hgg", "key", ".key");
FILE *f = mustOpen(keyTn.forCgi, "w");
for (el = list; el != NULL; el = el->next)
    fprintf(f, "%s\n", el->name);
carefulClose(&f);

/* Print out some info. */
hPrintf("Thresholding <i>%s</i> at %g. ", gg->shortLabel, threshold);
hPrintf("There are %d regions covering %lld bases.<BR>\n",
    slCount(bedList), bedTotalSize((struct bed*)bedList) );
hPrintf("Installed a Gene Sorter filter that selects only genes in these regions.<BR>\n");
if (m)
    {
    hPrintf("There are %d markers in the regions over threshold that overlap knownGenes.<BR>\n", markerCount);
    hPrintf("Installed a Gene Sorter custom column called \"%s Markers\" with these markers.<BR>\n", gg->shortLabel);
    }

/* close custom column output file */
if (m)
    {
    lineFileClose(&m);
    carefulClose(&g);
    }

/* Stuff cart variable with name of file. */
char keyCartName[256];
safef(keyCartName, sizeof(keyCartName), "%s%s.keyFile",
	advFilterPrefix, idColumn);
cartSetString(cart, keyCartName, keyTn.forCgi);

cartSetString(cart, customFileVarName, snpTn.forCgi);

char snpVisCartNameTemp[256];
char *snpVisCartName = NULL;
safef(snpVisCartNameTemp, sizeof(snpVisCartNameTemp), "%s%s Markers.vis",
	colConfigPrefix, gg->shortLabel);
snpVisCartName = replaceChars(snpVisCartNameTemp, " ", "_");
cartSetString(cart, snpVisCartName, "1");
freeMem(snpVisCartName);

hPrintf("<FORM ACTION=\"../cgi-bin/hgNear\" METHOD=GET>\n");
cartSaveSession(cart);
hPrintf("<CENTER>");
cgiMakeButton("submit", "go to gene sorter");
hPrintf("</CENTER>");
hPrintf("</FORM>");

cartWebEnd();
}
Exemplo n.º 26
0
void saveSubjList(struct subjInfo *subjListIn)
/* save the filtered list of subject gisaids to a file for other applications to use */
{
struct subjInfo *subjList;
char *outName = cartOptionalString(cart, gisaidSubjList);
char *outName2= cartOptionalString(cart, gisaidSeqList);
char *outName3= cartOptionalString(cart, gisaidAaSeqList);
char *outNameTemp;
struct tempName tn;
struct tempName tn2;
struct tempName tn3;
struct tempName tnTemp;
struct sqlResult *sr;
char **row;
char query[255];
int cnt;
char cmd[512];
if (!outName)
    {
    trashDirFile(&tn, "ct", "gisaidSubj", ".list");
    outName = tn.forCgi;
    }

if (!outName2)
    {
    trashDirFile(&tn2, "ct", "gisaidSeq", ".list");
    outName2 = tn2.forCgi;
    }

if (!outName3)
    {
    trashDirFile(&tn3, "ct", "gisaidAaSeq", ".list");
    outName3 = tn3.forCgi;
    }

trashDirFile(&tnTemp, "ct", "gisaidListTemp", ".list");
outNameTemp = tnTemp.forCgi;

FILE *outF = mustOpen(outName,"w");
FILE *outF2= mustOpen(outName2,"w");
FILE *outF3= mustOpen(outName3,"w");
cnt = 0;

subjList = subjListIn;
while (subjList)
    {
    fprintf(outF, "%s\n", subjList->fields[1]);

    sqlSafef(query, sizeof(query),
	  "select distinct seqId from h1n1SeqXref where islId='%s'",
	  subjList->fields[0]);
    sr = sqlGetResult(conn, query);
    while ((row = sqlNextRow(sr)) != NULL)
    	{
	/* Remove "ss." from the front of the DNA sequence ID,
	   so that they could be used both for DNA and protein MSA maf display */

	fprintf(outF2, "%s\t%s\n", row[0], subjList->fields[1]);
	cnt++;
	}
    sqlFreeResult(&sr);

    subjList=subjList->next;
    }

subjList = subjListIn;
while (subjList)
    {
    fprintf(outF, "%s\n", subjList->fields[0]);

    sqlSafef(query, sizeof(query),
	  "select distinct seqId, geneSymbol from h1n1SeqXref where islId='%s'",
	  subjList->fields[0]);

    sr = sqlGetResult(conn, query);
    while ((row = sqlNextRow(sr)) != NULL)
    	{
	/* Remove "ss." from the front of the DNA sequence ID,
	   so that they could be used both for DNA and protein MSA maf display */

	fprintf(outF3, "%s_%s\t%s\n", row[0], row[1], subjList->fields[1]);
	cnt++;
	}
    sqlFreeResult(&sr);

    subjList=subjList->next;
    }

carefulClose(&outF);
carefulClose(&outF2);
carefulClose(&outF3);

/* sort -u to make the selection lists unique */
sprintf(cmd, "cat %s |sort -u >%s", outName, outNameTemp);
system(cmd);
sprintf(cmd, "mv %s %s",  outNameTemp, outName);
system(cmd);

sprintf(cmd, "cat %s |sort -u >%s", outName2, outNameTemp);
system(cmd);
sprintf(cmd, "mv %s %s",  outNameTemp, outName2);
system(cmd);

sprintf(cmd, "cat %s |sort -u >%s", outName3, outNameTemp);
system(cmd);
sprintf(cmd, "mv %s %s",  outNameTemp, outName3);
system(cmd);

cartSetString(cart, gisaidSubjList, outName);
cartSetString(cart, gisaidSeqList, outName2);
cartSetString(cart, gisaidAaSeqList, outName3);
}
Exemplo n.º 27
0
void doMiddle(struct cart *theCart)
/* Print the body of an html file.   */
{
char cond_str[255];
struct sqlConnection *conn;
char *proteinAC;
char *chp, *chp1, *chp9;
char *debugTmp = NULL;
char *chromStr, *cdsStartStr, *cdsEndStr, posStr[255];

char *supportedGenomeDatabase;

char *answer;
char *queryID;

/* Initialize layout and database. */
cart = theCart;

/* Uncomment this to see parameters for debugging. */
/* Be careful though, it breaks if custom track
 * is more than 4k */
/*
{ struct dyString *state = cgiUrlString();
  hPrintf("State: %s\n", state->string);
}
*/

queryID = cartOptionalString(cart, "proteinID");
if (sameString(queryID, ""))
    {
    hUserAbort("Please go back and enter a gene symbol or a Swiss-Prot/TrEMBL protein ID.\n");
    }

if (cgiVarExists("db"))
    {
    /* if db is known, get key variables set */
    proteinInSupportedGenome = TRUE;
    database = cgiOptionalString("db");
    organism = hDbOrganism(database);
    protDbName = hPdbFromGdb(database);
    proteinID  = strdup(queryID);
    }
else
    {
    protCntInSwissByGene = searchProteinsInSwissProtByGene(queryID);
    /* no CGI 'db' variable means it did not come in from GB but from pbGateway */
    /* search existing GB databases to see if this protein can be found */
    protCntInSupportedGenomeDb =
        searchProteinsInSupportedGenomes(queryID, &supportedGenomeDatabase);
    if ((protCntInSupportedGenomeDb > 1) || protCntInSwissByGene >= 1)
        {
	/* more than 1 proteins match the query ID, present selection web page */
	proteinInSupportedGenome = 1;
	presentProteinSelections(queryID, protCntInSwissByGene, protCntInSupportedGenomeDb);
	return;
	}
    else
        {
	if (protCntInSupportedGenomeDb == 1)
	    {
	    /* one and only one protein found in a genome DB that support KG and PB */
	    proteinInSupportedGenome = TRUE;
	    database = strdup(supportedGenomeDatabase);
	    organism = hDbOrganism(database);
	    protDbName = hPdbFromGdb(database);
            proteinID=strdup(queryID);
	    }
	else
	    {
	    /* not found in genome DBs that support KG/PB */
	    /* now search PROTEOME_DB_NAMES to see if this protein is there. */

	    answer = uniProtFindPrimAcc(queryID);
	    if (answer == NULL)
		{
	        hUserAbort("'%s' does not seem to be a valid UniProtKB protein ID or a gene "
	                   "symbol.<br><br>Click <A HREF=\"../cgi-bin/pbGateway\">here</A> "
	                   "to start another query.", queryID);
                }

	    proteinInSupportedGenome = FALSE;
	    database = strdup(GLOBAL_PB_DB);
	    organism = strdup("");
            protDbName = strdup(PROTEOME_DB_NAME);
	    proteinID = strdup(answer);
	    }
	}

    if (proteinInSupportedGenome)
        {
        spConn = sqlConnect(database);
        sqlSafefFrag(cond_str, sizeof(cond_str), "alias='%s'", queryID);
        proteinID = sqlGetField(database, "kgSpAlias", "spID", cond_str);

        sqlSafefFrag(cond_str, sizeof(cond_str), "spID='%s'", proteinID);
        answer = sqlGetField(database, "kgXref", "spDisplayID", cond_str);

	sqlSafefFrag(cond_str, sizeof(cond_str), "proteinID='%s'", answer);
        chromStr    = sqlGetField(database, "knownGene", "chrom", cond_str);
	if (chromStr)
	    {
	    cdsStartStr = sqlGetField(database, "knownGene", "cdsStart", cond_str);
	    cdsEndStr   = sqlGetField( database, "knownGene", "cdsEnd", cond_str);
	    safef(posStr, sizeof(posStr), "%s:%s-%s", chromStr, cdsStartStr, cdsEndStr);
	    positionStr = strdup(posStr);
	    cartSetString(cart, "position", positionStr);
	    cartSetString(cart, "organism", organism);
	    }
	}
    }
/* print out key variables for debugging */
/* printf("<br>before enter main section: <br>proteinInSupportedGenome=%d<br>proteinID=%s <br>database=%s <br>organism=%s <br>protDbName=%s\n",
proteinInSupportedGenome, proteinID, database, organism, protDbName);fflush(stdout);
*/

if (hTableExists(database, "kgProtMap2"))
    {
    kgVersion = KG_III;
    strcpy(kgProtMapTableName, "kgProtMap2");
    }

debugTmp = cartUsualString(cart, "hgDebug", "off");
if(sameString(debugTmp, "on"))
    hgDebug = TRUE;
else
    hgDebug = FALSE;
conn  = hAllocConn(database);
hgsid     = cartOptionalString(cart, "hgsid");
if (hgsid != NULL)
    {
    safef(hgsidStr, sizeof(hgsidStr), "&hgsid=%s", hgsid);
    }
else
    {
    strcpy(hgsidStr, "");
    }

/* check proteinID to see if it is a valid SWISS-PROT/TrEMBL accession or display ID */
/* then assign the accession number to global variable proteinID */
sqlSafefFrag(cond_str, sizeof(cond_str), "accession='%s'", proteinID);
proteinAC = sqlGetField(protDbName, "spXref3", "accession", cond_str);
if (proteinAC == NULL)
    {
    sqlSafefFrag(cond_str, sizeof(cond_str), "displayID='%s'", proteinID);
    proteinAC = sqlGetField(protDbName, "spXref3", "accession", cond_str);
    if (proteinAC == NULL)
	{
	hUserAbort("'%s' does not seem to be a valid Swiss-Prot/TrEMBL protein ID or gene symbol.<br><br>Click <A HREF=\"../cgi-bin/pbGateway\">here</A> to start another query."
	, proteinID);
	}
    else
	{
	protDisplayID = proteinID;
	proteinID = proteinAC;
	}
    }
else
    {
    sqlSafefFrag(cond_str, sizeof(cond_str), "accession='%s'", proteinID);
    protDisplayID = sqlGetField(protDbName, "spXref3", "displayID", cond_str);
    }

if (proteinInSupportedGenome)
    {
    if (kgVersion == KG_III)
        {
        sqlSafefFrag(cond_str, sizeof(cond_str), "spId='%s'", proteinID);
        mrnaID = sqlGetField(database, "kgXref", "kgId", cond_str);
	}
    else
        {
        sqlSafefFrag(cond_str, sizeof(cond_str), "proteinID='%s'", protDisplayID);
        mrnaID = sqlGetField(database, "knownGene", "name", cond_str);
        }
    }
else
    {
    mrnaID = NULL;
    positionStr = NULL;
    }

sqlSafefFrag(cond_str, sizeof(cond_str), "accession='%s'", proteinID);
description = sqlGetField(protDbName, "spXref3", "description", cond_str);

if (positionStr != NULL)
    {
    chp = strstr(positionStr, ":");
    *chp = '\0';
    prevGBChrom = cloneString(positionStr);

    chp1 = chp + 1;
    chp9 = strstr(chp1, "-");
    *chp9 = '\0';
    prevGBStartPos = atoi(chp1);
    chp1 = chp9 + 1;
    prevGBEndPos   = atoi(chp1);
    }
else
    {
    prevGBChrom    = NULL;
    prevGBStartPos = -1;
    prevGBEndPos   = -1;
    }

/* Do main display. */
if (cgiVarExists("pbt.psOutput"))
    handlePostscript();
else
    {
    doTrackForm(NULL, NULL);
    }
}
Exemplo n.º 28
0
void doTracks(char *proteinID, char *mrnaID, char *aa, int *yOffp, char *psOutput)
/* draw various protein tracks */
{
int l;

char aaOrigOffsetStr[20];
int hasResFreq;
char uniProtDbName[50];
char *protDbDate;
char *chrom;
char strand;
char *kgId, *kgPep, *protPep;
char cond_str[255];
char *answer;
//int i, ll;
//char *chp1, *chp2;

g_font = mgSmallFont();
safef(pbScaleStr, sizeof(pbScaleStr), "%d", pbScale);

if (psOutput != NULL)
    {
    pbScale         = atoi(cartOptionalString(cart, "pbt.pbScaleStr"));
    }

if (cgiOptionalString("trackOffset") != NULL)
	{
	trackOrigOffset = atoi(cgiOptionalString("trackOffset")); 
	}

if (cgiOptionalString("pbScaleStr") != NULL)
	{
	pbScale  = atoi(cgiOptionalString("pbScaleStr")); 
	}

if (cgiOptionalString("pbScale") != NULL)
    {
    scaleButtonPushed = TRUE;
    if (strcmp(cgiOptionalString("pbScale"), "1/6")  == 0) pbScale = 1;
    if (strcmp(cgiOptionalString("pbScale"), "1/2")  == 0) pbScale = 3;
    if (strcmp(cgiOptionalString("pbScale"), "FULL") == 0) pbScale = 6;
    if (strcmp(cgiOptionalString("pbScale"), "DNA")  == 0) pbScale =22;
    safef(pbScaleStr, sizeof(pbScaleStr), "%d", pbScale);
    cgiMakeHiddenVar("pbScaleStr", pbScaleStr);
    }
else
    {
    scaleButtonPushed = FALSE;
    }

if (psOutput == NULL)
{
if (cgiVarExists("pbt.left3"))
    {
    relativeScroll(-0.95);
    initialWindow = FALSE;
    }
else if (cgiVarExists("pbt.left2"))
    {
    relativeScroll(-0.475);
    initialWindow = FALSE;
    }
else if (cgiVarExists("pbt.left1"))
    {
    relativeScroll(-0.02);
    initialWindow = FALSE;
    }
else if (cgiVarExists("pbt.right1"))
    {
    relativeScroll(0.02);
    initialWindow = FALSE;
    }
else if (cgiVarExists("pbt.right2"))
    {
    relativeScroll(0.475);
    initialWindow = FALSE;
    }
else if (cgiVarExists("pbt.right3"))
    {
    relativeScroll(0.95);
    initialWindow = FALSE;
    }
}

dnaUtilOpen();

l=strlen(aa);

/* initialize AA properties */
aaPropertyInit(&hasResFreq);
sfCount = getSuperfamilies2(proteinID);
if (sfCount == 0)
    {
    sfCount = getSuperfamilies(proteinID);
    }
if (mrnaID != NULL)
    {
    if (kgVersion == KG_III)
    	{
	doExonTrack = FALSE;
	sqlSafefFrag(cond_str, sizeof(cond_str), "spId='%s'", proteinID);
        kgId = sqlGetField(database, "kgXref", "kgId", cond_str);
	if (kgId != NULL)
	    {
	    sqlSafefFrag(cond_str, sizeof(cond_str), "name='%s'", kgId);
            kgPep = sqlGetField(database, "knownGenePep", "seq", cond_str);
      	    //printf("<pre><br>%s", kgPep);fflush(stdout);
	    if (kgPep != NULL)
	    	{
		if (strstr(protDbName, "proteins") != NULL)
		    {
		    protDbDate = strstr(protDbName, "proteins") + strlen("proteins");
		    safef(uniProtDbName, sizeof(uniProtDbName),"sp%s", protDbDate);
		
		    sqlSafefFrag(cond_str, sizeof(cond_str), "acc='%s'", proteinID);
            	    protPep = sqlGetField(uniProtDbName, "protein", "val", cond_str);
            	    //printf("<br>%s\n", protPep);fflush(stdout);
            	    if (protPep != NULL)
		    	{
			if (sameWord(kgPep, protPep))
			    {
			    //printf("<br>MATCH!\n");fflush(stdout);
		    	    sqlSafefFrag(cond_str, sizeof(cond_str), "qName='%s'", kgId);
            	    	    answer = sqlGetField(database, kgProtMapTableName, 
			    			 "qName", cond_str);
            	    	    if (answer != NULL)
			    	{
    			    	/* NOTE: passing in kgId instead of proteinID because
					 kgProtMap2's qName uses kgId instead of 
					 protein display ID */
    			    	getExonInfo(kgId, &exCount, &chrom, &strand);
			    	assert(exCount > 0);
				doExonTrack = TRUE;
			    	}
			    }
			/*
			else
			    {
			    chp1 = kgPep;
			    printf("<br>");
			    chp2 = protPep;
			    ll = strlen(kgPep);
			    if (strlen(protPep) < ll) ll= strlen(protPep);
			    for (i=0; i<ll; i++)
			    	{
				if (*chp1 != *chp2)
					{
					printf("%c", *chp1);
					}
				else
					{
					printf(".");
					}
				chp1++; chp2++;
				}
			    }
			    //printf("</pre>");fflush(stdout);
			*/
			}
		    }
		}
	    }
	}
    else
    	{
	doExonTrack = TRUE;
    	getExonInfo(proteinID, &exCount, &chrom, &strand);
    	assert(exCount > 0);
	}
    /* do the following only if pbTracks called doTracks() */
    if (initialWindow && IAmPbTracks)
	{
	prevGBOffsetSav = calPrevGB(exCount, chrom, strand, l, yOffp, proteinID, mrnaID);
	trackOrigOffset = prevGBOffsetSav;
    	if (trackOrigOffset > (protSeqLen*pbScale - 600))
	    trackOrigOffset = protSeqLen*pbScale - 600;
	/* prevent negative value */
	if (trackOrigOffset < 0) trackOrigOffset = 0;
	}

    /* if this if for PDF/Postscript, the trackOrigOffset is already calculated previously,
        use the saved value */
    if (psOutput != NULL)
    	{
    	trackOrigOffset = atoi(cartOptionalString(cart, "pbt.trackOffset"));
    	}
    }

/*printf("<br>%d %d<br>%d %d\n", prevGBStartPos, prevGBEndPos, 
	blockGenomeStartPositive[exCount-1], blockGenomeStartPositive[0]); fflush(stdout);
*/
if (strand == '-')
    {
    if ((prevGBStartPos <= blockGenomeStartPositive[exCount-1]) && (prevGBEndPos >= blockGenomeStartPositive[0]))
    	{
    	showPrevGBPos = FALSE;
    	}
    }
else
    {
    if ((prevGBStartPos <= blockGenomeStartPositive[0]) && (prevGBEndPos >= blockGenomeStartPositive[exCount-1]))
    	{
    	showPrevGBPos = FALSE;
    	}
    }

if ((cgiOptionalString("aaOrigOffset") != NULL) && scaleButtonPushed)
     {
     trackOrigOffset = atoi(cgiOptionalString("aaOrigOffset"))*pbScale;
     }

pixWidth = 160+ protSeqLen*pbScale;
if (pixWidth > MAX_PB_PIXWIDTH)
   {
   pixWidth = MAX_PB_PIXWIDTH;
   }

if ((protSeqLen*pbScale - trackOrigOffset) < MAX_PB_PIXWIDTH)
    {
    pixWidth = protSeqLen*pbScale - trackOrigOffset + 160;
    }

if (pixWidth < 550) pixWidth = 550;

insideWidth = pixWidth-gfxBorder;

if (proteinInSupportedGenome)
    {
    pixHeight = 250;
    }
else
    {
    pixHeight = 215;
    }

if (sfCount > 0) pixHeight = pixHeight + 20;

/* make room for individual residues display */
if (pbScale >=6)  pixHeight = pixHeight + 20;
if (pbScale >=18) pixHeight = pixHeight + 30;

if (psOutput)
    {
    vg = vgOpenPostScript(pixWidth, pixHeight, psOutput);
    suppressHtml = TRUE;
    hideControls = TRUE;
    }
else
    {
    trashDirFile(&gifTn, "pbt", "pbt", ".png");
    vg = vgOpenPng(pixWidth, pixHeight, gifTn.forCgi, FALSE);
    }

/* Put up horizontal scroll controls. */
hWrites("Move ");
hButton("pbt.left3", "<<<");
hButton("pbt.left2", " <<");
hButton("pbt.left1", " < ");
hButton("pbt.right1", " > ");
hButton("pbt.right2", ">> ");
hButton("pbt.right3", ">>>");

hPrintf(" &nbsp &nbsp ");

/* Put up scaling controls. */
hPrintf("Current scale: ");
if (pbScale == 1)  hPrintf("1/6 ");
if (pbScale == 3)  hPrintf("1/2 ");
if (pbScale == 6)  hPrintf("FULL ");
if (pbScale == 22) hPrintf("DNA ");

hPrintf(" &nbsp&nbsp Rescale to ");
hPrintf("<INPUT TYPE=SUBMIT NAME=\"pbScale\" VALUE=\"1/6\">\n");
hPrintf("<INPUT TYPE=SUBMIT NAME=\"pbScale\" VALUE=\"1/2\">\n");
hPrintf("<INPUT TYPE=SUBMIT NAME=\"pbScale\" VALUE=\"FULL\">\n");
if (kgVersion == KG_III)
    {
    /* for KG III, the protein has to exist in the kgProtMap2 table 
       (which will turn on doExonTrack flag)
       to provide the genomic position data needed for DNA sequence display */
    if ((proteinInSupportedGenome) && (doExonTrack))
    hPrintf("<INPUT TYPE=SUBMIT NAME=\"pbScale\" VALUE=\"DNA\">\n");
    }
else
    {
    if (proteinInSupportedGenome) 
   	hPrintf("<INPUT TYPE=SUBMIT NAME=\"pbScale\" VALUE=\"DNA\">\n");
    }
hPrintf("<FONT SIZE=1><BR><BR></FONT>\n");

g_vg = vg;

pbRed    = vgFindColorIx(g_vg, 0xf9, 0x51, 0x59);
pbBlue   = vgFindColorIx(g_vg, 0x00, 0x00, 0xd0);
bkgColor = vgFindColorIx(vg, 255, 254, 232);

vgBox(vg, 0, 0, insideWidth, pixHeight, bkgColor);

/* Start up client side map. */
hPrintf("<MAP Name=%s>\n", mapName);

vgSetClip(vg, 0, gfxBorder, insideWidth, pixHeight - 2*gfxBorder);

/* start drawing indivisual tracks */

doAAScale(l, yOffp, 1);

if (pbScale >= 6)  doResidues(aa, l, yOffp);

if (pbScale >= 18) doDnaTrack(chrom, strand, exCount, l, yOffp);

if ((mrnaID != NULL) && showPrevGBPos)
    {
    doPrevGB(exCount, chrom, strand, l, yOffp, proteinID, mrnaID);
    }

if (mrnaID != NULL)
    {
    if (doExonTrack) doExon(exCount, chrom, l, yOffp, proteinID, mrnaID);
    }

doCharge(aa, l, yOffp);

doHydrophobicity(aa, l, yOffp);

doCysteines(aa, l, yOffp);

if (sfCount > 0) doSuperfamily(ensPepName, sfCount, yOffp); 

if (hasResFreq) doAnomalies(aa, l, yOffp);

doAAScale(l, yOffp, -1);

vgClose(&vg);

/* Finish map and save out picture and tell html file about it. */
hPrintf("</MAP>\n");

/* put tracks image here */

hPrintf(
"\n<IMG SRC=\"%s\" BORDER=1 WIDTH=%d HEIGHT=%d USEMAP=#%s><BR>",
        gifTn.forCgi, pixWidth, pixHeight, mapName);

if (proteinInSupportedGenome)
    {
    hPrintf("<A HREF=\"../goldenPath/help/pbTracksHelpFiles/pbTracksHelp.shtml#tracks\" TARGET=_blank>");
    }
else
    {
    if (hIsGsidServer())
	{
	hPrintf("<A HREF=\"../goldenPath/help/pbTracksHelpFiles/pbGsid/pbTracksHelp.shtml#tracks\" TARGET=_blank>");
    	}
    else
	{
	hPrintf("<A HREF=\"../goldenPath/help/pbTracksHelpFiles/pbTracksHelp.shtml#tracks\" TARGET=_blank>");
    	}
    }

hPrintf("Explanation of Protein Tracks</A><br>");

safef(trackOffset, sizeof(trackOffset), "%d", trackOrigOffset);
cgiMakeHiddenVar("trackOffset", trackOffset);

/* remember where the AA base origin is so that it can be passed to next PB page */
aaOrigOffset = trackOrigOffset/pbScale;
safef(aaOrigOffsetStr, sizeof(aaOrigOffsetStr), "%d", aaOrigOffset);
cgiMakeHiddenVar("aaOrigOffset", aaOrigOffsetStr);

/* save the following state variables, to be used by PDF/Postcript processing */
cartSetString(cart,"pbt.pbScaleStr", pbScaleStr);
cartSetString(cart,"pbt.trackOffset", trackOffset);
cartSaveSession(cart);
fflush(stdout);
}
Exemplo n.º 29
0
void getDbGenomeClade(struct cart *cart, char **retDb, char **retGenome,
		      char **retClade, struct hash *oldVars)
/* Examine CGI and cart variables to determine which db, genome, or clade
 *  has been selected, and then adjust as necessary so that all three are
 * consistent.  Detect changes and reset db-specific cart variables.
 * Save db, genome and clade in the cart so it will be consistent hereafter.
 * The order of preference here is as follows:
 * If we got a request that explicitly names the db, that takes
 * highest priority, and we synch the organism to that db.
 * If we get a cgi request for a specific organism then we use that
 * organism to choose the DB.  If just clade, go from there.

 * In the cart only, we use the same order of preference.
 * If someone requests an Genome we try to give them the same db as
 * was in their cart, unless the Genome doesn't match.
 */
{
boolean gotClade = hGotClade();
*retDb = cgiOptionalString(dbCgiName);
*retGenome = cgiOptionalString(orgCgiName);
*retClade = cgiOptionalString(cladeCgiName);
/* phoneHome business */
phoneHome();

/* Was the database passed in as a cgi param?
 * If so, it takes precedence and determines the genome. */
if (*retDb && hDbExists(*retDb))
    {
    *retGenome = hGenome(*retDb);
    }
/* If no db was passed in as a cgi param then was the organism (a.k.a. genome)
 * passed in as a cgi param?
 * If so, the we use the proper database for that genome. */
else if (*retGenome && !sameWord(*retGenome, "0"))
    {
    *retDb = getDbForGenome(*retGenome, cart);
    *retGenome = hGenome(*retDb);
    }
else if (*retClade && gotClade)
    {
    *retGenome = hDefaultGenomeForClade(*retClade);
    *retDb = getDbForGenome(*retGenome, cart);
    }
/* If no cgi params passed in then we need to inspect the session */
else
    {
    *retDb = cartOptionalString(cart, dbCgiName);
    *retGenome = cartOptionalString(cart, orgCgiName);
    *retClade = cartOptionalString(cart, cladeCgiName);
    /* If there was a db found in the session that determines everything. */
    if (*retDb && hDbExists(*retDb))
        {
        *retGenome = hGenome(*retDb);
        }
    else if (*retGenome && !sameWord(*retGenome, "0"))
	{
	*retDb = hDefaultDbForGenome(*retGenome);
	}
    else if (*retClade && gotClade)
	{
        *retGenome = hDefaultGenomeForClade(*retClade);
	*retDb = getDbForGenome(*retGenome, cart);
	}
    /* If no organism in the session then get the default db and organism. */
    else
	{
	*retDb = hDefaultDb();
	*retGenome = hGenome(*retDb);
        }
    }
*retDb = cloneString(*retDb);
*retGenome = cloneString(*retGenome);
*retClade = hClade(*retGenome);

/* Detect change of database and reset db-specific cart variables: */
if (oldVars)
    {
    char *oldDb = hashFindVal(oldVars, "db");
    char *oldOrg = hashFindVal(oldVars, "org");
    char *oldClade = hashFindVal(oldVars, "clade");
    if ((!IS_CART_VAR_EMPTY(oldDb)    && differentWord(oldDb, *retDb)) ||
        (!IS_CART_VAR_EMPTY(oldOrg)   && differentWord(oldOrg, *retGenome)) ||
        (!IS_CART_VAR_EMPTY(oldClade) && differentWord(oldClade, *retClade)))
	{
	/* Change position to default -- unless it was passed in via CGI: */
	if (cgiOptionalString("position") == NULL)
	    cartSetString(cart, "position", hDefaultPos(*retDb));
	/* hgNear search term -- unless it was passed in via CGI: */
	if (cgiOptionalString("near_search") == NULL)
	    cartRemove(cart, "near_search");
	/* hgBlat results (hgUserPsl track): */
	cartRemove(cart, "ss");
	/* hgTables correlate: */
	cartRemove(cart, "hgta_correlateTrack");
	cartRemove(cart, "hgta_correlateTable");
	cartRemove(cart, "hgta_correlateGroup");
	cartRemove(cart, "hgta_correlateOp");
	cartRemove(cart, "hgta_nextCorrelateTrack");
	cartRemove(cart, "hgta_nextCorrelateTable");
	cartRemove(cart, "hgta_nextCorrelateGroup");
	cartRemove(cart, "hgta_nextCorrelateOp");
	cartRemove(cart, "hgta_corrWinSize");
	cartRemove(cart, "hgta_corrMaxLimitCount");
	}
    }

/* Save db, genome (as org) and clade in cart. */
cartSetString(cart, "db", *retDb);
cartSetString(cart, "org", *retGenome);
if (gotClade)
    cartSetString(cart, "clade", *retClade);
}
static void wiggleLinkedFeaturesDraw(struct track *tg, 
	int seqStart, int seqEnd,
struct hvGfx *hvg, int xOff, int yOff, int width, 
	MgFont *font, Color color, enum trackVisibility vis)
	/* Currently this routine is adapted from Terry's 
	* linkedFeatureSeriesDraw() routine.
	* It is called for 'sample' tracks as specified in the trackDb.ra.
	* and it looks at the cart to decide whether to interpolate, fill blocks,
	* and use anti-aliasing.*/
{
	int i;
	struct linkedFeatures *lf;
	struct simpleFeature *sf;
	int y = yOff;
	int heightPer = tg->heightPer;
	int lineHeight = tg->lineHeight;
	int x1,x2;
	boolean isFull = (vis == tvFull);
	Color bColor = tg->ixAltColor;
	double scale = scaleForPixels(width);
	int prevX = -1;
	int gapPrevX = -1;
	double prevY = -1;
	double y1 = -1, y2;
	int ybase;
	int sampleX, sampleY; /* A sample in sample coordinates. 
						  * Sample X coordinate is chromosome coordinate.
						  * Sample Y coordinate is usually 0-1000 */
	int binCount = 1.0/tg->scaleRange;   /* Maximum sample Y coordinate. */
	int bin;	      /* Sample Y coordinates are first converted to
					  * bin coordinates, and then to pixels.  I'm not
					  * totally sure why.  */



	int currentX, currentXEnd, currentWidth;

	int leftSide, rightSide;

	int noZoom = 1;
	enum wiggleOptEnum wiggleType;
	char *interpolate = NULL;
	char *aa = NULL; 
	boolean antiAlias = FALSE;
	int fill; 
	int lineGapSize;
	double min0, max0;

	char o1[128]; /* Option 1 - linear interp */
	char o2[128]; /* Option 2 - anti alias */
	char o3[128]; /* Option 3 - fill */
	char o4[128]; /* Option 4 - minimum vertical range cutoff of plot */	
	char o5[128]; /* Option 5 - maximum vertical range cutoff of plot */
	char o6[128]; /* Option 6 - max gap where interpolation is still done */
	char cartStr[64];
	char *fillStr;

	double hFactor;
	double minRange, maxRange;
	double minRangeCutoff, maxRangeCutoff;


	Color gridColor = hvGfxFindRgb(hvg, &guidelineColor); /* for horizontal lines*/

	lf=tg->items;    
	if(lf==NULL) return;

	//take care of cart options
	safef( o1, 128,"%s.linear.interp", tg->track);
	safef( o2, 128, "%s.anti.alias", tg->track);
	safef( o3, 128,"%s.fill", tg->track);
	safef( o4, 128,"%s.min.cutoff", tg->track);
	safef( o5, 128,"%s.max.cutoff", tg->track);
	safef( o6, 128,"%s.interp.gap", tg->track);

	interpolate = cartUsualString(cart, o1, "Linear Interpolation");
	wiggleType = wiggleStringToEnum(interpolate);
	aa = cartUsualString(cart, o2, "on");
	antiAlias = sameString(aa, "on");

	//don't fill gcPercent track by default (but fill others)
	if(sameString( tg->table, "pGC") && sameString(database,"zooHuman3"))
	{
		fillStr = cartUsualString(cart, o3, "0");
	}
	else
	{
		fillStr = cartUsualString(cart, o3, "1");
	}
	fill = atoi(fillStr);
	cartSetString(cart, o3, fillStr );

	//the 0.1 is so the label doesn't get truncated with integer valued user input min
	//display range.
	minRangeCutoff = max( atof(cartUsualString(cart,o4,"0.0"))-0.1, tg->minRange );
	maxRangeCutoff = min( atof(cartUsualString(cart,o5,"1000.0"))+0.1, tg->maxRange);

	lineGapSize = atoi(cartUsualString(cart, o6, "200"));

	//update cart settings to reflect truncated range cutoff values
	cartSetString( cart, "win", "F" );
	safef( cartStr, 64, "%g", minRangeCutoff );
	cartSetString( cart, o4, cartStr );
	safef( cartStr, 64, "%g", maxRangeCutoff );
	cartSetString( cart, o5, cartStr );

	heightPer = tg->heightPer+1;
	hFactor = (double)heightPer*tg->scaleRange;

	//errAbort( "min=%g, max=%g\n", minRangeCutoff, maxRangeCutoff );


	if( sameString( tg->table, "zoo" ) || sameString( tg->table, "zooNew" ) )
		binCount = binCount - 100;    //save some space at top, between each zoo species

	minRange = whichSampleBin( minRangeCutoff, tg->minRange, tg->maxRange, binCount );
	maxRange = whichSampleBin( maxRangeCutoff, tg->minRange, tg->maxRange, binCount );

	//errAbort( "(%g,%g) cutoff=(%g,%g)\n", tg->minRange, tg->maxRange, minRangeCutoff, maxRangeCutoff );


	if( sameString( tg->table, "zoo" ) || sameString( tg->table, "zooNew" ) )
	{
		/*Always interpolate zoo track (since gaps are explicitly defined*/
		lineGapSize = -1;
	}
	else if( tg->minRange == 0 && tg->maxRange == 8 )    //range for all L-score tracks
	{
		if( isFull )
		{
			min0 = whichSampleNum( minRange, tg->minRange, tg->maxRange, binCount );
			max0 = whichSampleNum( maxRange, tg->minRange, tg->maxRange,  binCount );
			for( i=1; i<=6; i++ )
				drawWiggleHorizontalLine(hvg, (double)i, min0, max0,
				binCount, y, hFactor, heightPer, gridColor );
		}
	}

	for(lf = tg->items; lf != NULL; lf = lf->next) 
	{
		gapPrevX = -1;
		prevX = -1;
		ybase = (int)((double)y+hFactor+(double)heightPer);


		for (sf = lf->components; sf != NULL; sf = sf->next)
		{
			sampleX = sf->start;
			sampleY = sf->end - sampleX;	// Stange encoding but so it is. 
			// It is to deal with the fact that
			// for a BED: sf->end = sf->start + length
			// but in our case length = height (or y-value)
			// so to recover height we take
			// height = sf->end - sf->start.
			// Otherwise another sf variable would 
			// be needed.


			/*mapping or sequencing gap*/
			if (sampleY == 0)
			{
				bin = -whichSampleBin( (int)((maxRange - minRange)/5.0+minRange), 
					minRange, maxRange, binCount );
				y1 = (int)((double)y+((double)bin)* hFactor+(double)heightPer);
				if( gapPrevX >= 0 )
					drawScaledBox(hvg, sampleX, gapPrevX, scale, 
					xOff, (int)y1, (int)(.10*heightPer), shadesOfGray[2]);
				gapPrevX = sampleX;
				prevX = -1; /*connect next point with gray bar too*/
				continue;
			}
			if (sampleY > maxRange)
				sampleY = maxRange;
			if (sampleY < minRange)
				sampleY = minRange;
			bin = -whichSampleBin( sampleY, minRange, maxRange, binCount );


			x1 = round((double)(sampleX-winStart)*scale) + xOff;
			y1 = (int)((double)y+((double)bin)* hFactor+(double)heightPer);



			if (prevX > 0)
			{
				y2 = prevY;
				x2 = round((double)(prevX-winStart)*scale) + xOff;
				if( wiggleType == wiggleLinearInterpolation ) 
					/*connect samples*/
				{
					if( lineGapSize < 0 || prevX - sampleX <= lineGapSize )   
						/*don't interpolate over large gaps*/
					{
						if (fill)
							hvGfxFillUnder(hvg, x1,y1, x2,y2, ybase, bColor);
						else
							hvGfxLine(hvg, x1,y1, x2,y2, color);
					}
				}
			}

			//if( x1 < 0 || x1 > tl.picWidth )
			//printf("x1 = %d, sampleX=%d, winStart = %d\n<br>", x1, sampleX, winStart );
			if( x1 >= 0 && x1 <= tl.picWidth )
			{
				/* Draw the points themselves*/
				drawScaledBox(hvg, sampleX, sampleX+1, scale, xOff, (int)y1-1, 3, color);
				if( fill )
					drawScaledBox(hvg, sampleX, sampleX+1, scale, xOff, (int)y1+2, 
					ybase-y1-2, bColor);
			}

			prevX = gapPrevX = sampleX;
			prevY = y1;
		}

		leftSide = max( tg->itemStart(tg,lf), winStart );
		rightSide = min(  tg->itemEnd(tg,lf), winEnd );

		currentX =  round((double)((int)leftSide-winStart)*scale) + xOff;
		currentXEnd =  round((double)((int)rightSide-winStart)*scale) + xOff;
		currentWidth = currentXEnd - currentX;

		if( noZoom && isFull )
		{
			fprintf(stderr, "mapBoxHc(id: %s;) in wiggleLinkedFeatures\n", 
				tg->track);
			mapBoxHc(hvg, lf->start, lf->end, currentX ,y, currentWidth,
				heightPer, tg->track, tg->mapItemName(tg, lf), tg->itemName(tg, lf));

			if( lf->next != NULL )
				y += sampleUpdateY( lf->name, lf->next->name, lineHeight );
			else
				y += lineHeight;
		}

	}
}