<repo_name>uvic-proteincentre/mousequapro<file_sep>/backend/src/qmpkbapp/downLoadData.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import Counter
from itertools import combinations
import ast
from operator import itemgetter
import operator
import json
import re,sys
import itertools
from collections import OrderedDict
import datetime
from statistics import mean
# function to generate peptidebased info into nested json format
def updateDataToDownload(jfinaldata):
	tempjfinaldata=[]
	for jitem in jfinaldata:
		sumtempconcendata=jitem["Summary Concentration Range Data"]
		alltempconcendata=jitem["All Concentration Range Data"]
		allConDataSampleLLOQ=jitem["All Concentration Range Data-Sample LLOQ Based"]


		sumconcinfo=jitem["Summary Concentration Range Data"].split(';')

		sumtempconcendata=['|'.join(x.split('|')[1:]) for x in sumtempconcendata.split(';')]
		alltempconcendata=['|'.join(x.split('|')[1:]) for x in alltempconcendata.split(';')]
		allConDataSampleLLOQ=['|'.join(x.split('|')[1:]) for x in allConDataSampleLLOQ.split(';')]

		sumconclist=[]
		for scitem in sumconcinfo:
			scinfo =scitem.split('|')
			measuredSampSize=int(scinfo[5].split('/')[1])
			for i in range(0,measuredSampSize):
				tempStempidInfo=scinfo[1:5]
				tempStempidInfo.insert(2,str(i+1))
				stempid='|'.join(map(str,tempStempidInfo))
				sumconclist.append([stempid,'NA|NA|NA'])
		for s in sumconclist:
			for x in allConDataSampleLLOQ:
				if len(x)>0:
					tempID='|'.join(x.split('|')[:5])
					if tempID == s[0]:
						s[1]='|'.join(x.split('|')[5:])
		finalAllConDataSampleLLOQ=['|'.join(y) for y in sumconclist]
		jitem["Summary Concentration Range Data"]=';'.join(sumtempconcendata)

		jitem["All Concentration Range Data"]=';'.join(alltempconcendata)
		jitem["All Concentration Range Data-Sample LLOQ Based"]=';'.join(finalAllConDataSampleLLOQ)

		tempjfinaldata.append(jitem)

	return tempjfinaldata<file_sep>/client/qmpkb-app/src/app/basic-search-without-example-result/basic-search-without-example-result.component.ts
import { Component, OnInit, Input, Renderer } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray } from '@angular/forms';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-basic-search-without-example-result',
  templateUrl: './basic-search-without-example-result.component.html',
  styleUrls: ['./basic-search-without-example-result.component.css']
})
export class BasicSearchWithoutExampleResultComponent implements OnInit {
  searchQuery: string;
  baseUrl;
  @Input()
  passedQuery: string;
  errorStr:Boolean;
  public alertIsVisible:boolean= false;

  constructor(
    private router: Router,
    private http: HttpClient,
    private renderer: Renderer,
    private _qmpkb:QmpkbService,
    private spinner: NgxSpinnerService
  ) { }


  ngOnInit() {
  }

  submitSearch(event,formData){

  	let searchedQuery = formData.value['searchterm']
    if (searchedQuery){
      this.spinner.show();
      let tempURL=window.location.origin+'/results/?searchterm='+searchedQuery;

      //window.open(tempURL,'_blank');
      //window.focus();
      location.assign(tempURL);

    }

  }

  moveAdv(){
    location.assign('/');
  }

}<file_sep>/client/qmpkb-app/src/app/drug-bank/drug-bank.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DrugBankComponent } from './drug-bank.component';

describe('DrugBankComponent', () => {
  let component: DrugBankComponent;
  let fixture: ComponentFixture<DrugBankComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DrugBankComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DrugBankComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
<file_sep>/backend/src/qmpkbapp/api/urls.py
from rest_framework import routers
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
from django.views.generic import RedirectView
from django.conf import settings


from .views import fileApi

urlpatterns = [
	url(r'^$',fileApi),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns +=static(settings.FILE_URL,document_root=settings.FILE_ROOT)<file_sep>/backend/updatefile/generate_final_data_report_qmpkp.py
import os,subprocess,psutil,re,shutil,datetime,sys,glob
import urllib,urllib2,urllib3
from bioservices.kegg import KEGG
from socket import error as SocketError
import errno
from Bio import SeqIO
import xmltodict
from xml.dom import minidom
from xml.parsers.expat import ExpatError
import random, time
from goatools import obo_parser
import csv
import json
import pandas as pd
import requests
from collections import Counter
from itertools import combinations
from xml.etree import cElementTree as ET
import pickle
import cPickle
import operator
from compileSkylineDataToFit import compileSkylineFile
import numpy as np
from statistics import mean
from presencePepSeqInHuman import presencePepSeqHuman
from ncbiGeneAPI import ncbiGeneExp
from addModCol import addModCol
from addSelCol import addSelCol
from maketotalassaypep import totalAssayPep
from preloadData import preLoadJsonData
from uploadDataElasticSearch import uploadData
import ctypes
from generate_pre_downloadable_file import preDownloadFile

def makemergedict(listOfResourceFile,colname,humanuniprotdic,humankdeggic):
	mergedictdata={}
	humanmousemergedic={}
	humanfuncdict = cPickle.load(open(humanuniprotdic, 'rb'))
	humanKEGGdict = cPickle.load(open(humankdeggic, 'rb'))
	for fitem in listOfResourceFile:
		with open(fitem,'r') as pepfile:
			reader = csv.DictReader(pepfile, delimiter='\t')
			for row in reader:
				info=[]
				for i in colname:
					info.append(str(row[i]).strip())
				if mergedictdata.has_key(info[0].strip()):
					mergedictdata[info[0].strip()].append(info[4])
				else:
					mergedictdata[info[0].strip()]=[info[4]]
				temphumanunilist=info[-1].split(',')
				hPNlist=[]
				hGNlist=[]
				hdislist=[]
				hunidislist=[]
				hunidisURLlist=[]
				hdisgenlist=[]
				hdisgenURLlist=[]
				hDruglist=[]
				hGoIDList=[]
				hGoNamList=[]
				hGoTermList=[]
				hGoList=[]
				hKeggList=[]
				hKeggdetailsList=[]
				for h in temphumanunilist:
					if h in humanfuncdict:
						hPNlist.append(humanfuncdict[h][0])
						hGNlist.append(humanfuncdict[h][1])
						hdislist.append(humanfuncdict[h][4])
						hunidislist.append(humanfuncdict[h][5])
						hunidisURLlist.append(humanfuncdict[h][6])
						hdisgenlist.append(humanfuncdict[h][7])
						hdisgenURLlist.append(humanfuncdict[h][8])
						hDruglist.append(humanfuncdict[h][9])
						hGoIDList.append(humanfuncdict[h][10])
						hGoNamList.append(humanfuncdict[h][11])
						hGoTermList.append(humanfuncdict[h][12])
						hGoList.append(humanfuncdict[h][-1])
					if h in humanKEGGdict:
						hKeggList.append(humanKEGGdict[h][0])
						hKeggdetailsList.append(humanKEGGdict[h][1])
				hPN='NA'
				hGN='NA'
				hdis='NA'
				hunidis='NA'
				hunidisURL='NA'
				hdisgen='NA'
				hdisgenURL='NA'
				hDrug='NA'
				hGoiddata='NA'
				hGonamedata='NA'
				hGotermdata='NA'
				hGodata='NA'
				hKeggdata='NA'
				hKeggdetails='NA'
				if len(hPNlist)>0:
					hPN='|'.join(list(set([l.strip() for k in hPNlist for l in k.split('|') if len(l.strip()) >0])))
				if len(hGNlist)>0:
					hGN='|'.join(list(set([l.strip() for k in hGNlist for l in k.split('|') if len(l.strip()) >0])))
				if len(hdislist)>0:
					hdis='|'.join(list(set([l.strip() for k in hdislist for l in k.split('|') if len(l.strip()) >0])))
				if len(hunidislist)>0:
					hunidis='|'.join(list(set([l.strip() for k in hunidislist for l in k.split('|') if len(l.strip()) >0])))
				if len(hunidisURLlist)>0:
					hunidisURL='|'.join(list(set([l.strip() for k in hunidisURLlist for l in k.split('|') if len(l.strip()) >0])))
				if len(hdisgenlist)>0:
					hdisgen='|'.join(list(set([l.strip() for k in hdisgenlist for l in k.split('|') if len(l.strip()) >0])))
				if len(hdisgenURLlist)>0:
					hdisgenURL='|'.join(list(set([l.strip() for k in hdisgenURLlist for l in k.split('|') if len(l.strip()) >0])))
				if len(hDruglist)>0:
					hDrug='|'.join(list(set([l.strip() for k in hDruglist for l in k.split('|') if len(l.strip()) >0])))
				if len(hGoIDList)>0:
					hGoiddata='|'.join(list(set([l.strip() for k in hGoIDList for l in k.split('|') if len(l.strip()) >0])))
				if len(hGoNamList)>0:
					hGonamedata='|'.join(list(set([l.strip() for k in hGoNamList for l in k.split('|') if len(l.strip()) >0])))
				if len(hGoTermList)>0:
					hGotermdata='|'.join(list(set([l.strip() for k in hGoTermList for l in k.split('|') if len(l.strip()) >0])))
				if len(hGoList)>0:
					hGodata='|'.join(list(set([l.strip() for k in hGoList for l in k.split('|') if len(l.strip()) >0])))
				if len(hKeggList)>0:
					hKeggdata='|'.join(list(set([str(l).strip() for k in hKeggList for l in k ])))
				if len(hKeggdetailsList)>0:
					hKeggdetails='|'.join(list(set([l.strip() for k in hKeggdetailsList for l in k.split('|') if len(l.strip()) >0])))
				humanmousemergedic[info[0].strip()]=[str(hPN),str(hGN),str(hdis),str(hunidis),str(hunidisURL),\
				str(hdisgen),str(hdisgenURL),str(hDrug),str(info[-1]),str(hGoiddata),str(hGonamedata),str(hGotermdata),\
				str(hGodata),str(hKeggdata),str(hKeggdetails)]
		print (str(fitem),"data dictionay job done",str(datetime.datetime.now()))
	return mergedictdata,humanmousemergedic


def runprog():
	# runcomplete=compileSkylineFile()
	# if runcomplete ==0:
	# 	print("No new data has been added!",str(datetime.datetime.now()))
	runcomplete=1
	return runcomplete
	
if __name__ == '__main__':
	colname=['UniProtKB Accession','Protein','Gene','Organism','Peptide Sequence','Summary Concentration Range Data','All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based','Peptide ID',\
	'Special Residues','Molecular Weight','GRAVY Score','Transitions','Retention Time','Analytical inofrmation',\
	'Gradients','AAA Concentration','CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ','Protocol','Trypsin','QC. Conc. Data','Human UniProtKB Accession']
	print (datetime.datetime.now())
	print ("Update mother file job starts now")
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	runcomplete=runprog()
	if runcomplete==1:
		#get home directory path
		homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
		outfilefilename ='outfilefile.csv'
		filename='ReportBook_mother_file.csv'
		kdicfile='keggdic.obj'
		filepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)
		# #copy mother file from its source to working directory
		if os.path.exists(filepath):
			movefilepath=os.path.join(homedir, 'updatefile', filename)
			if os.path.exists(movefilepath):
				os.remove(movefilepath)
			if not os.path.exists(movefilepath):
				shutil.copy2(filepath, movefilepath)
				#create backup folder before update and then move that folder with old version mother file for backup
				mydate = datetime.datetime.now()
				folder_name="version_"+mydate.strftime("%B_%d_%Y_%H_%M_%S")
				if not os.path.exists('./backup/'+folder_name):
					os.makedirs('./backup/'+folder_name)
				if not os.path.exists('./backup/'+folder_name+'/ReportBook_mother_file.csv'):
					shutil.copy2(movefilepath, './backup/'+folder_name+'/ReportBook_mother_file.csv')
				listOfResourceFile=['mouse_report_peptrack_data.csv']
				humanuniprotdic='humanUniprotfuncinfodic.obj'
				humankdeggic='humankeggdic.obj'
				mergedictdata,humanmousemergedic=makemergedict(listOfResourceFile,colname,humanuniprotdic,humankdeggic)
				if len(mergedictdata)>0:
					print ("Data formatting and checking pep seq present in uniprot specified seq, job starts",str(datetime.datetime.now()))
					uniidlist=[]
					dicmrm={}
					orgidDic={}
					unqisocheckdic={}
					unifuncdic={}
					countProt=0
					countPep=0
					RETRY_TIME = 20.0
					curr_dir = os.getcwd()
					below_curr_dir=os.path.normpath(curr_dir + os.sep + os.pardir)
					totalUniId=list(set(mergedictdata.keys()))

					tempcanonicalUnId=[]
					canonisounidic={}
					for tuid in totalUniId:
						tuempcode=(str(tuid).split('-'))[0]
						if canonisounidic.has_key(tuempcode):
							canonisounidic[tuempcode].append(tuid)
						else:
							canonisounidic[tuempcode]=[tuid]

					canonisounidic={a:list(set(b)) for a, b in canonisounidic.items()}
					unqcanonicalUnId=list(set(canonisounidic.keys()))
					print ("Total Unique protein in this file: ",len(unqcanonicalUnId))
					countProt=0
					print ("Extracting Protein Name, Gene, Organism Name,GO,Sub cellular data, drug bank data ,disease data and checking pep seq present in uniprot specified seq, job starts",str(datetime.datetime.now()))
					tempgotermdic={}
					tempsubcdic={}
					protgnogscgofilename='uniprotfuncdata.csv'
					protgnogscgofile=open(protgnogscgofilename,'w')
					protgnogscgoHeader=['ActualUniID','UpdatedUniID','PepSeq','ProteinName','Gene','Organism',\
					'OrganismID','Subcellular','Mouse GOID','Mouse GOName','Mouse GoTerm','Mouse Go',\
					'Human DrugBank','Human DiseaseData','Human UniProt DiseaseData','Human UniProt DiseaseData URL',\
					'Human DisGen DiseaseData','Human DisGen DiseaseData URL','PresentInSeq','Human UniProtKB Accession',\
					'Human ProteinName','Human Gene','Human Kegg Pathway Name',\
					'Human Kegg Pathway','Human Go ID','Human Go Name','Human Go Term','Human Go']
					protgnogscgofile.write('\t'.join(protgnogscgoHeader)+'\n')
					for subcgcode in unqcanonicalUnId:
						time.sleep(2)
						ScAllLocList=[]
						GoIDList=[]
						GoNamList=[]
						GoTermList=[]
						GOinfo=[]
						PN='NA'
						GN='NA'
						OG='NA'
						OGID='NA'
						try:
							countProt+=1
							if countProt%1000 ==0:
								print (str(countProt), "th protein Protein Name, Gene, Organism Name, GO, sub cellular and checking pep seq present in uniprot specified seq job starts",str(datetime.datetime.now()))

							SGrequestURL="https://www.uniprot.org/uniprot/"+str(subcgcode)+".xml"
							SGunifile=urllib.urlopen(SGrequestURL)
							SGunidata= SGunifile.read()
							SGunifile.close()

							try:
								SGunidata=minidom.parseString(SGunidata)
								try:
									subcelldata=(SGunidata.getElementsByTagName('subcellularLocation'))
									for subcItem in subcelldata:
										try:
											subloc=(subcItem.getElementsByTagName('location')[0]).firstChild.nodeValue
											if len(str(subloc).strip()) >0:
												ScAllLocList.append(str(subloc).strip())
										except:
											pass

								except IndexError:
									pass
								try:
									godata=(SGunidata.getElementsByTagName('dbReference'))
									for gItem in godata:
										if (gItem.attributes['type'].value).upper() == 'GO':
											try:
												gonamedetails=(str(gItem.getElementsByTagName('property')[0].attributes['value'].value).strip()).split(':')[1]
												gotermdetails=(str(gItem.getElementsByTagName('property')[0].attributes['value'].value).strip()).split(':')[0]
												GoNamList.append(gonamedetails)
												goid=str(gItem.attributes['id'].value).strip()
												GoIDList.append(goid)
												tempGoTerm=None
												
												if gotermdetails.lower()=='p':
													tempGoTerm='Biological Process'
												if gotermdetails.lower()=='f':
													tempGoTerm='Molecular Function'
												if gotermdetails.lower()=='c':
													tempGoTerm='Cellular Component'
												GoTermList.append(tempGoTerm)
												tempGOData=gonamedetails+';'+goid+';'+tempGoTerm
												GOinfo.append(tempGOData)
							
											except:
												pass

										if (gItem.attributes['type'].value).strip() == 'NCBI Taxonomy':
											try:
												OGID=str(gItem.attributes['id'].value).strip()
											except:
												pass
								except IndexError:
									pass

								try:
									try:
										PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('recommendedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

									except:
										PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('submittedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

								except IndexError:
									pass

								try:
									try:
										GN=((SGunidata.getElementsByTagName('gene')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
									except:
										GN='NA'
								except IndexError:
									pass

								try:
									try:
										OG=((SGunidata.getElementsByTagName('organism')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
									except:
										OG='NA'
								except IndexError:
									pass

							except ExpatError:
								pass
						except IOError:
							pass
						subcelldata='NA'
						goiddata='NA'
						gonamedata='NA'
						gotermdata='NA'
						goData='NA'
						if len(ScAllLocList)>0:
							subcelldata='|'.join(list(set(ScAllLocList)))
						if len(GoIDList)>0:
							goiddata='|'.join(list(set(GoIDList)))
						if len(GoNamList)>0:
							gonamedata='|'.join(list(set(GoNamList)))
						if len(GoTermList)>0:
							gotermdata='|'.join(list(set(GoTermList)))
						if len(GOinfo)>0:
							goData='|'.join(list(set(GOinfo)))

						if subcgcode in canonisounidic:
							for canisoitem in canonisounidic[subcgcode]:
								time.sleep(1)
								try:
									tempfastaseq=''
									unifastaurl="https://www.uniprot.org/uniprot/"+str(canisoitem)+".fasta"
									fr = requests.get(unifastaurl)
									fAC=(str(fr.url).split('/')[-1].strip()).split('.')[0].strip()
									fastaresponse = urllib.urlopen(unifastaurl)
									for seq in SeqIO.parse(fastaresponse, "fasta"):
										tempfastaseq=(seq.seq).strip()
									if len(tempfastaseq.strip()) >0:
										if canisoitem in mergedictdata:
											for temppgopepseq in mergedictdata[canisoitem]:
												pepinfastapresent='No'
												if temppgopepseq in tempfastaseq:
													pepinfastapresent='Yes'
												protFileDataList=['NA']*28
												if '-' in fAC:
													if canisoitem in humanmousemergedic:
														protFileDataList[0]=str(canisoitem)
														protFileDataList[1]=str(fAC)
														protFileDataList[2]=str(temppgopepseq)
														protFileDataList[3]=str(PN)
														protFileDataList[4]=str(GN)
														protFileDataList[5]=str(OG)
														protFileDataList[6]=str(OGID)
														protFileDataList[12]=str(humanmousemergedic[canisoitem][7])
														protFileDataList[13]=str(humanmousemergedic[canisoitem][2])
														protFileDataList[14]=str(humanmousemergedic[canisoitem][3])
														protFileDataList[15]=str(humanmousemergedic[canisoitem][4])
														protFileDataList[16]=str(humanmousemergedic[canisoitem][5])
														protFileDataList[17]=str(humanmousemergedic[canisoitem][6])
														protFileDataList[18]=str(pepinfastapresent)
														protFileDataList[19]=str(humanmousemergedic[canisoitem][8])
														protFileDataList[20]=str(humanmousemergedic[canisoitem][0])
														protFileDataList[21]=str(humanmousemergedic[canisoitem][1])
														protFileDataList[22]=str(humanmousemergedic[canisoitem][-2])
														protFileDataList[23]=str(humanmousemergedic[canisoitem][-1])
														protFileDataList[24]=str(humanmousemergedic[canisoitem][9])
														protFileDataList[25]=str(humanmousemergedic[canisoitem][10])
														protFileDataList[26]=str(humanmousemergedic[canisoitem][11])
														protFileDataList[27]=str(humanmousemergedic[canisoitem][12])
													else:
														protFileDataList[0]=str(canisoitem)
														protFileDataList[1]=str(fAC)
														protFileDataList[2]=str(temppgopepseq)
														protFileDataList[3]=str(PN)
														protFileDataList[4]=str(GN)
														protFileDataList[5]=str(OG)
														protFileDataList[6]=str(OGID)
														protFileDataList[18]=str(pepinfastapresent)
														
												else:
													if canisoitem in humanmousemergedic:
														protFileDataList[0]=str(canisoitem)
														protFileDataList[1]=str(fAC)
														protFileDataList[2]=str(temppgopepseq)
														protFileDataList[3]=str(PN)
														protFileDataList[4]=str(GN)
														protFileDataList[5]=str(OG)
														protFileDataList[6]=str(OGID)
														protFileDataList[7]=str(subcelldata)
														protFileDataList[8]=str(goiddata)
														protFileDataList[9]=str(gonamedata)
														protFileDataList[10]=str(gotermdata)
														protFileDataList[11]=str(goData)
														protFileDataList[12]=str(humanmousemergedic[canisoitem][7])
														protFileDataList[13]=str(humanmousemergedic[canisoitem][2])
														protFileDataList[14]=str(humanmousemergedic[canisoitem][3])
														protFileDataList[15]=str(humanmousemergedic[canisoitem][4])
														protFileDataList[16]=str(humanmousemergedic[canisoitem][5])
														protFileDataList[17]=str(humanmousemergedic[canisoitem][6])
														protFileDataList[18]=str(pepinfastapresent)
														protFileDataList[19]=str(humanmousemergedic[canisoitem][8])
														protFileDataList[20]=str(humanmousemergedic[canisoitem][0])
														protFileDataList[21]=str(humanmousemergedic[canisoitem][1])
														protFileDataList[22]=str(humanmousemergedic[canisoitem][-2])
														protFileDataList[23]=str(humanmousemergedic[canisoitem][-1])
														protFileDataList[24]=str(humanmousemergedic[canisoitem][9])
														protFileDataList[25]=str(humanmousemergedic[canisoitem][10])
														protFileDataList[26]=str(humanmousemergedic[canisoitem][11])
														protFileDataList[27]=str(humanmousemergedic[canisoitem][12])

													else:
														protFileDataList[0]=str(canisoitem)
														protFileDataList[1]=str(fAC)
														protFileDataList[2]=str(temppgopepseq)
														protFileDataList[3]=str(PN)
														protFileDataList[4]=str(GN)
														protFileDataList[5]=str(OG)
														protFileDataList[6]=str(OGID)
														protFileDataList[7]=str(subcelldata)
														protFileDataList[8]=str(goiddata)
														protFileDataList[9]=str(gonamedata)
														protFileDataList[10]=str(gotermdata)
														protFileDataList[11]=str(goData)
														protFileDataList[18]=str(pepinfastapresent)
												protgnogscgofile.write('\t'.join(protFileDataList)+'\n')
								except IOError:
									pass
					protgnogscgofile.close()
					mergedictdata.clear()
					countProt=0
					print ("Extracting Protein Name, Gene, Organism Name,GO,Sub cellular data, and checking pep seq present in uniprot specified seq, job done",str(datetime.datetime.now()))

					countProt=0
					countPep=0
					tempunifuncdic={}
					with open(protgnogscgofilename) as pgosgfile:
						preader = csv.DictReader(pgosgfile, delimiter='\t')
						for prow in preader:
							tempCol=['ActualUniID','ProteinName','Gene','Organism',\
							'OrganismID','Subcellular','PepSeq','Human DiseaseData',\
							'Human UniProt DiseaseData','Human UniProt DiseaseData URL',\
							'Human DisGen DiseaseData','Human DisGen DiseaseData URL',\
							'Mouse GOID','Mouse GOName','Mouse GoTerm','Mouse Go',\
							'Human DrugBank','Human UniProtKB Accession','Human ProteinName','Human Gene',\
							'Human Kegg Pathway Name','Human Kegg Pathway',\
							'Human Go ID','Human Go Name','Human Go Term','Human Go','PresentInSeq']
							templist=[]
							for tc in tempCol:
								templist.append(str(prow[tc]).strip())
							tempfuncid=str(prow['UpdatedUniID']).strip()+'_'+str(prow['PepSeq']).strip()
							tempunifuncdic[tempfuncid]=templist

							uniidlist.append((((prow['UpdatedUniID']).split('-'))[0]).strip())

							if str(prow['PresentInSeq']).strip() =='Yes':
								tempid=str(prow['UpdatedUniID']).strip()+'_'+str(prow['OrganismID']).strip()
								if unqisocheckdic.has_key(tempid):
									unqisocheckdic[tempid].append(str(prow['PepSeq']).strip())
								else:
									unqisocheckdic[tempid]=[str(prow['PepSeq']).strip()]

					unquniidlist=list(set(uniidlist))
					print ("Extracting KEGG pathway name, job starts",str(datetime.datetime.now()))
					keggdictfile={}
					uniproturl = 'https://www.uniprot.org/uploadlists/'
					k = KEGG()
					for kx in range(0,len(unquniidlist),2000):
						countProt+=kx+2000
						if countProt%2000 ==0:
							print (str(countProt), "th protein kegg job starts",str(datetime.datetime.now()))

						uniprotcodes=' '.join(unquniidlist[kx:kx+2000])
						uniprotparams = {
						'from':'ACC',
						'to':'KEGG_ID',
						'format':'tab',
						'query':uniprotcodes
						}
						
						while True:
							try:
								kuniprotdata = urllib.urlencode(uniprotparams)
								kuniprotrequest = urllib2.Request(uniproturl, kuniprotdata)
								kuniprotresponse = urllib2.urlopen(kuniprotrequest)
								for kuniprotline in kuniprotresponse:
									kudata=kuniprotline.strip()
									if not kudata.startswith("From"):
										kuinfo=kudata.split("\t")
										if len(kuinfo[1].strip()):
											kegg=k.get(kuinfo[1].strip())
											kudict_data = k.parse(kegg)
											try:
												try:
													if len(str(kuinfo[0]).strip()) >5:
														tempkeggData='|'.join('{};{}'.format(key, value) for key, value in kudict_data['PATHWAY'].items())
														keggdictfile[kuinfo[0].strip()]=[kudict_data['PATHWAY'].values(),tempkeggData]
												except TypeError: 
													pass
											except KeyError:
												pass
								break
							except urllib2.HTTPError:
								time.sleep(RETRY_TIME)
								print ('Hey, I am trying again until succeeds to get data from KEGG!',str(datetime.datetime.now()))
								pass
					kdicf = open(kdicfile, 'wb')
					pickle.dump(keggdictfile, kdicf , pickle.HIGHEST_PROTOCOL)
					kdicf.close()

					diseasefilepath = os.path.join(below_curr_dir, 'src/UniDiseaseInfo/' 'humsavar.txt')
					print ("Extracting disease data, job starts",str(datetime.datetime.now()))
					try:
						urllib.urlretrieve('ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/variants/humsavar.txt',diseasefilepath)
						urllib.urlcleanup()
					except:
						print ("Can't able to download humsavar.txt file!!")

					print ("Extracting Human disease data, job done",str(datetime.datetime.now()))

					print ("Checking uniqueness of peptide sequence and presence in isoforms, job starts",str(datetime.datetime.now()))
					countProt=0
					countPep=0
					outfilefileUnqIsoname='UnqIsoresult.csv'
					outfilefileUnqIso = open(outfilefileUnqIsoname,'w')
					outfilefileUnqIso.write('UniProtKB Accession'+'\t'+'Peptide Sequence'+'\t'+'Unique in protein'+'\t'+'Present in isoforms'+'\n')
					for mkey in unqisocheckdic.keys():
						pepunid=mkey.split('_')[0]
						unqtemppepseqList=list(set(unqisocheckdic[mkey]))
						pepUnqDic={}
						pepIsodic={}
						nonprotuniqstatDic={}
						peppresentUniFastaDic={}
						canopepunid=''
						pepunidver=''
						if '-' in pepunid:
							pepunidinfo=pepunid.split('-')
							canopepunid=pepunidinfo[0]
							pepunidver=pepunidinfo[-1]
						else:
							canopepunid=pepunid
						pirUqorgid=mkey.split('_')[1]

						countProt+=1
						if countProt%1000 ==0:
							print (str(countProt), "th protein peptide uniqueness job starts",str(datetime.datetime.now()))
							time.sleep(10)

						for mx in range(0,len(unqtemppepseqList),90):
							countPep+=mx+90
							if countPep%4000 ==0:
								print (str(countPep), "th peptide seq uniqueness check job starts",str(datetime.datetime.now()))

							unqtemppepseq=','.join(unqtemppepseqList[mx:mx+90])

							while True:
								try:
									PIRpepMatrequestURLUnq ="https://research.bioinformatics.udel.edu/peptidematchapi2/match_get?peptides="+str(unqtemppepseq)+"&taxonids="+str(pirUqorgid)+"&swissprot=true&isoform=true&uniref100=false&leqi=false&offset=0&size=-1"
									urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
									PIRPepMatrUnq = requests.get(PIRpepMatrequestURLUnq, headers={ "Accept" : "application/json"},verify=False)

									if not PIRPepMatrUnq.ok:
									  PIRPepMatrUnq.raise_for_status()
									  sys.exit()

									PIRPepMatresponseBodyUnq = PIRPepMatrUnq.json()

									if len(PIRPepMatresponseBodyUnq['results'][0]['proteins'])>0:
										for piritemUnq in PIRPepMatresponseBodyUnq['results'][0]['proteins']:
											uniID=piritemUnq['ac'].strip()
											pirRevStatUnq=piritemUnq['reviewStatus'].strip()

											if pepunid.lower() == (str(uniID).lower()).strip():
												for sxmatchpep in piritemUnq["matchingPeptide"]:
													matchpeptide=sxmatchpep["peptide"]
													if str(matchpeptide).strip() in unqtemppepseqList[mx:mx+90]:
														peppresentUniFastaDic[str(matchpeptide).strip()]=True

											if 'sp' == (str(pirRevStatUnq).lower()).strip():
												canouniID=''
												uniIDver=''
												if '-' in uniID:
													uniIDinfo=uniID.split('-')
													canouniID=uniIDinfo[0]
													uniIDver=uniIDinfo[-1]
												else:
													canouniID=uniID
												for mxmatchpep in piritemUnq["matchingPeptide"]:
													uimatchpeptide=mxmatchpep["peptide"]
													if str(uimatchpeptide).strip() in unqtemppepseqList[mx:mx+90]:
														if (canouniID.strip()).lower() == (canopepunid.strip()).lower():
															if len(uniIDver.strip()) ==0:
																pepUnqDic[str(uimatchpeptide).strip()]=True
															if len(uniIDver.strip()) !=0:
																if pepIsodic.has_key(str(uimatchpeptide).strip()):
																	pepIsodic[str(uimatchpeptide).strip()].append(uniID)
																else:
																	pepIsodic[str(uimatchpeptide).strip()]=[uniID]
														if canouniID.strip() !=canopepunid.strip():
															nonprotuniqstatDic[str(uimatchpeptide).strip()]=True

									break
								except requests.exceptions.ConnectionError:
									time.sleep(RETRY_TIME)
									print ('Hey, I am trying again until succeeds to get data from Peptide Match Server!',str(datetime.datetime.now()))
									pass
								except requests.exceptions.ChunkedEncodingError:
									time.sleep(RETRY_TIME)
									print ('chunked_encoding_error happened',str(datetime.datetime.now()))
									pass
									
						for peptideseq in unqtemppepseqList:
							peptideunique='NA'
							pepisodata='No'
							if peptideseq not in nonprotuniqstatDic:
								if peptideseq in pepUnqDic:
									if pepUnqDic[peptideseq]:
										peptideunique='Yes'
									else:
										peptideunique='Not unique'
							else:
								peptideunique='NA'
							if peptideseq in pepIsodic:
								pepisodata=','.join(list(set(pepIsodic[peptideseq])))
							outfilefileUnqIso.write(str(pepunid)+'\t'+str(peptideseq)+'\t'+str(peptideunique)+'\t'+str(pepisodata)+'\n')

					outfilefileUnqIso.close()
					print ("Checking uniqueness of peptide sequence and presence in isoforms, job done",str(datetime.datetime.now()))

					tempunqisodic={}
					with open(outfilefileUnqIsoname) as unqisofile:
						uireader = csv.DictReader(unqisofile, delimiter='\t')
						for uirow in uireader:
							tempunqisodic[str(uirow['UniProtKB Accession']).strip()+'_'+str(uirow['Peptide Sequence']).strip()]=[str(uirow['Unique in protein']).strip(),str(uirow['Present in isoforms']).strip()]
					
					keggdict = cPickle.load(open(kdicfile, 'rb'))

					tempunikeggunqisofuncdic={}
					for tukey in tempunifuncdic:
						tempkeggdata='NA'
						tempkeggdetails='NA'
						tempunqdata='NA'
						tempisodata='NA'
						tuniID=tukey.split('_')[0]
						if tuniID in keggdict:
							tempkeggdata='|'.join(list(set(keggdict[tuniID][0])))
							tempkeggdetails=keggdict[tuniID][1]
						if tukey in tempunqisodic:
							tempunqdata=tempunqisodic[tukey][0]
							tempisodata=tempunqisodic[tukey][1]

						tuitem=tempunifuncdic[tukey]
						tuitem.insert(7,tempunqdata)
						tuitem.insert(8,tempisodata)
						tuitem.insert(9,tempkeggdata)
						tuitem.insert(10,tempkeggdetails)
						tempolduniid=tuitem[0]
						tuitem[0]=tuniID
						modtukey=tempolduniid+'_'+tukey.split('_')[1]
						tempunikeggunqisofuncdic[modtukey]=tuitem
					print ("Functional data dictionay job done",str(datetime.datetime.now()))

					keggdict.clear()
					tempunifuncdic.clear()
					tempunqisodic.clear()
					temptransdic={}

					for fitem in listOfResourceFile:
						with open(fitem,'r') as pepfile:
							reader = csv.DictReader(pepfile, delimiter='\t')
							for row in reader:
								resinfo=[]
								for i in colname:
									resinfo.append(str(row[i]).strip())
								restempid=resinfo[0].strip()+'_'+resinfo[4].strip()
								if temptransdic.has_key(restempid):
									temptransdic[restempid].append(resinfo[5:])
								else:
									temptransdic[restempid]=[resinfo[5:]]
						print (str(fitem),"transition data dictionay job done",str(datetime.datetime.now()))
					outFileColName=['UniProtKB Accession','Protein','Gene','Organism','Organism ID','SubCellular',\
					'Peptide Sequence','Summary Concentration Range Data','All Concentration Range Data',\
					'All Concentration Range Data-Sample LLOQ Based','Peptide ID','Special Residues','Molecular Weight',\
					'GRAVY Score','Transitions','Retention Time','Analytical inofrmation','Gradients','AAA Concentration',\
					'CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ','Protocol','Trypsin','QC. Conc. Data',\
					'Unique in protein','Present in isoforms','Mouse Kegg Pathway Name','Mouse Kegg Pathway',\
					'Human Disease Name','Human UniProt DiseaseData','Human UniProt DiseaseData URL',\
					'Human DisGen DiseaseData','Human DisGen DiseaseData URL','Mouse Go ID',\
					'Mouse Go Name','Mouse Go Term','Mouse Go','Human Drug Bank',\
					'Human UniProtKB Accession','Human ProteinName','Human Gene',\
					'Human Kegg Pathway Name','Human Kegg Pathway','Human Go ID',\
					'Human Go Name','Human Go Term','Human Go','UniprotKb entry status']

					outFileColNameData='\t'.join(outFileColName)
					outfilefile = open(outfilefilename,'w')
					outfilefile.write(outFileColNameData+'\n')
					for key in temptransdic:

						for subtempitem in temptransdic[key]:
							temprow=['NA']*52
							peptracktemprowpos=[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
							for i,j in zip(subtempitem,peptracktemprowpos):
								temprow[j]=str(i)
							functemprowpos=[0,1,2,3,4,5,6,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51]
							if key in tempunikeggunqisofuncdic:
								for x,y in zip(tempunikeggunqisofuncdic[key],functemprowpos):
									temprow[y]=str(x)
							if (temprow[0].strip()).upper() != 'NA' and (temprow[6].strip()).upper() != 'NA':
								finalreportdata='\t'.join(temprow)
								outfilefile.write(finalreportdata+'\n')
							temprow=[]

					outfilefile.close()
					print ("Initial report file creation, job done",str(datetime.datetime.now()))
					temptransdic.clear()
					tempunikeggunqisofuncdic.clear()
					os.rename(outfilefilename,filename)
					shutil.move(movefilepath,filepath)
					print ("Initial report file transfer, job done",str(datetime.datetime.now()))

		addModCol()

		keggcmd='python statKEGGcoverage.py'
		subprocess.Popen(keggcmd, shell=True).wait()
		
		statjobcmd='python generateSummaryReport.py'
		subprocess.Popen(statjobcmd, shell=True).wait()

		totalAssayPep()
		addSelCol()
		presencePepSeqHuman()
		ncbiGeneExp()
		preLoadJsonData(homedir,filepath)
		uploadData()
		print ("Extracting Prepare download, job starts",str(datetime.datetime.now()))
		preDownloadFile()
		print ("Extracting Prepare download, job starts",str(datetime.datetime.now()))
<file_sep>/backend/updatefile/generateSummaryReport.py
import urllib,urllib2
from bioservices.kegg import KEGG
import os,subprocess,psutil,re,shutil,datetime,sys,glob
from operator import itemgetter
import numpy as np
import random, time
from itertools import count, groupby
import pandas as pd
import csv
import itertools
import json
import ctypes

#increase the field size of CSV
csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
filename='ReportBook_mother_file.csv'
filepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)

statfilename='overallstat.py'
statmovefilepath=os.path.join(homedir, 'updatefile', statfilename)
statfilepath = os.path.join(homedir, 'src/qmpkbapp', statfilename)

orglist=[]
orglistID=[]
statKeggDic={}
with open(filepath) as pepcsvfile:
	pepreader=csv.DictReader(pepcsvfile, delimiter='\t')
	for peprow in pepreader:
		if  str(peprow['UniprotKb entry status']).strip().upper()=='YES':
			orglist.append(' '.join(str(peprow['Organism']).strip().split(' ')[:2]))
			orglistID.append(str(peprow['Organism ID']).strip())
			statuniID=str(peprow['UniProtKB Accession']).strip().split('-')[0]
			statPathway=str(peprow['Mouse Kegg Pathway Name']).strip()
			statSpeciesID=str(peprow['Organism ID']).strip()
			if len(statPathway)>0:
				statPathwayList=statPathway.split('|')
				for stpItem in statPathwayList:
					if stpItem.lower() !='na':
						keggid=stpItem.strip()
						if statKeggDic.has_key(keggid):
							statKeggDic[keggid].append(statuniID.strip())
						else:
							statKeggDic[keggid] =[statuniID.strip()]

unqorglist=list(set(orglist))
unqorglist.sort(key=str.lower)
speciesList=unqorglist
speciesProt={}
speciesPep={}
godic={}
speciesdic={}
keggpathwaycoverage=[]
#print speciesList
with open(filepath) as pepcsvfile:
	pepreader=csv.DictReader(pepcsvfile, delimiter='\t')
	for frow in pepreader:
		if str(frow['UniprotKb entry status']).strip().upper()=='YES':
			pepseq=frow['Peptide Sequence'].strip()
			Calorg=str(frow['Organism']).strip()
			CalorgID=str(frow['Organism ID']).strip()
			speciesdic[CalorgID]=Calorg
			acccode=None
			acccode=str(frow['UniProtKB Accession']).split('-')[0]
			if acccode != None:
				for spitem in speciesList:
					if spitem in Calorg:
						if speciesProt.has_key(spitem):
							speciesProt[spitem].append(acccode)
						else:
							speciesProt[spitem]=[acccode]

						if speciesPep.has_key(spitem):
							speciesPep[spitem].append(pepseq)
						else:
							speciesPep[spitem]=[pepseq]
				if frow["Mouse Go Name"].upper() !='NA' and len(str(frow["Mouse Go Name"]).strip())>0:
					goname=(str(frow["Mouse Go Name"]).strip()).split('|')
					for gitem in goname:
						if godic.has_key(str(gitem).strip()):
							godic[str(gitem).strip()].append(acccode)
						else:
							godic[str(gitem).strip()]=[acccode]


sys.path.append(os.path.join(homedir, 'src/qmpkbapp'))
from calculationprog import *
pepfinalresult=finalresult['prodataseries']

keggpathwaycoverage=[]
for kskey in statKeggDic:
	keggpathwayname=(kskey.strip()).split('|')[0]
	tempUniqKeggUniIDList=list(set(statKeggDic[kskey]))
	peptrack=[]
	for ckey in pepfinalresult:
		if ckey == "PeptideTracker":
			peptrack=list(set(pepfinalresult[ckey]).intersection(tempUniqKeggUniIDList))

	temppeptrack=len(list(set(peptrack)))
	tempTotal=len(list(set(tempUniqKeggUniIDList)))
	templist=[keggpathwayname,tempTotal,temppeptrack]
	keggpathwaycoverage.append(templist)

statsepcies=[]
speciesProt={k:len(list(set(j))) for k,j in speciesProt.items()}
speciesPep={k:len(list(set(j))) for k,j in speciesPep.items()}

godic={k:len(set(v)) for k, v in godic.items()}
 
for skey in speciesProt:
	if skey in speciesPep:
		statsepcies.append([skey,speciesProt[skey],speciesPep[skey]])

sortedstatsepcies=sorted(statsepcies, key= itemgetter(1), reverse=True)

golist=[]
for gkey in godic:
	golist.append([gkey,godic[gkey]])

sortedgolist=sorted(golist, key= itemgetter(1), reverse=True)

keggpathwaycoverage.sort()
unqkeggpathwaycoverage=list(keggpathwaycoverage for keggpathwaycoverage,_ in itertools.groupby(keggpathwaycoverage))
sortedkeggpathwaycoverage=sorted(unqkeggpathwaycoverage, key= itemgetter(1), reverse=True)

overallSumresult={}
overallSumresult['organism']=unqorglist
unqorglist.insert(0,"")
overallSumresult['species']=unqorglist
overallSumresult['speciesstat']=sortedstatsepcies
overallSumresult['mousegostat']=sortedgolist
overallSumresult['mousekeggstat']=sortedkeggpathwaycoverage

statfileoutput=open(statfilename,'w')
statfileoutput.write("overallSumresult=")
statfileoutput.write(json.dumps(overallSumresult))
statfileoutput.close()
shutil.move(statmovefilepath,statfilepath)<file_sep>/client/qmpkb-app/src/app/detail-concentration/detail-concentration.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DetailConcentrationComponent } from './detail-concentration.component';

describe('DetailConcentrationComponent', () => {
  let component: DetailConcentrationComponent;
  let fixture: ComponentFixture<DetailConcentrationComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DetailConcentrationComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DetailConcentrationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
<file_sep>/client/qmpkb-app/src/app/detail-concentration/detail-concentration.component.ts

import { Component, OnInit, OnDestroy, ViewChild, Renderer, HostListener,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as Plotly from 'plotly.js';
import * as $ from "jquery";
declare var jquery: any;

@Component({
  selector: 'app-detail-concentration',
  templateUrl: './detail-concentration.component.html',
  styleUrls: ['./detail-concentration.component.css']
})
export class DetailConcentrationComponent implements OnInit {

  dtOptions: any = {};
  dtOptionsOther: any = {};
  errorStr:Boolean;
  conclist:any;
  conclistlen:number;
  foundHits:number;
  sampleConcUnit:string;
  protList:any
  queryData:any;
  plotlyData:any=[];
  lenOfConcData:any;
  screenWidth:any;
  finalPlotData:any={};
  queryConcen:any;
  strainData:any;
  knockoutData:any;
  bioMatData:any;
  sexData:any;
  allConcSamLLOQ:any;
  allConc:any;
  concenPlotlyData:any=[];
  concenPlotDataUnit: string;
  bioMatDataTableData:any=[];
  bioMatDataLen=0;
  strainDataTableData:any=[];
  strainDataLen=0;
  sexDataTableData:any=[];
  sexDataLen=0;
  knockoutDataTableData:any=[];
  knockoutDataLen=0;
  concenDataStatus=false;
/*  cocenDataTypeObj={
    'biomat':[this.bioMatData,0],
    'str':['strainData',1],
    'knock':['knockoutData',1],
    'sex':['sexData',1]

  }*/
  wildObj={
    'Wild type':'WT'
  };
  sexObj={
    'Male':'M',
    'Female':'F'
  };
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;

  plotDataOptions=[
       {num:0, name:'Concentration Data'},
       {num:1, name:'Log2(Concentration Data)'},
       {num:2, name:'Log10(Concentration Data)'},
  ];
/*  this.selectedLevel=this.plotDataOptions[0];*/
   selected=this.plotDataOptions[2];

  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=(window.innerWidth-50)+"px";
  }


  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService,
    private renderer: Renderer,
    ) { 
      this.getScreenSize();
  }

  @Input()
  set concentermQuery(concenQuery:any){
      this.queryConcen=concenQuery;

  }
  async getConcenData(){
  	let queryConcenArray=this.queryConcen.split('|');
    await this._qmpkb.receiveDataFromBackendSearch('/detailConcentrationapi/?uniProtKb=' + queryConcenArray[0]+ '&resultFilePath=' + queryConcenArray[1]).subscribe((response: any)=>{
      
      this.queryData=response;
      this.conclist=this.queryData.conclist;
      this.strainData=this.queryData.strainData;
      this.knockoutData=this.queryData.knockoutData;
      this.bioMatData=this.queryData.bioMatData;
      this.sexData=this.queryData.sexData;
      this.allConcSamLLOQ=this.queryData.allConcSamLLOQ;
      this.allConc=this.queryData.allConc;
      this.conclistlen=Object.keys(this.conclist).length
      this.foundHits=this.queryData.foundHits;
      this.sampleConcUnit=this.queryData.concUnit;
      this.lenOfConcData= this.queryData.lenOfConcData;

      jQuery.extend( jQuery.fn.dataTable.ext.oSort, {
          "na-asc": function (str1, str2) {
              if(str1 == "NA" || str1.includes('Sample'))
                  return 1;
              else if(str2 == "NA" || str2.includes('Sample') )
                  return -1;
              else{
                 var fstr1 = parseFloat(str1);
                 var fstr2 = parseFloat(str2);
                 return ((fstr1 < str2) ? -1 : ((fstr1 > fstr2) ? 1 : 0));
              }
             
          },
       
          "na-desc": function (str1, str2) {
              if(str1 == "NA" || str1.includes('Sample'))
                  return 1;
              else if(str2 == "NA" || str2.includes('Sample'))
                  return -1;
              else {
                var fstr1 = parseFloat(str1);
                var fstr2 = parseFloat(str2);
                return ((fstr1 < fstr2) ? 1 : ((fstr1 > fstr2) ? -1 : 0));
              }
              
          }
      } );

      this.dtOptions = {
        processing: true,
        serverSide: false,
        orderCellsTop: true,
        fixedHeader: true,
        pageLength: 10,
        pagingType: 'full_numbers',
        scrollX:true,
        scrollY:'650px',
        scrollCollapse:true,
        columnDefs:[
          {
            targets: 0,
            data: null,
            defaultContent: '',
            orderable: false,
            className: 'select-checkbox',
            searchable:false
          },
          {
            targets: 1,
            searchable:false,
            visible:false
          },
          {
            targets: 2,
            searchable:false,
            visible:false
          },
/*          {
            targets: 3,
            searchable:false,
            visible:false
          },*/
          {
            targets: 13,
            searchable:false,
            visible:false
          },
          {
            targets: 14,
            searchable:false,
            visible:false
          },
          {
            targets: 15,
            searchable:false,
            visible:false
          },        
          {
            targets: 16,
            searchable:false,
            visible:false
          },
          {
            targets: 17,
            searchable:false,
            visible:false
          },
          {type: 'na', targets: [8,9,10,11]} // define 'name' column as na type
        ],
        select:{
          style:'multi'
        },
        // Declare the use of the extension in the dom parameter
        dom: 'lBfrtip',
        buttons: [
            {
              extend:'csv',
              filename: 'ConcentrationMouseQuaPro',
              text:'Download all(CSV)',
              exportOptions:{
                columns:[1,2,3,4,5,6,7,8,9,10,11,12,15,16,17]
              }
            },
            {
              extend:'excel',
              filename: 'ConcentrationMouseQuaPro',
              text:'Download all(Excel)',
              exportOptions:{
                columns:[1,2,3,4,5,6,7,8,9,10,11,12,15,16,17]
              }
            },
            'selectAll',
            'selectNone'
        ],
        order: [],
        autoWidth:true

      };
      this.dtOptionsOther = {
        orderCellsTop: true,
        fixedHeader: true,
        pageLength: 10,
        pagingType: 'full_numbers',
        scrollX:true,
        scrollY:'650px',
        scrollCollapse:true,
        autoWidth:true,
        columnDefs:[{
          type: 'na', 
          targets: 4
        }]
      };
      if (this.lenOfConcData > 0){
           setTimeout(() => {this.dataTableGenerated()}, 100);
       }
       this.concenDataStatus=true;
    }, error=>{
      this.errorStr = error;
    })

  }

  ngOnInit() {
  	this.getConcenData()
  }

  dataTableGenerated(): void {      
    const self = this;
    
    self.datatableElement.dtInstance.then((dtInstance:any) => {
      dtInstance.rows(function(idx,data){
        const plotName=data[13].split('|');
        //plotName[0]=self.wildObj[plotName[0]];
        plotName[2]=self.sexObj[plotName[2]];
        const plotData=data[14];
        const plotDataSampleLLOQ=data[15];
        const sampleLLOQ=data[16];
        const ULOQ=data[17];
        const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
        self.plotlyData.push(tempPlotArray.join(';'));

        return idx >=0;
      }).select();
      self.prepareDatatoPlot(self.plotlyData);
    });

     self.datatableElement.dtInstance.then(table => {
      $('#dataTables-wrkld-concentration').on('select.dt', function (e,dt,type,indexes) {
        if (self.lenOfConcData == indexes.length){
           self.plotlyData=[];
           for(let j=0; j< indexes.length;j++){
              const plotName=dt.row(indexes[j]).data()[13].split('|');
              //plotName[0]=self.wildObj[plotName[0]];
              plotName[2]=self.sexObj[plotName[2]];
              const plotData=dt.row(indexes[j]).data()[14];
              const plotDataSampleLLOQ=dt.row(indexes[j]).data()[15];
              const sampleLLOQ=dt.row(indexes[j]).data()[16];
              const ULOQ=dt.row(indexes[j]).data()[17];
              const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
              self.plotlyData.push(tempPlotArray.join(';'));
              self.selected=self.plotDataOptions[0];
           }
           self.prepareDatatoPlot(self.plotlyData);

        } else {
          const plotName=dt.row(indexes[0]).data()[13].split('|');
          //plotName[0]=self.wildObj[plotName[0]];
          plotName[2]=self.sexObj[plotName[2]];
          const plotData=dt.row(indexes[0]).data()[14];
          const plotDataSampleLLOQ=dt.row(indexes[0]).data()[15];
          const sampleLLOQ=dt.row(indexes[0]).data()[16];
          const ULOQ=dt.row(indexes[0]).data()[17];
          const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
          self.plotlyData.push(tempPlotArray.join(';'));
          self.prepareDatatoPlot(self.plotlyData); 
          self.selected=self.plotDataOptions[0];       
        }

        
      });
      $('#dataTables-wrkld-concentration').on('deselect.dt', function (e,dt,type,indexes) {
        if (self.lenOfConcData == indexes.length || indexes.length>1 || self.plotlyData == indexes.length){
            self.plotlyData=[];
            self.prepareDatatoPlot(self.plotlyData);
        } else {
          const plotName=dt.row(indexes[0]).data()[13].split('|');
          //plotName[0]=self.wildObj[plotName[0]];
          plotName[2]=self.sexObj[plotName[2]];
          const plotData=dt.row(indexes[0]).data()[14];
          const plotDataSampleLLOQ=dt.row(indexes[0]).data()[15];
          const sampleLLOQ=dt.row(indexes[0]).data()[16];
          const ULOQ=dt.row(indexes[0]).data()[17];
          const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
          const indexOfplotlyData=self.plotlyData.indexOf(tempPlotArray.join(';'));
          self.plotlyData.splice(indexOfplotlyData,1);
          self.prepareDatatoPlot(self.plotlyData);
          self.selected=self.plotDataOptions[0];        
        }

      });
    });

  }

  prepareDatatoPlot(rawData:any) {
      const tissueColor= {
        "Brain":"cyan",
        "Brown Adipose":"olive",
        "Epididymis":"slategray",
        "Eye":"rosybrown", 
        "Heart":"darksalmon",
        "Kidney":"lightcoral",
        "Liver Caudate and Right Lobe":"sandybrown",
        "Liver Left Lobe":"deepskyblue",
        "Lung":"tan",
        "Pancreas":"cadetblue",
        "Plasma":"greenyellow",
        "Ovary":"goldenrod",
        "RBCs":"seagreen",
        "Salivary Gland":"chocolate",
        "Seminal Vesicles":"khaki",
        "Skeletal Muscle":"indigo",
        "Skin":"thistle",
        "Spleen":"violet",
        "Testes":"lightpink",
        "White Adipose":"plum"
      };

      let prepareDatatoPlotDataArray=[];
      let prepareDatatoPlotDataArrayLog2=[];
      let prepareDatatoPlotDataArrayLog10=[];
      const yAxisTile='Concentration<br>(fmol target protein/µg extracted protein)';
      let layout={
        yaxis:{
        title:yAxisTile,
        zeroline:false,
        showlegend: true,
        legend :{
          x:rawData.length+1
        }
       },
       xaxis:{
         automargin: true
       }
      };

      let layout2={
        yaxis:{
        title:'Concentration<br>in Log2 Scale',
        zeroline:false,
        showlegend: true,
        legend :{
          x:rawData.length+1
        }
       },
       xaxis:{
         automargin: true
       }
      };

      let layout10={
        yaxis:{
        title:'Concentration<br>in Log10 Scale',
        zeroline:false,
        showlegend: true,
        legend :{
          x:rawData.length+1
        }
       },
       xaxis:{
         automargin: true
       }
      };
      const d3colors = Plotly.d3.scale.category10();


      for(let i=0; i< rawData.length;i++){
        const tempPlotDataArray=rawData[i].split(';');
        const plotDataArray=[];
        const plotDataArrayLog2=[];
        const plotDataArrayLog10=[];
        let tempArray=tempPlotDataArray[2].split('|');
        if (tempPlotDataArray[2] === 'NA' || tempPlotDataArray[2].trim().length == 0){
          tempArray=tempPlotDataArray[1].split('|');
        }
        for(let j=0; j< tempArray.length;j++){
           plotDataArray.push(parseFloat(tempArray[j]));
           plotDataArrayLog2.push(Math.log2(parseFloat(tempArray[j])));
           plotDataArrayLog10.push(Math.log10(parseFloat(tempArray[j])));
        }
        let prepareDatatoPlotData={};
        let prepareDatatoPlotDataLog2={};
        let prepareDatatoPlotDataLog10={};

        let boxSamLLOQData={};
        let boxSamLLOQDataLog2={};
        let boxSamLLOQDataLog10={};

        let boxULOQData={};
        let boxULOQDataLog2={};
        let boxULOQDataLog10={};

        let tempplotDataArray=plotDataArray.filter(value=> !Number.isNaN(value));
        if (tempPlotDataArray[2] === 'NA' || tempPlotDataArray[2].trim().length == 0){
          if (tempplotDataArray.length > 0){
            prepareDatatoPlotData={
              y:plotDataArray,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
            prepareDatatoPlotDataLog2={
              y:plotDataArrayLog2,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
            prepareDatatoPlotDataLog10={
              y:plotDataArrayLog10,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
          }

        } else {
          if (tempplotDataArray.length > 0){
            const tempColor=tissueColor[tempPlotDataArray[0].split('|')[0]];
            prepareDatatoPlotData={
              y:plotDataArray,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              boxmean:true,
              marker:{
                color:tempColor
              },
              type:'box'
            };
            prepareDatatoPlotDataLog2={
              y:plotDataArrayLog2,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              boxmean:true,
              marker:{
                color:tempColor
              },
              type:'box'
            };
            prepareDatatoPlotDataLog10={
              y:plotDataArrayLog10,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              boxmean:true,
              marker:{
                color:tempColor
              },
              type:'box'
            };
          }
        }

        if (tempplotDataArray.length > 0){
            boxSamLLOQData={
              x:[tempPlotDataArray[0]],
              y:[parseFloat(tempPlotDataArray[3])],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };


            boxSamLLOQDataLog2={
              x:[tempPlotDataArray[0]],
              y:[Math.log2(parseFloat(tempPlotDataArray[3]))],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };

            boxSamLLOQDataLog10={
              x:[tempPlotDataArray[0]],
              y:[Math.log10(parseFloat(tempPlotDataArray[3]))],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };

            boxULOQData={
              x:[tempPlotDataArray[0]],
              y:[parseFloat(tempPlotDataArray[4])],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };


            boxULOQDataLog2={
              x:[tempPlotDataArray[0]],
              y:[Math.log2(parseFloat(tempPlotDataArray[4]))],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };

            boxULOQDataLog10={
              x:[tempPlotDataArray[0]],
              y:[Math.log10(parseFloat(tempPlotDataArray[4]))],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };

          prepareDatatoPlotDataArray.push(prepareDatatoPlotData);
          prepareDatatoPlotDataArray.push(boxSamLLOQData);
          prepareDatatoPlotDataArray.push(boxULOQData);
          prepareDatatoPlotDataArrayLog2.push(prepareDatatoPlotDataLog2);
          prepareDatatoPlotDataArrayLog2.push(boxSamLLOQDataLog2);
          prepareDatatoPlotDataArrayLog2.push(boxULOQDataLog2);
          prepareDatatoPlotDataArrayLog10.push(prepareDatatoPlotDataLog10);
          prepareDatatoPlotDataArrayLog10.push(boxSamLLOQDataLog10);
          prepareDatatoPlotDataArrayLog10.push(boxULOQDataLog10);
        }
      }

     let finalprepareDatatoPlotDataArray={
       0:prepareDatatoPlotDataArray,
       1:prepareDatatoPlotDataArrayLog2,
       2:prepareDatatoPlotDataArrayLog10
     }

      let defaultPlotlyConfiguration={};
      defaultPlotlyConfiguration ={
        responsive: true,
        scrollZoom: true,
        showTips:true,
        modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
        displayLogo: false
      };

      this.finalPlotData={
        'plotData':finalprepareDatatoPlotDataArray,
        'plotLayout':[layout,layout2,layout10],
        'config':defaultPlotlyConfiguration
      };
      Plotly.newPlot('myDivConcAll',finalprepareDatatoPlotDataArray[2],layout10,defaultPlotlyConfiguration);

      if (rawData.length==0){
        Plotly.purge('myDivConcAll')
      }
  }

  prepareDataToCocenComb(concenTabName:any){
    let concQuery=[];
     if (concenTabName == "biomat") {
        let tempUnit=[];
        if (this.bioMatData.length >0 ){
          this.bioMatDataLen=1;
          for(let y = 0; y <this.bioMatData.length; y++){
            let biomatrixifo = this.bioMatData[y];
            let tempconcQuery=[];
            let tempSampLLOQ=biomatrixifo[8];
            let tempULOQ=biomatrixifo[9];
            tempconcQuery.push(biomatrixifo[4].trim());
            tempconcQuery.push(biomatrixifo[2].trim());
            concQuery.push([tempconcQuery.join('|'),tempSampLLOQ,tempULOQ]);
            let tempView='<a target="_blank"  routerLinkActive="active" href="/dataload/concentration_'+biomatrixifo[7].trim()+'" >' + 'View' + '</a>';
            let tempBiomatTableData=[biomatrixifo[4].trim(), biomatrixifo[1].trim(), biomatrixifo[5].trim(), biomatrixifo[6].trim(), biomatrixifo[0].trim(), tempView,biomatrixifo[2].trim()];
            this.bioMatDataTableData.push(tempBiomatTableData);
          }
          for (let m = 0; m <concQuery.length; m++){
            const tconcQuery = concQuery[m][0].trim().split('|');
                  const plotName=concQuery[m][0].trim();
                  const sampleLLOQ=concQuery[m][1].trim();
                  const ULOQ=concQuery[m][2].trim();
                  const plotData=[];
                  const plotDataSampleLLOQ=[];
                  
            for(let x = 0; x <this.allConcSamLLOQ.length; x++){
              const tempConcAllSamLLOQ=this.allConcSamLLOQ[x][1].trim().split(';');
              if ('NA' != Array.from(new Set(tempConcAllSamLLOQ)).join('')){
                for(let i = 0; i <tempConcAllSamLLOQ.length; i++){
                  const subConcAllSamLLOQ=tempConcAllSamLLOQ[i].trim().split('|');
                  if(subConcAllSamLLOQ[2] == tconcQuery[0] && this.allConcSamLLOQ[x][0] == tconcQuery[1]){
                    plotDataSampleLLOQ.push(subConcAllSamLLOQ.slice(-3)[0].split('(')[0].trim())
                      
                  }
                }

              }
            }
            //Group-1|Wild type|Plasma|1|C57BL6NCrl_Perfused|Female
            for(let z = 0; z <this.allConc.length; z++){
              const tempConcAll=this.allConc[z][1].trim().split(';')
              for(let j = 0; j <tempConcAll.length; j++){
                const subConcAll=tempConcAll[j].trim().split('|');
                if(subConcAll[2] == tconcQuery[0] && this.allConc[z][0] == tconcQuery[1]){
                  plotData.push(subConcAll.slice(-3)[0].split('(')[0].trim())
                  tempUnit.push('('+subConcAll.slice(-3)[0].split('(')[1].trim());
                    
                }
              }
            }
            const tempPlotArray=[plotName,plotData.join('|'),plotDataSampleLLOQ.join('|'),sampleLLOQ,ULOQ];
            this.concenPlotlyData.push(tempPlotArray.join(';'));
                  
          }
          this.concenPlotDataUnit ='Concentration '+Array.from(new Set(tempUnit)).join('&');
          //var plotLyHTML='<div id="myDivConc"></div>';
                  
          this.boxplot(this.concenPlotlyData,this.concenPlotDataUnit,0,concenTabName);

        }
      } else if (concenTabName == "str") {
        let tempUnit=[];
        if (this.strainData.length >0 ){
          this.strainDataLen=1;
          for(let y = 0; y <this.strainData.length; y++){
            let strainifo = this.strainData[y];
            let tempconcQuery=[];
            let tempSampLLOQ=strainifo[8];
            let tempULOQ=strainifo[9];
            tempconcQuery.push(strainifo[5].trim());
            tempconcQuery.push(strainifo[4].trim());
            tempconcQuery.push(strainifo[2].trim());
            concQuery.push([tempconcQuery.join('|'),tempSampLLOQ,tempULOQ]);
            let tempView='<a target="_blank"  routerLinkActive="active" href="/dataload/concentration_'+strainifo[7].trim()+'" >' + 'View' + '</a>';
            let tempStrainTableData=[ strainifo[5].trim(),strainifo[4].trim(), strainifo[1].trim(), strainifo[6].trim(), strainifo[0].trim(), tempView,strainifo[2].trim()];
            this.strainDataTableData.push(tempStrainTableData);
          }
          for (let m = 0; m <concQuery.length; m++){
            const tconcQuery = concQuery[m][0].trim().split('|');
                  const plotName=concQuery[m][0].trim();
                  const sampleLLOQ=concQuery[m][1].trim();
                  const ULOQ=concQuery[m][2].trim();
                  const plotData=[];
                  const plotDataSampleLLOQ=[];
                  
            for(let x = 0; x <this.allConcSamLLOQ.length; x++){
              const tempConcAllSamLLOQ=this.allConcSamLLOQ[x][1].trim().split(';');
              if ('NA' != Array.from(new Set(tempConcAllSamLLOQ)).join('')){
                for(let i = 0; i <tempConcAllSamLLOQ.length; i++){
                  const subConcAllSamLLOQ=tempConcAllSamLLOQ[i].trim().split('|');
                  if(subConcAllSamLLOQ[4] == tconcQuery[0] && subConcAllSamLLOQ[2] == tconcQuery[1] && this.allConcSamLLOQ[x][0] == tconcQuery[2]){
                    plotDataSampleLLOQ.push(subConcAllSamLLOQ.slice(-3)[0].split('(')[0].trim())
                      
                  }
                }

              }
            }
            //Group-1|Wild type|Plasma|1|C57BL6NCrl_Perfused|Female
            for(let z = 0; z <this.allConc.length; z++){
              const tempConcAll=this.allConc[z][1].trim().split(';')
              for(let j = 0; j <tempConcAll.length; j++){
                const subConcAll=tempConcAll[j].trim().split('|');
                if(subConcAll[4] == tconcQuery[0] && subConcAll[2] == tconcQuery[1] && this.allConc[z][0] == tconcQuery[2]){
                  plotData.push(subConcAll.slice(-3)[0].split('(')[0].trim())
                  tempUnit.push('('+subConcAll.slice(-3)[0].split('(')[1].trim());
                    
                }
              }
            }
            const tempPlotArray=[plotName,plotData.join('|'),plotDataSampleLLOQ.join('|'),sampleLLOQ,ULOQ];
            this.concenPlotlyData.push(tempPlotArray.join(';'));
                  
          }

          this.concenPlotDataUnit ='Concentration '+Array.from(new Set(tempUnit)).join('&');
          //var plotLyHTML='<div id="myDivConc"></div>';
                  
          this.boxplot(this.concenPlotlyData,this.concenPlotDataUnit,1,concenTabName);

        }
      } else if (concenTabName == "knock") {
        let tempUnit=[];
        if (this.knockoutData.length >0 ){
          this.knockoutDataLen=1;
          for(let y = 0; y <this.knockoutData.length; y++){
            let knockoutifo = this.knockoutData[y];
            let tempSampLLOQ=knockoutifo[8];
            let tempULOQ=knockoutifo[9];
            let tempconcQuery=[];
            tempconcQuery.push(knockoutifo[6].trim());
            tempconcQuery.push(knockoutifo[4].trim());
            tempconcQuery.push(knockoutifo[2].trim());
            concQuery.push([tempconcQuery.join('|'),tempSampLLOQ,tempULOQ]);
            let tempView='<a target="_blank"  routerLinkActive="active" href="/dataload/concentration_'+knockoutifo[7].trim()+'" >' + 'View' + '</a>';
            let tempKnockoutTableData=[knockoutifo[6].trim(),knockoutifo[4].trim(), knockoutifo[1].trim(), knockoutifo[5].trim(), knockoutifo[0].trim(), tempView,knockoutifo[2].trim()];
            this.knockoutDataTableData.push(tempKnockoutTableData);

          }
          for (let m = 0; m <concQuery.length; m++){
            const tconcQuery = concQuery[m][0].trim().split('|');
                  const plotName=concQuery[m][0].trim();
                  const sampleLLOQ=concQuery[m][1].trim();
                  const ULOQ=concQuery[m][2].trim();
                  const plotData=[];
                  const plotDataSampleLLOQ=[];
                  
            for(let x = 0; x <this.allConcSamLLOQ.length; x++){
              const tempConcAllSamLLOQ=this.allConcSamLLOQ[x][1].trim().split(';');
              if ('NA' != Array.from(new Set(tempConcAllSamLLOQ)).join('')){
                for(let i = 0; i <tempConcAllSamLLOQ.length; i++){
                  const subConcAllSamLLOQ=tempConcAllSamLLOQ[i].trim().split('|');
                  if(subConcAllSamLLOQ[1] == tconcQuery[0] && subConcAllSamLLOQ[2] == tconcQuery[1] && this.allConcSamLLOQ[x][0] == tconcQuery[2]){
                    plotDataSampleLLOQ.push(subConcAllSamLLOQ.slice(-3)[0].split('(')[0].trim())
                      
                  }
                }

              }
            }
            //Group-1|Wild type|Plasma|1|C57BL6NCrl_Perfused|Female
            for(let z = 0; z <this.allConc.length; z++){
              const tempConcAll=this.allConc[z][1].trim().split(';')
              for(let j = 0; j <tempConcAll.length; j++){
                const subConcAll=tempConcAll[j].trim().split('|');
                if(subConcAll[1] == tconcQuery[0] && subConcAll[2] == tconcQuery[1] && this.allConc[z][0] == tconcQuery[2]){
                  plotData.push(subConcAll.slice(-3)[0].split('(')[0].trim())
                  tempUnit.push('('+subConcAll.slice(-3)[0].split('(')[1].trim());
                    
                }
              }
            }
            const tempPlotArray=[plotName,plotData.join('|'),plotDataSampleLLOQ.join('|'),sampleLLOQ,ULOQ];
            this.concenPlotlyData.push(tempPlotArray.join(';'));
                  
          }

          this.concenPlotDataUnit ='Concentration '+Array.from(new Set(tempUnit)).join('&');
          //var plotLyHTML='<div id="myDivConc"></div>';
                  
          this.boxplot(this.concenPlotlyData,this.concenPlotDataUnit,1,concenTabName);
        }
      } else if (concenTabName == "sex") {
        let strs='';
        let tempUnit=[];
        if (this.sexData.length >0 ){
          this.sexDataLen=1;
          for(let y = 0; y <this.sexData.length; y++){
            let sexifo = this.sexData[y];
            let tempSampLLOQ=sexifo[8];
            let tempULOQ=sexifo[9];
            let tempconcQuery=[];
            tempconcQuery.push(sexifo[1].trim());
            tempconcQuery.push(sexifo[4].trim());
            tempconcQuery.push(sexifo[2].trim());
            concQuery.push([tempconcQuery.join('|'),tempSampLLOQ,tempULOQ]);
            let tempView='<a target="_blank"  routerLinkActive="active" href="/dataload/concentration_'+sexifo[7].trim()+'" >' + 'View' + '</a>';
            let tempSexTableData=[sexifo[1].trim(),sexifo[4].trim(), sexifo[5].trim(), sexifo[6].trim(), sexifo[0].trim(), tempView,sexifo[2].trim()];
            this.sexDataTableData.push(tempSexTableData);
          }
          for (let m = 0; m <concQuery.length; m++){
            const tconcQuery = concQuery[m][0].trim().split('|');
                  const plotName=concQuery[m][0].trim();
                  const sampleLLOQ=concQuery[m][1].trim();
                  const ULOQ=concQuery[m][2].trim();
                  const plotData=[];
                  const plotDataSampleLLOQ=[];
                  
            for(let x = 0; x <this.allConcSamLLOQ.length; x++){
              const tempConcAllSamLLOQ=this.allConcSamLLOQ[x][1].trim().split(';');
              if ('NA' != Array.from(new Set(tempConcAllSamLLOQ)).join('')){
                for(let i = 0; i <tempConcAllSamLLOQ.length; i++){
                  const subConcAllSamLLOQ=tempConcAllSamLLOQ[i].trim().split('|');
                  if(subConcAllSamLLOQ[5] == tconcQuery[0] && subConcAllSamLLOQ[2] == tconcQuery[1] && this.allConcSamLLOQ[x][0] == tconcQuery[2]){
                    plotDataSampleLLOQ.push(subConcAllSamLLOQ.slice(-3)[0].split('(')[0].trim())
                      
                  }
                }

              }
            }
            //Group-1|Wild type|Plasma|1|C57BL6NCrl_Perfused|Female
            for(let z = 0; z <this.allConc.length; z++){
              const tempConcAll=this.allConc[z][1].trim().split(';')
              for(let j = 0; j <tempConcAll.length; j++){
                const subConcAll=tempConcAll[j].trim().split('|');
                if(subConcAll[5] == tconcQuery[0] && subConcAll[2] == tconcQuery[1] && this.allConc[z][0] == tconcQuery[2]){
                  plotData.push(subConcAll.slice(-3)[0].split('(')[0].trim())
                  tempUnit.push('('+subConcAll.slice(-3)[0].split('(')[1].trim());
                    
                }
              }
            }
            const tempPlotArray=[plotName,plotData.join('|'),plotDataSampleLLOQ.join('|'),sampleLLOQ,ULOQ];
            this.concenPlotlyData.push(tempPlotArray.join(';'));
                  
          }

          this.concenPlotDataUnit ='Concentration '+Array.from(new Set(tempUnit)).join('&');
          //var plotLyHTML='<div id="myDivConc"></div>';
                  
          this.boxplot(this.concenPlotlyData,this.concenPlotDataUnit,1,concenTabName);
        }
      }
    //this.boxplot(this.concenPlotlyData,this.concenPlotDataUnit,1);

  }

  boxplot(dataToPlot:any,yAxisTile:any,tisPos:any, clickedTabName:any):void {
      const tissueColor= {
        "Brain":"cyan",
        "Brown Adipose":"olive",
        "Epididymis":"slategray",
        "Eye":"rosybrown", 
        "Heart":"darksalmon",
        "Kidney":"lightcoral",
        "Liver Caudate and Right Lobe":"sandybrown",
        "Liver Left Lobe":"deepskyblue",
        "Lung":"tan",
        "Pancreas":"cadetblue",
        "Plasma":"greenyellow",
        "Ovary":"goldenrod",
        "RBCs":"seagreen",
        "Salivary Gland":"chocolate",
        "Seminal Vesicles":"khaki",
        "Skeletal Muscle":"indigo",
        "Skin":"thistle",
        "Spleen":"violet",
        "Testes":"lightpink",
        "White Adipose":"plum"
      };
      let boxPlotDataArray=[];
      let boxPlotDataArrayLog2=[];
      let boxPlotDataArrayLog10=[];
      yAxisTile='Concentration<br>(fmol target protein/µg extracted protein)';
      let layout={
        yaxis:{
        title:yAxisTile,
        zeroline:false,
        showlegend: true,
        legend :{
          x:dataToPlot.length+1
        }
       },
       xaxis:{
         automargin: true,
         showticklabels:false
       }
      };

      let layout2={
        yaxis:{
        title:'Concentration<br>(fmol target protein/µg extracted protein)<br> in Log2 Scale',
        zeroline:false,
        showlegend: true,
        legend :{
          x:dataToPlot.length+1
        }
       },
       xaxis:{
         automargin: true,
         showticklabels:false
       }
      };

      let layout10={
        yaxis:{
        title:'Concentration<br>(fmol target protein/µg extracted protein)<br> in Log10 Scale',
        zeroline:false,
        showlegend: true,
        legend :{
          x:dataToPlot.length+1
        }
       },
       xaxis:{
         automargin: true,
         showticklabels:false
       }
      };
      const d3colors = Plotly.d3.scale.category10();
      let defaultPlotlyConfiguration={};
      defaultPlotlyConfiguration ={
        responsive: true,
        scrollZoom: true,
        showTips:true,
        modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
        displayLogo: false
      };

      for(let i=0; i< dataToPlot.length;i++){
        const tempPlotDataArray=dataToPlot[i].split(';');
        const plotDataArray=[];
        const plotDataArrayLog2=[];
        const plotDataArrayLog10=[];
        let tempArray=tempPlotDataArray[2].split('|');
        if (tempPlotDataArray[2] === 'NA' || tempPlotDataArray[2].trim().length == 0){
          tempArray=tempPlotDataArray[1].split('|');
        }
        for(let j=0; j< tempArray.length;j++){
           if (parseFloat(tempArray[j]) >0){
             plotDataArray.push(parseFloat(tempArray[j]));
             plotDataArrayLog2.push(Math.log2(parseFloat(tempArray[j])));
             plotDataArrayLog10.push(Math.log10(parseFloat(tempArray[j])));
           }
        }
        let boxPlotData={};
        let boxPlotDataLog2={};
        let boxPlotDataLog10={};

        let boxSamLLOQData={};
        let boxSamLLOQDataLog2={};
        let boxSamLLOQDataLog10={};

        let boxULOQData={};
        let boxULOQDataLog2={};
        let boxULOQDataLog10={};

        let tempplotDataArray=plotDataArray.filter(value=> !Number.isNaN(value));

        if (tempPlotDataArray[2] === 'NA' || tempPlotDataArray[2].trim().length == 0){
          if (tempplotDataArray.length > 0){
            boxPlotData={
              y:plotDataArray,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
            boxPlotDataLog2={
              y:plotDataArrayLog2,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
            boxPlotDataLog10={
              y:plotDataArrayLog10,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
          }

        } else {
          if (tempplotDataArray.length > 0){
            const tempColor=tissueColor[tempPlotDataArray[0].split('|')[tisPos]];
              boxPlotData={
                y:plotDataArray,
                name: tempPlotDataArray[0],
                boxpoints: 'all',
                jitter: 0,
                pointpos: 0,
                boxmean:true,
                marker:{
                  color:tempColor
                },
                type:'box'
              };
              boxPlotDataLog2={
                y:plotDataArrayLog2,
                name: tempPlotDataArray[0],
                boxpoints: 'all',
                jitter: 0,
                pointpos: 0,
                boxmean:true,
                marker:{
                  color:tempColor
                },
                type:'box'
              };
              boxPlotDataLog10={
                y:plotDataArrayLog10,
                name: tempPlotDataArray[0],
                boxpoints: 'all',
                jitter: 0,
                pointpos: 0,
                boxmean:true,
                marker:{
                  color:tempColor
                },
                type:'box'
              };
          }
        }
        if (tempplotDataArray.length > 0){
            boxSamLLOQData={
              x:[tempPlotDataArray[0]],
              y:[parseFloat(tempPlotDataArray[3])],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };


            boxSamLLOQDataLog2={
              x:[tempPlotDataArray[0]],
              y:[Math.log2(parseFloat(tempPlotDataArray[3]))],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };

            boxSamLLOQDataLog10={
              x:[tempPlotDataArray[0]],
              y:[Math.log10(parseFloat(tempPlotDataArray[3]))],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };

            boxULOQData={
              x:[tempPlotDataArray[0]],
              y:[parseFloat(tempPlotDataArray[4])],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };


            boxULOQDataLog2={
              x:[tempPlotDataArray[0]],
              y:[Math.log2(parseFloat(tempPlotDataArray[4]))],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };

            boxULOQDataLog10={
              x:[tempPlotDataArray[0]],
              y:[Math.log10(parseFloat(tempPlotDataArray[4]))],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };

            boxPlotDataArray.push(boxPlotData);
            boxPlotDataArray.push(boxSamLLOQData);
            boxPlotDataArray.push(boxULOQData);
            boxPlotDataArrayLog2.push(boxPlotDataLog2);
            boxPlotDataArrayLog2.push(boxSamLLOQDataLog2);
            boxPlotDataArrayLog2.push(boxULOQDataLog2);
            boxPlotDataArrayLog10.push(boxPlotDataLog10);
            boxPlotDataArrayLog10.push(boxSamLLOQDataLog10);
            boxPlotDataArrayLog10.push(boxULOQDataLog10);

        }
      }

     let finalBoxPlotDataArray={
       0:boxPlotDataArray,
       1:boxPlotDataArrayLog2,
       2:boxPlotDataArrayLog10
     }
     let plotlyWidth=$(window).width();
     plotlyWidth=plotlyWidth-320;
     const updatedDimension={
       width:plotlyWidth
     }
     if (clickedTabName=='str'){
       if(document.getElementById('myDivConcStrain')){
      /* Plotly.newPlot('myDivConcStrain',finalBoxPlotDataArray[0],layout,defaultPlotlyConfiguration);      
          Plotly.newPlot('myDivConcStrain',finalBoxPlotDataArray[1],layout2,defaultPlotlyConfiguration);*/
          Plotly.newPlot('myDivConcStrain',finalBoxPlotDataArray[2],layout10,defaultPlotlyConfiguration);
          Plotly.relayout('myDivConcStrain',updatedDimension);
          Plotly.purge('myDivConcSex');
          Plotly.purge('myDivConcKnockout');
          Plotly.purge('myDivConcBioMat');
      }
        if (dataToPlot.length==0){
          if(document.getElementById('myDivConcStrain')){
            Plotly.purge('myDivConcStrain')
          }
        }
     } else if (clickedTabName=='sex'){
       if(document.getElementById('myDivConcSex')){
      /* Plotly.newPlot('myDivConcSex',finalBoxPlotDataArray[0],layout,defaultPlotlyConfiguration);      
          Plotly.newPlot('myDivConcSex',finalBoxPlotDataArray[1],layout2,defaultPlotlyConfiguration);*/
          Plotly.newPlot('myDivConcSex',finalBoxPlotDataArray[2],layout10,defaultPlotlyConfiguration);
          Plotly.relayout('myDivConcSex',updatedDimension);
          Plotly.purge('myDivConcStrain');
          Plotly.purge('myDivConcKnockout');
          Plotly.purge('myDivConcBioMat');
      }
        if (dataToPlot.length==0){
          if(document.getElementById('myDivConcSex')){
            Plotly.purge('myDivConcSex')
          }
        }
     } else if (clickedTabName=='knock'){
       if(document.getElementById('myDivConcKnockout')){
      /* Plotly.newPlot('myDivConcKnockout',finalBoxPlotDataArray[0],layout,defaultPlotlyConfiguration);      
          Plotly.newPlot('myDivConcKnockout',finalBoxPlotDataArray[1],layout2,defaultPlotlyConfiguration);*/
          Plotly.newPlot('myDivConcKnockout',finalBoxPlotDataArray[2],layout10,defaultPlotlyConfiguration);
          Plotly.relayout('myDivConcKnockout',updatedDimension);
          Plotly.purge('myDivConcStrain');
          Plotly.purge('myDivConcSex');
          Plotly.purge('myDivConcBioMat');
      }
        if (dataToPlot.length==0){
          if(document.getElementById('myDivConcKnockout')){
            Plotly.purge('myDivConcKnockout')
          }
        }
     } else if (clickedTabName=='biomat'){
       if(document.getElementById('myDivConcBioMat')){
      /* Plotly.newPlot('myDivConcBioMat',finalBoxPlotDataArray[0],layout,defaultPlotlyConfiguration);      
          Plotly.newPlot('myDivConcBioMat',finalBoxPlotDataArray[1],layout2,defaultPlotlyConfiguration);*/
          Plotly.newPlot('myDivConcBioMat',finalBoxPlotDataArray[2],layout10,defaultPlotlyConfiguration);
          Plotly.relayout('myDivConcBioMat',updatedDimension);
          Plotly.purge('myDivConcStrain');
          Plotly.purge('myDivConcSex');
          Plotly.purge('myDivConcKnockout');
      }
        if (dataToPlot.length==0){
          if(document.getElementById('myDivConcBioMat')){
            Plotly.purge('myDivConcBioMat')
          }
        }
     }
    }

  onOptionsSelected(event){
      if(event.target){
        let tempPlotData=this.finalPlotData['plotData'];
        let tempPlotLayout=this.finalPlotData['plotLayout'];
        let tempConfig=this.finalPlotData['config'];
        if (this.selected.name == 'Concentration Data'){
          Plotly.purge('myDivConcAll')
          Plotly.newPlot('myDivConcAll',tempPlotData[0],tempPlotLayout[0],tempConfig)
        }

        if (this.selected.name == 'Log2(Concentration Data)'){
          Plotly.purge('myDivConcAll')
          Plotly.newPlot('myDivConcAll',tempPlotData[1],tempPlotLayout[1],tempConfig)
        }

        if (this.selected.name == 'Log10(Concentration Data)'){
          Plotly.purge('myDivConcAll')
          Plotly.newPlot('myDivConcAll',tempPlotData[2],tempPlotLayout[2],tempConfig)
        }
        
      }
    }

  private openTabsConcen(evt, tabName) {
      this.prepareDataToCocenComb(tabName);
      var i, tabcontent, tablinks;
      tabcontent = document.getElementsByClassName("tabcontentconcen");
      for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
      }
      tablinks = document.getElementsByClassName("tablinksconcen");
      for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
      }
      document.getElementById(tabName).style.display = "block";
      evt.currentTarget.className += " active";
  }
}
<file_sep>/backend/updatefile/addSelCol.py
import os,subprocess,psutil,re,shutil,datetime,sys,glob
import csv
import ctypes

def addSelCol():
	homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	filename='ReportBook_mother_file.csv'
	filepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)
	addselfile="addsel.csv"
	aoutput= open(addselfile,'w')
	with open(filepath,'r') as f:
		for line in f:
			info=line.rstrip().split('\t')
			if 'UniProtKB Accession' in info:
				info.insert(0,"sel")
				aoutput.write(('\t'.join(info))+'\n')
			else:
				info.insert(0,"")
				aoutput.write(('\t'.join(info))+'\n')
	aoutput.close()
	movefilepath=os.path.join(homedir, 'updatefile', filename)
	os.rename(addselfile,filename)
	shutil.move(movefilepath,filepath)<file_sep>/backend/src/qmpkbapp/adjustP.py
import numpy as np

def p_adjust_bh(p):
	"""Benjamini-Hochberg p-value correction for multiple hypothesis testing."""
	p = np.asfarray(p)
	by_descend = p.argsort()[::-1]
	by_orig = by_descend.argsort()
	steps = float(len(p)) / np.arange(len(p), 0, -1)
	q = np.minimum(1, np.minimum.accumulate(steps * p[by_descend]))
	return q[by_orig]<file_sep>/client/qmpkb-app/src/app/data-submission-form/data-submission-form.component.ts
import { Component, OnInit, HostListener } from '@angular/core';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-data-submission-form',
  templateUrl: './data-submission-form.component.html',
  styleUrls: ['./data-submission-form.component.css']
})
export class DataSubmissionFormComponent implements OnInit {

	submissionForm: FormGroup;
	disabledSubmitButton: boolean = true;
	optionsSelect: Array<any>;

	@HostListener('input') oninput() {
		if (this.submissionForm.valid) {
			this.disabledSubmitButton = false;
		}
	}
	constructor(
		private http: HttpClient,
		private fb: FormBuilder
		) {
		this.submissionForm = fb.group({
			'submissionFormName': ['', Validators.required],
			'submissionFormEmail': ['', Validators.compose([Validators.required, Validators.email])],
			'submissionFormLaboratory': ['', Validators.required],
			'submissionFormExperiment': ['', Validators.required],
			'submissionFormPublication': [''],
			'submissionFormDataRepository': ['', Validators.required],
			'submissionFormDataAcessionNumber': ['', Validators.required],
			'submissionFormRepositoryPassword': [''],
			'submissionFormMessage': ['', Validators.required],
			'submissionFormCopy': [''],
		});
	}



  ngOnInit() {
  }

	onSubmit() {
		if (this.submissionForm.valid) {
			alert('We have received your data.');
			this.http.get('/submissionapi/?submissiondetails=' + JSON.stringify(this.submissionForm.value)).subscribe(response => {},errors => {console.log(errors)});
			this.submissionForm.reset();
			this.disabledSubmitButton = true;
		}
	}
}
<file_sep>/client/qmpkb-app/src/app/human-prott-vista-view/human-prott-vista-view.component.ts
import { Component, OnInit, Input} from '@angular/core';
import * as $ from "jquery";

declare var require: any
declare var jquery: any;

@Component({
  selector: 'app-human-prott-vista-view',
  templateUrl: './human-prott-vista-view.component.html',
  styleUrls: ['./human-prott-vista-view.component.css']
})
export class HumanProttVistaViewComponent implements OnInit  {

  humanPepStart:number;
  humanPepEnd:number;
  humanUniprotKB:any;
  queryHuamanProtVistaInfo:any;
  humanProtvistaQueryData:any;
  constructor(
    ) { }

    @Input()
    set humanProtVistamQuery(humanProtvistaQueryInfo:any){
      this.queryHuamanProtVistaInfo=humanProtvistaQueryInfo;

    }

  ngOnInit() {
    this.humanUniprotKB=this.queryHuamanProtVistaInfo.humanUniprotKB;
    this.humanPepStart=this.queryHuamanProtVistaInfo.humanPepStart;
    this.humanPepEnd=this.queryHuamanProtVistaInfo.humanPepEnd;
    if (this.humanPepEnd > 0){
       setTimeout(() => {this.plotProtVistaHumanFunc(this.humanUniprotKB,this.humanPepStart,this.humanPepEnd)}, 100); 
   };

  }

  plotProtVistaHumanFunc(protvistaHumanUni:string,humanPreSelectStart:number,humanPreSelectEnd:number): void {

    if (humanPreSelectStart >0){
        var humanDiv = document.getElementById('humanDiv');
        var ProtVistaHuman = require('ProtVista');
        var humaninstance = new ProtVistaHuman({
          el: humanDiv,
          uniprotacc: protvistaHumanUni,
          defaultSources: true,
          //These categories will **not** be rendered at all
          exclusions: ['SEQUENCE_INFORMATION', 'STRUCTURAL', 'TOPOLOGY', 'MOLECULE_PROCESSING', 'ANTIGEN'],
          //Your data sources are defined here
          customDataSource: {
            url: 'fileapi/resultFile/jsonData/protvistadataJson/human/externalLabeledFeatures_',
            source: 'MouseQuaPro',
            useExtension: true
          },
          categoryOrder: ['TARGETED_PROTEOMICS_ASSAY_HUMAN', 'PROTEOMICS', 'DOMAINS_AND_SITES', 'PTM', 'MUTAGENESIS'],
          //This feature will be preselected
          selectedFeature: {
          begin: humanPreSelectStart,
          end: humanPreSelectEnd,
          type: 'MRM'
          },
        });
    }
  }

}
<file_sep>/backend/updatefile/ncbiGeneAPI.py
import json
from Bio import Entrez
import sys,urllib3,requests,time,datetime,urllib2
import os,subprocess,psutil,re,shutil,glob
from socket import error as SocketError
import errno
import random
import csv
import requests
import ctypes

def ncbiGeneExp():
	#increase the field size of CSV
	print ("NCBI Gene transcription, job starts",str(datetime.datetime.now()))
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
	filename='ReportBook_mother_file.csv'
	filepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)
	finalresult=[]
	RETRY_TIME=20
	Entrez.email = "<EMAIL>"
	handleNCBI = Entrez.einfo()
	recordNCBI = Entrez.read(handleNCBI)
	with open(filepath) as tsvfile:
		reader = csv.DictReader(tsvfile, delimiter='\t')
		colName=reader.fieldnames
		addNewCol=['Gene Expression Data','Gene Expression View']
		colName=colName+addNewCol
		finalresult.append(colName)
		for row in reader:
			expData='No'
			maxRPKMMeanOrgan='No'
			mouseUniID=row['UniProtKB Accession'].strip()
			RETRY_TIME = 20.0
			while True:
				try:
					handleIDNCBI = Entrez.esearch(db="gene",term=mouseUniID+"[Protein Accession]")
					recordIDNCBI = Entrez.read(handleIDNCBI)
					try:
						hitIDNCBI=recordIDNCBI["IdList"][0]
						httpNCBI = urllib3.PoolManager()
						expNCBIURL='https://www.ncbi.nlm.nih.gov/gene/'+hitIDNCBI+'/?report=expression'
						urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
						try:
							expNCBIResponse = httpNCBI.request('GET', expNCBIURL)
							expNCBIData=str(expNCBIResponse.data)
							tempExpNCBIList=[]
							for eData in expNCBIData.split('\n'):
								if 'var tissues_data = {' in eData.strip():
									organSpecExpData=str(eData.strip().replace('\\','').split('=')[1].replace('}};','}}'))
									organSpecExpData=organSpecExpData.replace("'", "\"")
									organSpecExpDic=json.loads(organSpecExpData)
									for eKey in organSpecExpDic:
										geneID=organSpecExpDic[eKey]['gene']
										meanExpRPKM=organSpecExpDic[eKey]['exp_rpkm']
										if int(hitIDNCBI) == int(geneID):
											if float(str(meanExpRPKM).strip()) >0:
												tempExpNCBIList.append([str(eKey).strip(),str(meanExpRPKM).strip()])

							if len(tempExpNCBIList)>0:
								expData='MeanExpressionInRPKM|Tissue'
								tempData=';'.join(['|'.join(i) for i in tempExpNCBIList])
								expData=expData+';'+tempData
								tempExpNCBIList.sort(key=lambda x: float(x[1]))
								maxRPKMMeanOrgan=str(tempExpNCBIList[-1][1])+' (Mean RPKM in '+str(tempExpNCBIList[-1][0])+')'
						except urllib3.exceptions.NewConnectionError:
							print('Connection failed.')
							pass
					except IndexError:
						pass
						
					break
				except urllib2.HTTPError:
					time.sleep(RETRY_TIME)
					print 'Hey, I am trying again until succeeds to get data from NCBI Gene Exp!',str(datetime.datetime.now())
					pass
			row['Gene Expression Data']=expData
			row['Gene Expression View']=maxRPKMMeanOrgan
			tempList=[]
			for col in colName: 
				tempList.append(row[col])
			finalresult.append(tempList)

	outputresultpeptrack=dgnosvoutputresultpeptrack=filepath
	with open(outputresultpeptrack,'wb') as pf:
		pwriter =csv.writer(pf,delimiter='\t')
		pwriter.writerows(finalresult)
	print ("NCBI Gene transcription, job done",str(datetime.datetime.now()))<file_sep>/client/qmpkb-app/src/app/dropdown-service/where.ts
export class Where {
  constructor(public id: string,  public selectid: string ,public name: string ) { }
}<file_sep>/backend/updatefile/presencePepSeqInHuman.py
import os,subprocess,psutil,re,shutil,datetime,sys,glob
import urllib,urllib2,urllib3
from socket import error as SocketError
import errno
from Bio import SeqIO
import random, time
import csv
import requests
import ctypes

def presencePepSeqHuman():
	print ("Checking peptide sequence presence in Human homolog sequence, job starts",str(datetime.datetime.now()))
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
	filename='ReportBook_mother_file.csv'
	filepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)
	finalresult=[]
	with open(filepath) as tsvfile:
		reader = csv.DictReader(tsvfile, delimiter='\t')
		colName=reader.fieldnames
		addNewCol=['Present in human ortholog','Unique in human protein', 'Present in human isoforms']
		colName=colName+addNewCol
		finalresult.append(colName)
		for row in reader:
			pepSeq=row['Peptide Sequence'].strip()
			humanUniId=row['Human UniProtKB Accession'].strip()
			row['Present in human ortholog']='No'
			row['Unique in human protein']='NA'
			row['Present in human isoforms']='NA'
			pepisodata=[]
			humanCanoPepUnId=''
			humanPepUnIdVer=''
			unqStatus=False
			otherProPresentStatus=False
			if '-' in humanUniId:
				pepUnIdInfo=humanUniId.split('-')
				humanCanoPepUnId=pepUnIdInfo[0]
				humanPepUnIdVer=pepUnIdInfo[-1]
			else:
				humanCanoPepUnId=humanUniId
			try:
				tempfastaseq=''
				unifastaurl="https://www.uniprot.org/uniprot/"+str(humanUniId)+".fasta"
				fastaresponse = urllib.urlopen(unifastaurl)
				for seq in SeqIO.parse(fastaresponse, "fasta"):
					tempfastaseq=(seq.seq).strip()

				if len(tempfastaseq.strip()) >0 and pepSeq in tempfastaseq:
					row['Present in human ortholog']='Yes'
					while True:
						try:
							PIRpepMatrequestURLUnq ="https://research.bioinformatics.udel.edu/peptidematchapi2/match_get?peptides="+str(pepSeq)+"&taxonids=9606&swissprot=true&isoform=true&uniref100=false&leqi=false&offset=0&size=-1"
							urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
							PIRPepMatrUnq = requests.get(PIRpepMatrequestURLUnq, headers={ "Accept" : "application/json"},verify=False)

							if not PIRPepMatrUnq.ok:
							  PIRPepMatrUnq.raise_for_status()
							  sys.exit()

							PIRPepMatresponseBodyUnq = PIRPepMatrUnq.json()

							if len(PIRPepMatresponseBodyUnq['results'][0]['proteins'])>0:
								for piritemUnq in PIRPepMatresponseBodyUnq['results'][0]['proteins']:
									uniId=piritemUnq['ac'].strip()
									pirRevStatUnq=piritemUnq['reviewStatus'].strip()

									if 'sp' == (str(pirRevStatUnq).lower()).strip():
										canoUniId=''
										uniIdVer=''
										if '-' in uniId:
											uniIdinfo=uniId.split('-')
											canoUniId=uniIdinfo[0]
											uniIdVer=uniIdinfo[-1]
										else:
											canoUniId=uniId
										for mxmatchpep in piritemUnq["matchingPeptide"]:
											uimatchpeptide=mxmatchpep["peptide"]
											if str(uimatchpeptide).strip() ==pepSeq:
												if (canoUniId.strip()).lower() == (humanCanoPepUnId.strip()).lower():
													if len(uniIdVer.strip()) ==0:
														unqStatus=True
													if len(uniIdVer.strip()) !=0:
														unqStatus=False
														pepisodata.append(str(uniId))
												if (canoUniId.strip()).lower() != (humanCanoPepUnId.strip()).lower():
													otherProPresentStatus=True

							break
						except requests.exceptions.ConnectionError:
							time.sleep(RETRY_TIME)
							print ('Hey, I am trying again until succeeds to get data from Peptide Match Server!',str(datetime.datetime.now()))
							pass
						except requests.exceptions.ChunkedEncodingError:
							time.sleep(RETRY_TIME)
							print ('chunked_encoding_error happened',str(datetime.datetime.now()))
							pass
							
			except IOError:
				pass

			if row['Present in human ortholog'] =='Yes':
				if unqStatus:
					if otherProPresentStatus:
						row['Unique in human protein']='Not unique'
					else:
						row['Unique in human protein']='Yes'
				else:
					row['Unique in human protein']='Not unique'

				if len(pepisodata)>0:
					row['Present in human isoforms']=','.join(list(set(pepisodata)))
				else:
					row['Present in human isoforms']='No'

			tempList=[]
			for col in colName: 
				tempList.append(row[col])
			finalresult.append(tempList)

	outputresultpeptrack=filepath
	with open(outputresultpeptrack,'wb') as pf:
		pwriter =csv.writer(pf,delimiter='\t')
		pwriter.writerows(finalresult)
	print ("Checking peptide sequence presence in Human ortholog sequence, job done",str(datetime.datetime.now()))
<file_sep>/client/qmpkb-app/src/app/dropdown-service/select.ts
export class Select {
  constructor(public id: string,  public name: string) { }
}<file_sep>/client/qmpkb-app/src/app/app.routing.ts
import {NgModule} from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { HomeComponent } from './home/home.component';
import { ResultPageComponent } from './result-page/result-page.component';
import { ResultPageUserSeqComponent } from './result-page-user-seq/result-page-user-seq.component';
import { ResultsQueryComponent } from './results-query/results-query.component';
import { HelpComponent } from './help/help.component';
import { ContactComponent } from './contact/contact.component';
import { ConcentrationComponent } from './concentration/concentration.component';
import { PathwayviewComponent } from './pathwayview/pathwayview.component';
import { PeptideuniquenessComponent } from './peptideuniqueness/peptideuniqueness.component';
import { DataLoadPageComponent } from './data-load-page/data-load-page.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { DetailInformationComponent } from './detail-information/detail-information.component';
import { ProtocolComponent } from './protocol/protocol.component';
import { DataSubmissionFormComponent } from './data-submission-form/data-submission-form.component';



const appRoutes: Routes =[
	{
		path:"",
		component:HomeComponent,
		pathMatch:'full',
	},
	{
		path:"results",
		component:ResultsQueryComponent,
	},
	{
		path:"resultsseq",
		component:ResultPageUserSeqComponent,
	},
	{
		path:"protocol",
		component:ProtocolComponent,
	},
	{
		path:"help",
		component:HelpComponent,
	},
	{
		path:"contact",
		component:ContactComponent,
	},
	{
		path:"concentration",
		component:ConcentrationComponent,
	},
	{
		path:"peptideuniqueness",
		component:PeptideuniquenessComponent,
	},
	{
		path:"detailinformation",
		component:DetailInformationComponent,
	},
	{
		path:"viewpathway",
		component:PathwayviewComponent,
	},
	{
		path:"submission",
		component:DataSubmissionFormComponent,
	},
	{
		path:"dataload/:slug",
		component:DataLoadPageComponent,
	},
	{
		path:"**",
		component:NotFoundComponent,
	}
]



@NgModule({
	imports:[
		RouterModule.forRoot(
			appRoutes
		)
	],
	exports:[
		RouterModule
	]
})

export class AppRoutingModule{}<file_sep>/client/qmpkb-app/src/app/pathway/pathway.component.ts
import { Component, OnInit, OnDestroy,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

@Component({
  selector: 'app-pathway',
  templateUrl: './pathway.component.html',
  styleUrls: ['./pathway.component.css']
})
export class PathwayComponent implements OnInit {
  dtOptions: any = {};
  errorStr:Boolean;
  keggData:any;
  keggDatalen:number;
  pathwayInputData:any;
  pathwayDataStatus=false;
  queryData:any;

  pathViewUniprotid:any;
  pathViewUniprotname:any;
  keggimagedict:any;
  keggimagedictlen:number;
  otherkeggcolor:any;
  notpresentkeggcolor:any;
  screenWidth:any;

  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { }

  @Input()
  set pathwaytermQuery(pathQuery:any){
      this.pathwayInputData=pathQuery;

  }

  ngOnInit() {

    this._qmpkb.receiveDataFromBackendSearch('/pathwayapi/?uniProtKb='+ this.pathwayInputData).subscribe((response: any)=>{
        this.queryData=response;
        this.keggData=this.queryData.pathWayList;
        this.keggDatalen=Object.keys(this.keggData).length;
        this.pathwayDataStatus=true;
        this.dtOptions = {
          processing: true,
          serverSide: false,
          orderCellsTop: true,
          fixedHeader: true,
          pageLength: 10,
          pagingType: 'full_numbers',
          scrollX:true,
          scrollY:'650px',
          scrollCollapse:true,
          // Declare the use of the extension in the dom parameter
          dom: 'lBfrtip',
          buttons: [
              {
                extend:'csv',
                filename: 'PathwayMouseQuaPro',
                text:'Download all(CSV)'
              },
              {
                extend:'excel',
                filename: 'PathwayMouseQuaPro',
                text:'Download all(Excel)'
              }
          ],
          autoWidth:true  
         };
    }, error=>{
        this.errorStr = error;
    });
  }
  
}



<file_sep>/client/qmpkb-app/src/app/disease-information/disease-information.component.ts
import { Component, OnInit, OnDestroy,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-disease-information',
  templateUrl: './disease-information.component.html',
  styleUrls: ['./disease-information.component.css']
})
export class DiseaseInformationComponent implements OnInit {
  disDataStatus=false;
  humanDiseaseUniProt:any;
  humanDiseaseDisGeNet:any;
  humanDiseaseUniProtArray:any;
  humanDiseaseDisGeNetArray:any;
  diseaseInputData:any;
  filterredHumanDiseaseUniProt:any;
  filterredHumanDiseaseDisGeNet:any;
  filterHumanDiseaseUniProtStatus=false;
  filterHumanDiseaseDisGeNetStatus=false;

  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { }

  @Input()
  set diseasetermQuery(disQuery:any){
      this.diseaseInputData=disQuery;

  }

  ngOnInit() {
  	this.disDataStatus=true;
    this.humanDiseaseUniProtArray=this.diseaseInputData.humanDiseaseUniProt;
  	this.humanDiseaseUniProt=this.diseaseInputData.humanDiseaseUniProt.join('; ');
    this.humanDiseaseDisGeNetArray=this.diseaseInputData.humanDiseaseDisGeNet;
  	this.humanDiseaseDisGeNet=this.diseaseInputData.humanDiseaseDisGeNet.join('; ');
  }

  ngAfterViewInit(): void {
      var self= this;
      $("#myInputUniProt").on("keyup", function() {
        const valueUniProt = $(this).val().toString().toLowerCase();
        if (valueUniProt.trim().length > 0){
          self.filterHumanDiseaseUniProtStatus=true;
          const textArrayUniProt=self.humanDiseaseUniProtArray;
          let textContentUniProt=[];
          for(let i=0; i < textArrayUniProt.length; i++){
              const strUniProt = textArrayUniProt[i];
              const divUniProt=document.createElement('div');
              divUniProt.innerHTML=strUniProt;
              if (textArrayUniProt[i] == 'NA'){
                textContentUniProt.push(textArrayUniProt[i]);
              } else{
               textContentUniProt.push(divUniProt.children[0].textContent);
              }
          }
          const filterredUniProt=textContentUniProt.filter(function (elem) {
             return elem.toString().toLowerCase().indexOf(valueUniProt) > -1;
          });
          if (filterredUniProt.length >0){
              const tempData=[];
              for(let j=0; j < filterredUniProt.length; j++){
                tempData.push(textArrayUniProt[textContentUniProt.indexOf(filterredUniProt[j])])
              }
              self.filterredHumanDiseaseUniProt=tempData.join('; '); 
          } else{
             self.filterredHumanDiseaseUniProt='Oopps. No result matched with your search criteria!'; 
          }      
        } 
        if (valueUniProt.trim().length == 0){
          self.filterHumanDiseaseUniProtStatus=false;
        }
      });

      $("#myInputDisGenNet").on("keyup", function() {
        const valueDisGenNet = $(this).val().toString().toLowerCase();
        if (valueDisGenNet.trim().length > 0){
          self.filterHumanDiseaseDisGeNetStatus=true;
          const textArrayDisGeNet=self.humanDiseaseDisGeNetArray;
          let textContentDisGeNet=[];
          for(let i=0; i < textArrayDisGeNet.length; i++){
              const strDisGeNet = textArrayDisGeNet[i];
              const divDisGeNet=document.createElement('div');
              divDisGeNet.innerHTML=strDisGeNet;
              if (textArrayDisGeNet[i] == 'NA'){
                textContentDisGeNet.push(textArrayDisGeNet[i]);
              } else{
                textContentDisGeNet.push(divDisGeNet.children[0].textContent);
              }
              
          }
          const filterredDisGeNet=textContentDisGeNet.filter(function (elem) {
             return elem.toString().toLowerCase().indexOf(valueDisGenNet) > -1;
          });
          if (filterredDisGeNet.length >0){
              const tempData=[];
              for(let j=0; j < filterredDisGeNet.length; j++){
                tempData.push(textArrayDisGeNet[textContentDisGeNet.indexOf(filterredDisGeNet[j])])
              }
              self.filterredHumanDiseaseDisGeNet=tempData.join('; '); 
          } else{
             self.filterredHumanDiseaseDisGeNet='Oopps. No result matched with your search criteria!'; 
          }      
        } 
        if (valueDisGenNet.trim().length == 0){
          self.filterHumanDiseaseDisGeNetStatus=false;
        }
      });

  }
  openTabsDis(evt, tabName) {
      var i, tabcontent, tablinks;
      tabcontent = document.getElementsByClassName("tabcontentdisease");
      for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
      }
      tablinks = document.getElementsByClassName("tablinksdisease");
      for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
      }
      document.getElementById(tabName).style.display = "block";
      evt.currentTarget.className += " active";
  }

}
<file_sep>/client/qmpkb-app/src/app/drug-bank/drug-bank.component.ts
import { Component, OnInit, OnDestroy,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-drug-bank',
  templateUrl: './drug-bank.component.html',
  styleUrls: ['./drug-bank.component.css']
})
export class DrugBankComponent implements OnInit {

  drugDataStatus=false;
  drugBankQueryData:any;
  drugBankInputData:any;
  drugBankInputDataArray:any;

  filterredDrugBankData:any;
  filterDrugBankDataStatus=false;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private _qmpkb:QmpkbService
    ) { }

  @Input()
  set drugBanktermQuery(drugQuery:any){
      this.drugBankQueryData=drugQuery;

  }

  ngOnInit() {
  	this.drugDataStatus=true;
    this.drugBankInputDataArray=this.drugBankQueryData.drugBankDataArray;
  	this.drugBankInputData=this.drugBankQueryData.drugBankData;
  }

  ngAfterViewInit(): void {
      var self= this;
      $("#myInputDrug").on("keyup", function() {
        const valueDrug = $(this).val().toString().toLowerCase();
        if (valueDrug.trim().length > 0){
          self.filterDrugBankDataStatus=true;
          const textArrayDrug=self.drugBankInputDataArray;
          let textContentDrug=[];
          for(let i=0; i < textArrayDrug.length; i++){
              const strDrug = textArrayDrug[i];
              const divDrug=document.createElement('div');
              divDrug.innerHTML=strDrug;
              if (textArrayDrug[i] == 'NA'){
              	textContentDrug.push(textArrayDrug[i]);
              } else{
              	textContentDrug.push(divDrug.children[0].textContent);
              }
              
          }
          const filterredDrug=textContentDrug.filter(function (elem) {
             return elem.toString().toLowerCase().indexOf(valueDrug) > -1;
          });
          if (filterredDrug.length >0){
              const tempData=[];
              for(let j=0; j < filterredDrug.length; j++){
                tempData.push(textArrayDrug[textContentDrug.indexOf(filterredDrug[j])])
              }
              self.filterredDrugBankData=tempData.join('; '); 
          } else{
             self.filterredDrugBankData='Oopps. No result matched with your search criteria!'; 
          }      
        } 
        if (valueDrug.trim().length == 0){
          self.filterDrugBankDataStatus=false;
        }
      });
  }

}
<file_sep>/client/qmpkb-app/src/app/qmpkb-service/qmpkb.service.spec.ts
import { TestBed } from '@angular/core/testing';

import { QmpkbService } from './qmpkb.service';

describe('QmpkbService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: QmpkbService = TestBed.get(QmpkbService);
    expect(service).toBeTruthy();
  });
});
<file_sep>/client/qmpkb-app/src/app/basic-search-without-example/basic-search-without-example.component.ts
import { Component, OnInit, Input, HostListener, Renderer } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray } from '@angular/forms';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-basic-search-without-example',
  templateUrl: './basic-search-without-example.component.html',
  styleUrls: ['./basic-search-without-example.component.css']
})
export class BasicSearchWithoutExampleComponent implements OnInit {
  searchQuery: string;
  baseUrl;
  @Input()
  passedQuery: string;
  errorStr:Boolean;
  public alertIsVisible:boolean= false;
/*  @Input() public href: string | undefined;
  @HostListener('click', ['$event']) public onClick(event: Event): void{
    if (!this.href || this.href === '#' || (this.href && this.href.length ===0)){
      event.preventDefault();
    }
  }*/

  constructor(
    private router: Router,
    private http: HttpClient,
    private renderer: Renderer,
    private _qmpkb:QmpkbService,
    private spinner: NgxSpinnerService
  ) { }


  ngOnInit() {
  }

  submitSearch(event,formData){

  	let searchedQuery = formData.value['searchterm']
    if (searchedQuery){
      this.spinner.show();
      this.router.navigate(['/results'],{queryParams:{searchterm:searchedQuery}});

    }

  }
  moveAdv(){
    location.assign('/');
  }

}<file_sep>/backend/updatefile/map_mouse_to_human.py
'''
this script based on jax lab pre-calculated homolog file
'''

import os,subprocess,psutil,re,shutil,datetime,sys,glob
import urllib,urllib2,urllib3,httplib
from socket import error as SocketError
import errno
from Bio import SeqIO
import random, time
import csv
import more_itertools as mit
import pickle
import cPickle
from xml.etree import cElementTree as ET
import xmltodict
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from bioservices.kegg import KEGG
import pandas as pd
import ctypes
from extractDisGenData import disGenData

def mapSpecies(mousepeptrackfilename):
	RETRY_TIME = 20.0
	mouseTohumanfilepath = os.path.join(os.getcwd(), 'MouseToHuman.tsv')
	print ("Extracting Mouse to Human Map data, job starts",str(datetime.datetime.now()))
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	try:
		urllib.urlretrieve('http://www.informatics.jax.org/downloads/reports/HOM_MouseHumanSequence.rpt',mouseTohumanfilepath)
		urllib.urlcleanup()
	except:
		print ("Can't able to download MouseToHuman.tsv file!!")

	colnameMousHu=['HomoloGene ID','Common Organism Name','NCBI Taxon ID','Symbol','EntrezGene ID','Mouse MGI ID','HGNC ID','OMIM Gene ID','Genetic Location','Genomic Coordinates (mouse: , human: )','Nucleotide RefSeq IDs','Protein RefSeq IDs','SWISS_PROT IDs']

	mouseHumandata=[]
	homologID=[]
	with open(mouseTohumanfilepath) as mhtsvfile:
		mhreader = csv.DictReader(mhtsvfile, delimiter='\t')
		for mhrow in mhreader:
			mhtemplist=[]
			for i in colnameMousHu:
				mhtempdata=str(mhrow[i]).strip()
				mhtemplist.append(mhtempdata)
			if len(mhtemplist[-1].strip()) >0:
				homologID.append(mhtemplist[0])
				mouseHumandata.append(mhtemplist)
	homologID=list(set(homologID))
	homologID.sort()

	mousehumandic={}
	for homologidItem in homologID:
		tempHumanHomoUniID=''
		tempMouseHomoUniID=''
		for item in mouseHumandata:
			if homologidItem == item[0]:
				if 'mouse' in item[1].strip().lower():
					tempMouseHomoUniID=item[-1].strip()
				else:
					tempHumanHomoUniID=item[-1].strip()
		if len(tempMouseHomoUniID.strip()) >0 and len(tempHumanHomoUniID.strip()) >0 and tempHumanHomoUniID.strip().upper() !='NA':
			mousehumandic[tempMouseHomoUniID]=tempHumanHomoUniID

	colname=['UniProtKB Accession','Protein','Gene','Organism','Peptide Sequence','Summary Concentration Range Data','All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based','Peptide ID',\
	'Special Residues','Molecular Weight','GRAVY Score','Transitions','Retention Time','Analytical inofrmation',\
	'Gradients','AAA Concentration','CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ','Protocol','Trypsin','QC. Conc. Data','Human UniProtKB Accession']

	finalresult=[]
	finalresult.append(colname)
	humanUniprotID=[]
	with open(mousepeptrackfilename) as csvfile:
		reader = csv.DictReader(csvfile, delimiter='\t')
		for row in reader:
			templist=[]
			for i in colname[:-1]:
				tempdata=str(row[i]).strip()
				templist.append(tempdata)
			if len(str(templist[0]).strip())>0:
				if templist[0].split('-')[0] in mousehumandic:
					humanUniprotID.append(mousehumandic[templist[0].split('-')[0]])
					templist.append(mousehumandic[templist[0].split('-')[0]])
				else:
					templist.append('NA')

			finalresult.append(templist)

	with open(mousepeptrackfilename,'wb') as pf:
		pwriter =csv.writer(pf,delimiter='\t')
		pwriter.writerows(finalresult)

	disGenDataDicName=disGenData()
	#disGenDataDicName='disGen.obj'
	disGenDataDic = cPickle.load(open(disGenDataDicName, 'rb'))
	unqhumanUniprotID=list(set(humanUniprotID))
	humanUniprotfuncinfodic={}
	countProt=0
	for subcode in unqhumanUniprotID:
		time.sleep(2)
		drugbanklist=[]
		PN='NA'
		GN='NA'
		OG='NA'
		OGID='NA'
		dislist=[]
		unidislist=[]
		unidisURLlist=[]
		disgendislist=[]
		disgendisURLlist=[]
		GoIDList=[]
		GoNamList=[]
		GoTermList=[]
		GOinfo=[]
		try:
			countProt+=1
			if countProt%1000 ==0:
				print str(countProt), "th protein Protein Name, Gene, Organism Name,drug bank data,disease data job starts",str(datetime.datetime.now())

			SGrequestURL="https://www.uniprot.org/uniprot/"+str(subcode)+".xml"
			SGunifile=urllib.urlopen(SGrequestURL)
			SGunidata= SGunifile.read()
			SGunifile.close()

			try:
				SGunidata=minidom.parseString(SGunidata)
				try:
					drugdata=(SGunidata.getElementsByTagName('dbReference'))
					for duItem in drugdata:
						if (duItem.attributes['type'].value).upper() == 'DRUGBANK':
							try:
								drugname=(str(duItem.getElementsByTagName('property')[0].attributes['value'].value).strip())
								drugid=str(duItem.attributes['id'].value).strip()
								durl='<a target="_blank" href="https://www.drugbank.ca/drugs/'+drugid+'">'+drugname+'</a>'
								drugbanklist.append(durl)
							except:
								pass
						if (duItem.attributes['type'].value).strip() == 'NCBI Taxonomy':
							try:
								OGID=str(duItem.attributes['id'].value).strip()
							except:
								pass
				except IndexError:
					pass

				try:
					godata=(SGunidata.getElementsByTagName('dbReference'))
					for gItem in godata:
						if (gItem.attributes['type'].value).upper() == 'GO':
							try:
								gonamedetails=(str(gItem.getElementsByTagName('property')[0].attributes['value'].value).strip()).split(':')[1]
								gotermdetails=(str(gItem.getElementsByTagName('property')[0].attributes['value'].value).strip()).split(':')[0]
								GoNamList.append(gonamedetails)
								goid=str(gItem.attributes['id'].value).strip()
								GoIDList.append(goid)
								tempGoTerm=None
								
								if gotermdetails.lower()=='p':
									tempGoTerm='Biological Process'
								if gotermdetails.lower()=='f':
									tempGoTerm='Molecular Function'
								if gotermdetails.lower()=='c':
									tempGoTerm='Cellular Component'
								GoTermList.append(tempGoTerm)
								tempGOData=gonamedetails+';'+goid+';'+tempGoTerm
								GOinfo.append(tempGOData)
							except:
								pass

						if (gItem.attributes['type'].value).strip() == 'NCBI Taxonomy':
							try:
								OGID=str(gItem.attributes['id'].value).strip()
							except:
								pass
				except IndexError:
					pass

				try:
					try:
						PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('recommendedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

					except:
						PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('submittedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

				except IndexError:
					pass

				try:
					try:
						GN=((SGunidata.getElementsByTagName('gene')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
					except:
						GN='NA'
				except IndexError:
					pass

				try:
					try:
						OG=((SGunidata.getElementsByTagName('organism')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
					except:
						OG='NA'
				except IndexError:
					pass

				try:
					disdata=SGunidata.getElementsByTagName('disease')
					for dItem in disdata:
						disname=''
						disshort=''
						disURL=''
						disID=''
						try:
							disname=(dItem.getElementsByTagName('name')[0]).firstChild.nodeValue
							disID=(dItem.attributes['id'].value).upper()
						except:
							pass
						try:
							disshort=(dItem.getElementsByTagName('acronym')[0]).firstChild.nodeValue
						except:
							pass
						if len(disname.strip())>0:
							disURL='<a target="_blank" href="https://www.uniprot.org/diseases/'+disID+'">'+str(disname.strip())+'('+str(disshort)+')'+'</a>'
							dislist.append(str(disname.strip())+'('+str(disshort)+')')
							unidislist.append(str(disname.strip())+'('+str(disshort)+')')
							unidisURLlist.append(disURL)
				except IndexError:
					pass

			except ExpatError:
				pass
		except IOError:
			pass
		drugbankdata='NA'
		disdata='NA'
		uniDisData='NA'
		uniDisURLData='NA'
		disgenDisData='NA'
		disgenDisURLData='NA'
		goiddata='NA'
		gonamedata='NA'
		gotermdata='NA'
		goData='NA'
		if GN != 'NA' and GN in disGenDataDic:
			disgendislist=disGenDataDic[GN][0]
			disgendisURLlist=disGenDataDic[GN][1]
			if len(dislist)>0:
				dislist=dislist+disGenDataDic[GN][0]
			else:
				dislist=disGenDataDic[GN][0]
			
		if len(GoIDList)>0:
			goiddata='|'.join(list(set(GoIDList)))
		if len(GoNamList)>0:
			gonamedata='|'.join(list(set(GoNamList)))
		if len(GoTermList)>0:
			gotermdata='|'.join(list(set(GoTermList)))
		if len(GOinfo)>0:
			goData='|'.join(list(set(GOinfo)))
		if len(drugbanklist)>0:
			drugbankdata='|'.join(list(set(drugbanklist)))
		if len(dislist)>0:
			disdata='|'.join(list(set(dislist)))
		if len(unidislist)>0:
			uniDisData='|'.join(list(set(unidislist)))
		if len(unidisURLlist)>0:
			uniDisURLData='|'.join(list(set(unidisURLlist)))
		if len(disgendislist)>0:
			disgenDisData='|'.join(list(set(disgendislist)))
		if len(disgendisURLlist)>0:
			disgenDisURLData='|'.join(list(set(disgendisURLlist)))
		humanUniprotfuncinfodic[subcode]=[PN,GN,OG,OGID,disdata,uniDisData,uniDisURLData,disgenDisData,disgenDisURLData,drugbankdata,goiddata,gonamedata,gotermdata,goData]
	hudicfile='humanUniprotfuncinfodic.obj'
	hudicf = open(hudicfile, 'wb')
	pickle.dump(humanUniprotfuncinfodic, hudicf , pickle.HIGHEST_PROTOCOL)
	hudicf.close()	

	print ("Extracting KEGG pathway name, job starts",str(datetime.datetime.now()))
	hkeggdictfile={}
	huniproturl = 'https://www.uniprot.org/uploadlists/'
	hk = KEGG()
	for hkx in range(0,len(unqhumanUniprotID),2000):
		countProt+=hkx+2000
		if countProt%2000 ==0:
			print (str(countProt), "th protein kegg job starts",str(datetime.datetime.now()))

		huniprotcodes=' '.join(unqhumanUniprotID[hkx:hkx+2000])
		huniprotparams = {
		'from':'ACC',
		'to':'KEGG_ID',
		'format':'tab',
		'query':huniprotcodes
		}
		
		while True:
			try:
				hkuniprotdata = urllib.urlencode(huniprotparams)
				hkuniprotrequest = urllib2.Request(huniproturl, hkuniprotdata)
				hkuniprotresponse = urllib2.urlopen(hkuniprotrequest)
				for hkuniprotline in hkuniprotresponse:
					hkudata=hkuniprotline.strip()
					if not hkudata.startswith("From"):
						hkuinfo=hkudata.split("\t")
						if len(hkuinfo[1].strip()):
							hkegg=hk.get(hkuinfo[1].strip())
							hkudict_data = hk.parse(hkegg)
							try:
								try:
									if len(str(hkuinfo[0]).strip()) >5:
										tempkeggData='|'.join('{};{}'.format(key, value) for key, value in hkudict_data['PATHWAY'].items())
										hkeggdictfile[hkuinfo[0].strip()]=[hkudict_data['PATHWAY'].values(),tempkeggData]
								except TypeError: 
									pass
							except KeyError:
								pass
				break
			except urllib2.HTTPError:
				time.sleep(RETRY_TIME)
				print ('Hey, I am trying again until succeeds to get data from KEGG!',str(datetime.datetime.now()))
				pass

	hkdicfile='humankeggdic.obj'
	hkdicf = open(hkdicfile, 'wb')
	pickle.dump(hkeggdictfile, hkdicf , pickle.HIGHEST_PROTOCOL)
	hkdicf.close()<file_sep>/backend/updatefile/preloadData.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
import datetime,glob
import time
import os,subprocess,psutil,re,sys,shutil,datetime
import csv
import datetime
import urllib,urllib2,urllib3
import json
import numpy as np
from statistics import mean
import ctypes

def preLoadJsonData(homedir,filepath):
	print ("Preload, job starts",str(datetime.datetime.now()))
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	calfilename='preloadHomeData.json'
	calmovefilepath=os.path.join(homedir, 'updatefile', calfilename)
	calfilepath = os.path.join(homedir, 'src/resultFile/jsonData/preLoadData', calfilename)
	prodataseries={}
	pepseqdataseries={}
	totalpeptideseq=''
	aacountlist=[]
	biomatCalDicPep={}
	biomatCalDicPro={}
	sexCalDicPep={}
	sexCalDicPro={}
	strainCalDicPep={}
	strainCalDicPro={}
	biopepList=[]
	bioproList=[]
	biomatList=[]
	sexpepList=[]
	sexproList=[]
	sexList=[]
	uniqueAssaysList=[]
	strainpepList=[]
	strainproList=[]
	strainList=[]
	meanStrainDic={}
	meanBioMatDic={}
	finalMeanConcDic={}
	finalmeanBioMatDic={}
	pepSeqPresenceHumanOrtholog=[]
	pepSeqPresenceHumanOrthologUniId=[]
	finalreader = csv.DictReader(open(filepath),delimiter='\t')
	for frow in finalreader:
		pepseq=frow['Peptide Sequence'].strip()
		acccode=None
		acccode=str(frow['UniProtKB Accession']).split('-')[0]
		genecode=str(frow['Gene']).strip()
		biomat=frow['Biological Matrix'].strip().split('|')
		sex=frow['Sex'].strip().split('|')
		strain=frow['Strain'].strip().split('|')
		sumconcdata=str(frow["Summary Concentration Range Data"]).strip().split(';')
		if acccode !=None and str(frow['UniprotKb entry status']).strip().upper()=='YES':
			totalpeptideseq +=pepseq.upper()

			if 'PeptideTracker' in prodataseries:
				prodataseries['PeptideTracker'].append(acccode)
			else:
				prodataseries['PeptideTracker']=[acccode]

			if 'PeptideTracker' in pepseqdataseries:
				pepseqdataseries['PeptideTracker'].append(pepseq.upper())
			else:
				pepseqdataseries['PeptideTracker']=[pepseq.upper()]


			for si in sumconcdata:
				meanConc=si.split('|')[6].split('(')[0].strip()
				if meanConc.upper() != 'NA':
					meanConc=float(meanConc)
					meanConclog10=round(np.log10(meanConc),2)
					strainConc=si.split('|')[3]
					matConc=si.split('|')[2]
					sexConc=si.split('|')[4]
					updatedAcccode='UniProtKB:'+acccode+'<br>Gene:'+genecode
					if meanStrainDic.has_key(strainConc):
						meanStrainDic[strainConc].append([meanConclog10,updatedAcccode,sexConc,matConc])
					else:
						meanStrainDic[strainConc]=[[meanConclog10,updatedAcccode,sexConc,matConc]]

					if meanBioMatDic.has_key(matConc):
						meanBioMatDic[matConc].append([meanConclog10,updatedAcccode])
					else:
						meanBioMatDic[matConc]=[[meanConclog10,updatedAcccode]]

			for bi in biomat:
				uniqueAssaysList.append(pepseq+bi)
				if bi  in biomatCalDicPep:
					biomatCalDicPep[bi].append(pepseq)
				else:
					biomatCalDicPep[bi]=[pepseq]

				if bi in biomatCalDicPro:
					biomatCalDicPro[bi].append(acccode)
				else:
					biomatCalDicPro[bi]=[acccode]

			for si in sex:
				if si in sexCalDicPep:
					sexCalDicPep[si].append(pepseq)
				else:
					sexCalDicPep[si]=[pepseq]

				if si in sexCalDicPro:
					sexCalDicPro[si].append(acccode)
				else:
					sexCalDicPro[si]=[acccode]

			for sti in strain:
				if sti in strainCalDicPep:
					strainCalDicPep[sti].append(pepseq)
				else:
					strainCalDicPep[sti]=[pepseq]

				if sti in strainCalDicPro:
					strainCalDicPro[sti].append(acccode)
				else:
					strainCalDicPro[sti]=[acccode]

			if str(frow['Present in human ortholog']) == 'Yes':
				pepSeqPresenceHumanOrtholog.append(pepseq.upper())
				pepSeqPresenceHumanOrthologUniId.append(frow['Human UniProtKB Accession'].strip().upper().split('-')[0])


	for mi in meanStrainDic:
		tempMeanjsonData=[]
		tempMeanMatdic={}
		for i in range(0,len(meanStrainDic[mi])):
			if meanStrainDic[mi][i][3] in tempMeanMatdic:
				tempMeanMatdic[meanStrainDic[mi][i][3]].append(meanStrainDic[mi][i][:3])
			else:
				tempMeanMatdic[meanStrainDic[mi][i][3]]=[meanStrainDic[mi][i][:3]]

		for tmati in tempMeanMatdic:
			tempMatJsonData={}
			tempMeanSexDic={}
			for j in range(0,len(tempMeanMatdic[tmati])):
				if tempMeanMatdic[tmati][j][2] in tempMeanSexDic:
					tempMeanSexDic[tempMeanMatdic[tmati][j][2]].append(tempMeanMatdic[tmati][j][:2])
				else:
					tempMeanSexDic[tempMeanMatdic[tmati][j][2]]=[tempMeanMatdic[tmati][j][:2]]
			for tsi in tempMeanSexDic:
				tempDic={}
				for z in range(0,len(tempMeanSexDic[tsi])):
					if tempMeanSexDic[tsi][z][1] in tempDic:
						tempDic[tempMeanSexDic[tsi][z][1]].append(tempMeanSexDic[tsi][z][0])
					else:
						tempDic[tempMeanSexDic[tsi][z][1]]=[tempMeanSexDic[tsi][z][0]]
				updatedConcData=[[mean(tempDic[k]),k] for k in tempDic]
				updatedConcData.sort(key=lambda x:x[0], reverse=True)
				tempMeanData='|'.join(map(str,list(zip(*updatedConcData)[0])))
				tempaccData='|'.join(list(zip(*updatedConcData)[1]))
				tempMatJsonData[tsi]={'MeanConcData':tempMeanData,'MeanProtein':tempaccData}
			tempMeanjsonData.append({tmati:tempMatJsonData})
		finalMeanConcDic[mi]=tempMeanjsonData



	for biomi in meanBioMatDic:
		tempDic={}
		for ai in meanBioMatDic[biomi]:
			if ai[1] in tempDic:
				tempDic[ai[1]].append(ai[0])
			else:
				tempDic[ai[1]]=[ai[0]]
		updatedConcData=[[round(mean(tempDic[k]),2),k] for k in tempDic]
		updatedConcData.sort(key=lambda x:x[0], reverse=True)
		tempMeanData='|'.join(map(str,list(zip(*updatedConcData)[0])))
		tempaccData='|'.join(list(zip(*updatedConcData)[1]))
		finalmeanBioMatDic[biomi]={'MeanConcData':tempMeanData,'MeanProtein':tempaccData}

		
	prodataseries['PeptideTracker']=list(set(prodataseries['PeptideTracker']))
	uniqueProtein=len(list(set(prodataseries['PeptideTracker'])))
	pepseqdataseries['PeptideTracker']=list(set(pepseqdataseries['PeptideTracker']))
	uniquePeptide=len(list(set(pepseqdataseries['PeptideTracker'])))
	uniqueAssays=len(list(set(uniqueAssaysList)))

	biomatList=biomatCalDicPro.keys()
	biomatList.sort()
	for bkey in biomatList:
		if bkey in biomatCalDicPep and bkey in biomatCalDicPro:
			bioproList.append(len(set(biomatCalDicPro[bkey])))
			biopepList.append(len(set(biomatCalDicPep[bkey])))


	for skey in sexCalDicPro:
		if skey in sexCalDicPep:
			sexList.append(skey)
			sexproList.append(len(set(sexCalDicPro[skey])))
			sexpepList.append(len(set(sexCalDicPep[skey])))


	strainList=strainCalDicPro.keys()
	strainList.sort()
	for stkey in strainList:
		if stkey in strainCalDicPep and stkey in strainCalDicPro:
			strainproList.append(len(set(strainCalDicPro[stkey])))
			strainpepList.append(len(set(strainCalDicPep[stkey])))

	strainDic={'Strain':'|'.join(strainList),'PeptideSeq':'|'.join(map(str,strainpepList)),'Protein':'|'.join(map(str,strainproList))}
	biomatDic={'BioMat':'|'.join(biomatList),'PeptideSeq':'|'.join(map(str,biopepList)),'Protein':'|'.join(map(str,bioproList))}
	sexDic={'Sex':'|'.join(sexList),'PeptideSeq':'|'.join(map(str,sexpepList)),'Protein':'|'.join(map(str,sexproList))}
	finalresultdic={}
	finalresultdic['uniqueAssays']=uniqueAssays
	finalresultdic['uniquePeptide']=uniquePeptide
	finalresultdic['uniqueProtein']=uniqueProtein
	finalresultdic['pepSeqPresenceHumanOrtholog']=len(set(pepSeqPresenceHumanOrtholog))
	finalresultdic['pepSeqPresenceHumanOrthologUniId']=len(set(pepSeqPresenceHumanOrthologUniId))
	finalresultlist=[]
	finalresultlist.append(finalresultdic)
	finalresultlist.append(biomatDic)
	finalresultlist.append(strainDic)
	finalresultlist.append(sexDic)
	finalresultlist.append(finalMeanConcDic)
	finalresultlist.append(finalmeanBioMatDic)

	finalresultJson={"data":finalresultlist}
	calfileoutput=open(calfilename,'w')
	calfileoutput.write(json.dumps(finalresultJson))
	calfileoutput.close()
	shutil.move(calmovefilepath,calfilepath)
	print ("Preload, job done",str(datetime.datetime.now()))<file_sep>/backend/src/qmpkbapp/appTissueInfo.py
# -*- coding: utf-8 -*-

listOfMatrix=['Plasma','Red blood cells','Brain','Skin','Testes','Eye','Heart','Liver Caudate and Right Lobe','Liver Left Lobe','Lung','Kidney','Ovary','Brown Adipose','White Adipose','Epididymis','Seminal Vesicles', 'Skeletal Muscle','Spleen','Pancreas','Salivary Gland']

unitDic={
	'Plasma':' (fmol target protein/ug extracted protein)',
	'RBCs':' (fmol target protein/ug extracted protein)',
	'Brain':' (fmol target protein/ug extracted protein)',
	'Skin':' (fmol target protein/ug extracted protein)',
	'Testes':' (fmol target protein/ug extracted protein)',
	'Eye':' (fmol target protein/ug extracted protein)',
	'Heart':' (fmol target protein/ug extracted protein)',
	'Liver Caudate and Right Lobe': ' (fmol target protein/ug extracted protein)',
	'Liver Left Lobe': ' (fmol target protein/ug extracted protein)',
	'Lung': ' (fmol target protein/ug extracted protein)',
	'Ovary': ' (fmol target protein/ug extracted protein)',
	'Kidney': ' (fmol target protein/ug extracted protein)',
	'Brown Adipose': ' (fmol target protein/ug extracted protein)',
	'White Adipose': ' (fmol target protein/ug extracted protein)',
	'Epididymis': ' (fmol target protein/ug extracted protein)',
	'Seminal Vesicles': ' (fmol target protein/ug extracted protein)',
	'Skeletal Muscle': ' (fmol target protein/ug extracted protein)',
	'Spleen': ' (fmol target protein/ug extracted protein)',
	'Pancreas': ' (fmol target protein/ug extracted protein)',
	'Salivary Gland': ' (fmol target protein/ug extracted protein)'
}<file_sep>/backend/src/qmpkbapp/colName.py
proteinInfoColname=['sel', 'UniProtKB Accession', 'Protein', 'Gene', 'Peptide Sequence', 'SubCellular','Strain',\
'Knockout','Biological Matrix','Sex','Concentration Range','Gene Expression View','Human UniProtKB Accession', \
'Human ProteinName', 'Human Gene', 'Mouse Kegg Pathway Name','Mouse Kegg Pathway','Human Kegg Pathway Name', \
'Human Kegg Pathway','Human Disease Name','Human UniProt DiseaseData','Human UniProt DiseaseData URL',\
'Human DisGen DiseaseData','Human DisGen DiseaseData URL',\
'Mouse Go ID','Mouse Go Name','Mouse Go Term','Mouse Go','Human Go ID','Human Go Name','Human Go Term','Human Go',\
'Human Drug Bank','Available assays in human ortholog']


downloadColName=['Mouse Protein name','Mouse Gene','Mouse UniProtKB accession','Peptide sequence',\
'Peptide present in isoforms','Peptide unique in proteome','Strain','Mutant','Human ortholog','Human Gene',\
'UniProtKB accession of human ortholog','Peptide present in human ortholog','Peptide unique in human protein',\
'Peptide present in human isoforms','Available assays in human ortholog','Subcellular localization',\
'Molecular pathway(s) Mouse','Molecular pathway(s) Human','Involvement in disease-Human(UniProt)','Involvement in disease-Human(DisGeNET)',\
'Go Mouse','Go Human','Drug associations-Human','Transitions','Retention Time','Analytical inofrmation',\
'Gradients','Molecular Weight','GRAVY Score','Summary Concentration Range Data',\
'All Concentration Range Data-Sample LLOQ Based','Panel','Assay LLOQ','Assay ULOQ','Sample LLOQ','Gene Expression Data']

downloadColNameUserSeq=['Mouse Protein name','Mouse Gene','Mouse UniProtKB accession','Peptide sequence',\
'Peptide present in isoforms','Peptide unique in proteome',"Peptide unique in user's database",\
"Peptide in user's database",'Strain','Mutant','Human ortholog','Human Gene','UniProtKB accession of human Ortholog',\
'Peptide present in human ortholog','Peptide unique in human protein','Peptide present in human isoforms',\
'Available assays in human ortholog','Subcellular localization','Molecular pathway(s) Mouse','Molecular pathway(s) Human',\
'Involvement in disease-Human(UniProt)','Involvement in disease-Human(DisGeNET)','Go Mouse','Go Human',\
'Drug associations-Human','Transitions','Retention Time','Analytical inofrmation','Gradients','Molecular Weight','GRAVY Score',\
'Summary Concentration Range Data','All Concentration Range Data-Sample LLOQ Based','Panel','Assay LLOQ',\
'Assay ULOQ','Sample LLOQ','Gene Expression Data']<file_sep>/backend/updatefile/generate_pre_downloadable_file.py
#!/usr/bin/env.python
# -*- coding: utf-8 -*-
# encoding: utf-8
from __future__ import unicode_literals
from django.utils.encoding import force_text
import os,subprocess,psutil,re,shutil,datetime,sys,glob
import errno
import csv
import json
import pandas as pd
import numpy as np
from statistics import mean
import ctypes
from elasticsearch import Elasticsearch,helpers,RequestsHttpConnection
from modJsonData import pepbasedInfo
from prePareDownloadFile import updateDataToDownload
def preDownloadFile():
	proteinInfoColname=['sel', 'UniProtKB Accession', 'Protein', 'Gene', 'Peptide Sequence', 'SubCellular','Strain',\
	'Knockout','Biological Matrix','Sex','Concentration Range','Gene Expression View','Human UniProtKB Accession', \
	'Human ProteinName', 'Human Gene', 'Mouse Kegg Pathway Name','Mouse Kegg Pathway','Human Kegg Pathway Name', \
	'Human Kegg Pathway','Human Disease Name','Human UniProt DiseaseData','Human UniProt DiseaseData URL','Human DisGen DiseaseData','Human DisGen DiseaseData URL',\
	'Mouse Go ID','Mouse Go Name','Mouse Go Term','Mouse Go','Human Go ID','Human Go Name','Human Go Term','Human Go',\
	'Human Drug Bank','Available assays in human ortholog']

	downloadColName=['Mouse Protein Name','Mouse Gene','Mouse UniProtKB Accession','Peptide Sequence',\
	'Peptide present in isoforms','Peptide unique in proteome','Strain','Knockout','Human Ortholog','Human Gene',\
	'UniProtKB Accession of Human Ortholog','Peptide present in human ortholog','Peptide unique in human protein',\
	'Peptide present in human isoforms','Available assays in human ortholog','Subcellular localization',\
	'Pathway(s) Mouse','Pathway(s) Human','Involvement in disease-Human(UniProt)','Involvement in disease-Human(DisGeNET)',\
	'Go Mouse','Go Human','Drug Bank-Human','Transitions','Retention Time','Analytical inofrmation',\
	'Gradients','Molecular Weight','GRAVY Score','Summary Concentration Range Data',\
	'All Concentration Range Data-Sample LLOQ Based','Panel','Assay LLOQ','Assay ULOQ','Sample LLOQ','Gene Expression Data']
	es = Elasticsearch(
		['http://xxxxx:9200/'],
		connection_class=RequestsHttpConnection
	)
	homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
	es.indices.refresh(index="xxxxx-index")
	query={"query": {
		"bool": {
			"must": [
				{"match": {"Organism ID": "10090"}}
			]
		}
	}
	}
	jsonfilename_proteincentric='all_data_proteincentric.json'
	downloadFilename='Results_all.csv'
	jsonfilepath_proteincentric=os.path.join(homedir, 'src/resultFile/preDownloadFile/json', jsonfilename_proteincentric)
	downloadResultFilePath=os.path.join(homedir, 'src/resultFile/preDownloadFile/csv',  downloadFilename)
	jsonfileoutput_proteincentric= open(jsonfilepath_proteincentric,'w')


	res=helpers.scan(client=es,scroll='2m',index="xxxxx-index", doc_type="xxxxx-type",query=query,request_timeout=30)
	jfinaldata=[]
	uniprotpepinfo={}
	for i in res:
		jdic=i['_source']
		jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
		if jdic["UniprotKb entry status"] =="Yes":
			if uniprotpepinfo.has_key(jdic["UniProtKB Accession"]):
				uniprotpepinfo[jdic["UniProtKB Accession"]].append(jdic["Peptide Sequence"])
			else:
				uniprotpepinfo[jdic["UniProtKB Accession"]]=[jdic["Peptide Sequence"]]
			#if jdic["Retention Time"].lower() =='na' or jdic["Gradients"].lower() =='na':
			if jdic["Retention Time"].lower() =='na':
				jdic["Summary Concentration Range Data"]='NA'
				jdic["Concentration View"]='NA'

			if jdic["Human UniProtKB Accession"].lower() !='na' and jdic["Present in human ortholog"].lower() =='no':
				jdic["Available assays in human ortholog"]='http://mrmassaydb.proteincentre.com/search/hyperlink/?UniProtKB Accession='+jdic["Human UniProtKB Accession"]
			else:
				jdic["Available assays in human ortholog"]='NA'

			if len(str(jdic["Summary Concentration Range Data"]).strip()) >0 and str(jdic["Summary Concentration Range Data"]).strip().upper() !="NA":
				try:
					jdic["Biological Matrix"]=jdic["Biological Matrix"].replace('|','<br/>')
				except KeyError:
					pass
			jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
			jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/u','µg protein/µ')
			jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

			jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
			jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/u','µg protein/µ')
			jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

			jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('fmol target protein/u','fmol target protein/µ')
			jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/u','µg protein/µ')
			jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/mg','µg protein/mg')

			jdic["Concentration View"]=jdic["Concentration View"].replace('fmol target protein/u','fmol target protein/µ')
			jdic["Concentration Range"]=jdic["Concentration Range"].replace('fmol target protein/u','fmol target protein/µ')

			jdic["LLOQ"]=jdic["LLOQ"].replace('fmol target protein/u','fmol target protein/µ')
			jdic["ULOQ"]=jdic["ULOQ"].replace('fmol target protein/u','fmol target protein/µ')
			jdic["Sample LLOQ"]=jdic["Sample LLOQ"].replace('fmol target protein/u','fmol target protein/µ')

			if jdic["Unique in protein"].upper() =='NA':
				jdic["Unique in protein"]=jdic["Unique in protein"].replace('NA','No')
			if jdic["Present in isoforms"].upper() =='NA':
				jdic["Present in isoforms"]=jdic["Present in isoforms"].replace('NA','No')

			
			jfinaldata.append(jdic)

	es.indices.refresh(index="xxxxx-index")
	finalupdatedUniInfo=pepbasedInfo(jfinaldata,uniprotpepinfo,proteinInfoColname)
	json.dump(finalupdatedUniInfo,jsonfileoutput_proteincentric)
	jsonfileoutput_proteincentric.close()

	jfinaldata=updateDataToDownload(jfinaldata)
	df=pd.read_json(json.dumps(jfinaldata))
	df.rename(columns ={'UniProtKB Accession':'Mouse UniProtKB Accession','Protein':'Mouse Protein Name',\
		'Gene':'Mouse Gene','Present in isoforms':'Peptide present in isoforms',\
		'Unique in protein':'Peptide unique in proteome','Human UniProtKB Accession': \
		'UniProtKB Accession of Human ortholog','Human ProteinName': 'Human ortholog',\
		'Peptide ID':'Assay ID','Present in human isoforms':'Peptide present in human isoforms',\
		'Unique in human protein':'Peptide unique in human protein',\
		'SubCellular':'Subcellular localization','Mouse Kegg Pathway':'Pathway(s) Mouse',\
		'Present in human ortholog':'Peptide present in human ortholog',\
		'Human Kegg Pathway':'Pathway(s) Human','Human UniProt DiseaseData':'Involvement in disease-Human(UniProt)',\
		'Human DisGen DiseaseData':'Involvement in disease-Human(DisGeNET)','Human Drug Bank':\
		'Drug Bank-Human','CZE Purity':'CZE','AAA Concentration':'AAA',\
		'Mouse Go':'Go Mouse','Human Go':'Go Human','LLOQ':'Assay LLOQ','ULOQ':'Assay ULOQ'}, inplace =True)
	df.to_csv(downloadResultFilePath,index=False, encoding='utf-8', columns=downloadColName)
<file_sep>/client/qmpkb-app/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule }    from '@angular/common/http';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';

// third party imports
import { Ng2OdometerModule } from 'ng2-odometer';
import { DataTablesModule } from 'angular-datatables';
import { NgxSpinnerModule } from 'ngx-spinner';
import { NgMultiSelectDropDownModule } from 'ng-multiselect-dropdown';
import { CollapseModule } from 'ngx-bootstrap/collapse';
import * as $ from "jquery";
//service
import {DropdownService} from './dropdown-service/dropdown.service';
import {QmpkbService} from './qmpkb-service/qmpkb.service';

import { AppRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HelpComponent } from './help/help.component';
import { ContactComponent } from './contact/contact.component';
import { BasicSearchComponent } from './basic-search/basic-search.component';
import { BasicSearchWithoutExampleComponent } from './basic-search-without-example/basic-search-without-example.component';
import { BasicSearchWithoutExampleResultComponent } from './basic-search-without-example-result/basic-search-without-example-result.component';
import { AdvanceSearchComponent } from './advance-search/advance-search.component';
import { ProtvistaViewComponent } from './protvista-view/protvista-view.component';
import { ResultPageComponent } from './result-page/result-page.component';
import { ResultPageUserSeqComponent } from './result-page-user-seq/result-page-user-seq.component';
import { AssayComponent } from './assay/assay.component';
import { ConcentrationComponent } from './concentration/concentration.component';
import { PathwayComponent } from './pathway/pathway.component';
import { PathwayviewComponent } from './pathwayview/pathwayview.component';
import { GotermComponent } from './goterm/goterm.component';
import { PeptideuniquenessComponent } from './peptideuniqueness/peptideuniqueness.component';
import { MouseAnatomyComponent } from './mouse-anatomy/mouse-anatomy.component';
import { DataLoadPageComponent } from './data-load-page/data-load-page.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { GeneExpressionComponent } from './gene-expression/gene-expression.component';
import { FoldChangeComponent } from './fold-change/fold-change.component';
import { DetailInformationComponent } from './detail-information/detail-information.component';
import { DetailConcentrationComponent } from './detail-concentration/detail-concentration.component';
import { DiseaseInformationComponent } from './disease-information/disease-information.component';
import { DrugBankComponent } from './drug-bank/drug-bank.component';
import { SubcellLocationComponent } from './subcell-location/subcell-location.component';
import { ResultsQueryComponent } from './results-query/results-query.component';
import { ProtocolComponent } from './protocol/protocol.component';
import { HumanProttVistaViewComponent } from './human-prott-vista-view/human-prott-vista-view.component';
import { Navbar1Component } from './navbar1/navbar1.component';
import { Navbar2Component } from './navbar2/navbar2.component';
import { Navbar3Component } from './navbar3/navbar3.component';
import { DataSubmissionFormComponent } from './data-submission-form/data-submission-form.component';
import { DownloadResultComponent } from './download-result/download-result.component';



@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    HelpComponent,
    ContactComponent,
    BasicSearchComponent,
    BasicSearchWithoutExampleComponent,
    BasicSearchWithoutExampleResultComponent,
    ProtvistaViewComponent,
    ResultPageComponent,
    ResultPageUserSeqComponent,
    AdvanceSearchComponent,
    AssayComponent,
    ConcentrationComponent,
    PathwayComponent,
    PathwayviewComponent,
    GotermComponent,
    PeptideuniquenessComponent,
    MouseAnatomyComponent,
    DataLoadPageComponent,
    NotFoundComponent,
    GeneExpressionComponent,
    FoldChangeComponent,
    DetailInformationComponent,
    DetailConcentrationComponent,
    DiseaseInformationComponent,
    DrugBankComponent,
    SubcellLocationComponent,
    ResultsQueryComponent,
    ProtocolComponent,
    HumanProttVistaViewComponent,
    Navbar1Component,
    Navbar2Component,
    Navbar3Component,
    DataSubmissionFormComponent,
    DownloadResultComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    Ng2OdometerModule.forRoot(),
    NgMultiSelectDropDownModule.forRoot(),
    DataTablesModule,
    NgxSpinnerModule,
    CollapseModule.forRoot()
  ],
  providers: [
  DropdownService,
  QmpkbService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/backend/src/qmpkbapp/admin.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin

# Register your models here.
from .models import IpAddressInformation
class IpAddressInformationAdmin(admin.ModelAdmin):
	"""docstring for ClassName"""
	list_display=["__unicode__","access_date"]
	class Meta:
		model=IpAddressInformation

admin.site.register(IpAddressInformation,IpAddressInformationAdmin)<file_sep>/client/qmpkb-app/src/app/assay/assay.component.ts
import { Component, OnInit, OnDestroy,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-assay',
  templateUrl: './assay.component.html',
  styleUrls: ['./assay.component.css']
})
export class AssayComponent implements OnInit {
  dtOptionsSummary: any = {};
  dtOptionsGrad: any = {};
  dtOptionsTrans:any ={};
  dtOptionsLOQ:any ={};
  errorStr:Boolean;
  transdic: any;
  transdiclen: number;
  gradientlist:any;
  gradientlistlen:number;
  gradinfoheader:any;
  loquantinfo:any;
  foundHits:number;
  protinfo:any
  queryData:any;
  assayInputData:any;
  assayDataStatus=false;
  userFastaStatus:number;
  fastafilename:any;
  assayuniProtKb:any;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { }

  @Input()
  set assaytermQuery(assayQuery:any){
      this.assayInputData=assayQuery;

  }

  ngOnInit() {
      let assayQueryArray=this.assayInputData.split('|');
      this._qmpkb.receiveDataFromBackendSearch('/assaydetailsapi/?resultFilePath=' + assayQueryArray[1]+'&uniProtKb='+ assayQueryArray[0]+'&fastafilename='+assayQueryArray[2]).subscribe((response: any)=>{
        this.queryData=response;
        this.transdic=this.queryData.transdic;
        this.gradientlist=this.queryData.gradientlist;
        this.gradinfoheader=this.queryData.gradinfoheader;
        this.loquantinfo=this.queryData.loquantinfo;
        this.foundHits=this.queryData.foundHits;
        this.userFastaStatus=this.queryData.userFastaStatus;
        this.protinfo=this.queryData.protinfo;
        this.fastafilename=this.queryData.fastafilename;
        this.transdiclen=Object.keys(this.transdic).length;
        this.gradientlistlen=Object.keys(this.gradientlist).length;
        this.assayuniProtKb=assayQueryArray[0];
        this.assayDataStatus=true;
        this.dtOptionsSummary = {
          orderCellsTop: true,
          fixedHeader: true,
          pageLength: 10,
          pagingType: 'full_numbers',
          scrollX:true,
          scrollY:'650px',
          scrollCollapse:true,
          autoWidth:true,
          dom: 'lBfrtip',
          buttons: [
              {
                extend:'csv',
                filename: 'PeptideInformationMouseQuaPro',
                text:'Download all(CSV)'
              },
              {
                extend:'excel',
                filename: 'PeptideInformationMouseQuaPro',
                text:'Download all(Excel)'
              }
          ]

        };
        this.dtOptionsGrad = {
          orderCellsTop: true,
          fixedHeader: true,
          pageLength: 10,
          pagingType: 'full_numbers',
          scrollX:true,
          scrollY:'650px',
          scrollCollapse:true,
          autoWidth:true,
          dom: 'lBfrtip',
          buttons: [
              {
                extend:'csv',
                filename: 'GradientsMouseQuaPro',
                text:'Download all(CSV)'
              },
              {
                extend:'excel',
                filename: 'GradientsMouseQuaPro',
                text:'Download all(Excel)'
              }
          ],
/*          columnDefs:[{
            type: 'na',
            targets: 3
          }]*/

        };
        this.dtOptionsLOQ = {
          orderCellsTop: true,
          fixedHeader: true,
          pageLength: 10,
          pagingType: 'full_numbers',
          scrollX:true,
          scrollY:'650px',
          scrollCollapse:true,
          autoWidth:true,
          dom: 'lBfrtip',
          buttons: [
              {
                extend:'csv',
                filename: 'LimitofquantificationMouseQuaPro',
                text:'Download all(CSV)'
              },
              {
                extend:'excel',
                filename: 'LimitofquantificationMouseQuaPro',
                text:'Download all(Excel)'
              }
          ]

        };
        this.dtOptionsTrans = {
          orderCellsTop: true,
          fixedHeader: true,
          pageLength: 10,
          pagingType: 'full_numbers',
          scrollX:true,
          scrollY:'650px',
          scrollCollapse:true,
          autoWidth:true,
          dom: 'lBfrtip',
          buttons: [
              {
                extend:'csv',
                filename: 'TransitionMouseQuaPro',
                text:'Download all(CSV)'
              },
              {
                extend:'excel',
                filename: 'TransitionMouseQuaPro',
                text:'Download all(Excel)'
              }
          ]

        };

      }, error=>{
        this.errorStr = error;
      })

  }

  private openTabsAssay(evt, tabName) {
      var i, tabcontent, tablinks;
      tabcontent = document.getElementsByClassName("tabcontentassay");
      for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
      }
      tablinks = document.getElementsByClassName("tablinksassay");
      for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
      }
      document.getElementById(tabName).style.display = "block";
      evt.currentTarget.className += " active";
  }
}
<file_sep>/client/qmpkb-app/src/app/goterm/goterm.component.ts
import { Component, OnInit, OnDestroy,Input,ViewChildren, QueryList, ElementRef} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { Subject } from 'rxjs';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";
declare var jquery: any;

@Component({
  selector: 'app-goterm',
  templateUrl: './goterm.component.html',
  styleUrls: ['./goterm.component.css']
})
export class GotermComponent implements OnInit {

  dtOptions: any = {};
  errorStr:Boolean;
  foundHits:number;
  contextgoterminfo:any
  contextgoterminfolen:number;
  goStat:any;
  queryGoUniProtKB:any;
  goDataStatus=false;
  queryData:any;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { }

  @Input()
  set gotermQuery(goUniProtKB:any){
      this.queryGoUniProtKB=goUniProtKB;

  }
  ngOnInit() {
  }

  ngAfterViewInit(): void {
    this._qmpkb.receiveDataFromBackendSearch('/gotermapi/?uniProtKb='+ this.queryGoUniProtKB).subscribe((response: any)=>{
      this.goDataStatus=true;
      this.queryData=response;
      this.foundHits=this.queryData.foundHits;
      this.contextgoterminfo=this.queryData.contextgoterminfo;
      this.contextgoterminfolen=Object.keys(this.contextgoterminfo).length;
      this.goStat=this.queryData.goStat;
      this.dtOptions = {
        processing: true,
        serverSide: false,
        orderCellsTop: true,
        fixedHeader: true,
        pageLength: 10,
        pagingType: 'full_numbers',
        scrollX:true,
        scrollY:'650px',
        scrollCollapse:true,
        // Declare the use of the extension in the dom parameter
        dom: 'lBfrtip',
        buttons: [
            {
              extend:'csv',
              filename: 'GeneOntologyMouseQuaPro',
              text:'Download all(CSV)'
            },
            {
              extend:'excel',
              filename: 'GeneOntologyMouseQuaPro',
              text:'Download all(Excel)'
            }
        ],
        autoWidth:true  
       };
    }, error=>{
      this.errorStr = error;
    })

  }
}
<file_sep>/client/qmpkb-app/src/app/advance-search/advance-search.component.ts
import { Component, OnInit, Input, ElementRef, ViewChild, NgModule, Renderer, HostListener } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray } from '@angular/forms';
import {DropdownService} from '../dropdown-service/dropdown.service';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import {saveAs} from 'file-saver';


@Component({
  selector: 'app-advance-search',
  templateUrl: './advance-search.component.html',
  styleUrls: ['./advance-search.component.css']
})
export class AdvanceSearchComponent implements OnInit {
	selects: any[];
	@Input()
	wheres;
	formIndex:number = 1;
	fastaFileContext:any;
	fastaFileName:any;
	savedfastaFileName:any;
	parts = {};
	errorStr:Boolean;
	dropdownSettings = {};
	dropdownList = [];
	selectedItems = [];
	public alertIsVisible:boolean= false;
	

  fields ={
	protein: 'Protein',
	gene: 'Gene',
	uniProtKBAccession:'UniProtKB accession',
	pepSeq:'Peptide sequence',
	panel:'Panel',
	strain:'Strain',
	mutant : 'Mutant',
	sex:'Sex',
	biologicalMatrix : 'Biological matrix',
	subCellLoc:'Subcellular localization',
	keggPathway:'Molecular pathway(s)',
	disCausMut:'Involvement in disease',
	goId:'GO ID',
	goTerm:'GO term',
	goAspects:'GO aspects',
	drugId:'Drug associations ID',
	fastaFile: 'Own protein sequences in FASTA format'

  };

	public queryForm: FormGroup;
	@ViewChild('fileInput') fileInput: ElementRef;
	

	ngOnInit(){}

	public addOptionGroup(){
		const fa = this.queryForm.controls["optionGroups"] as FormArray;
		fa.push(this.newOptionGroup());
		this.formIndex ++;
	}

	public removeOptionGroup(index: number){
		const fa = this.queryForm.controls["optionGroups"] as FormArray;
		fa.removeAt(index);
		this.formIndex --;
	}


	public savequeryForm() {
		this.spinner.show();
		let advancedFormData={};
		for(let i=0; i<Object.keys(this.queryForm.value.optionGroups).length;i++){
			const temQParm=this.queryForm.value.optionGroups[i].selectInput;
			const temQVal=this.queryForm.value.optionGroups[i].whereInput;
			if (temQParm=='panel' || temQParm=='strain' ||temQParm=='mutant' || temQParm=='sex' || temQParm=='biologicalMatrix'){
				advancedFormData[temQParm]=temQVal.join('|');
			} else{
				if (temQParm !=='fastaFile'){
					advancedFormData[temQParm]=temQVal;
				}
			}
		}
		advancedFormData['fastaFileName']=this.savedfastaFileName;
	    this.router.navigate(['/results'],{queryParams:advancedFormData});
	  	this.queryForm.reset();


	}

	openFile(event:any, selectInput: string , formIndex : number) {
		if (event.target.files && event.target.files[0]) {
			let fileReader = new FileReader();
			fileReader.onload = (e) => {
				// this 'text' is the content of the file
				this.fastaFileContext = fileReader.result;
				this.fastaFileName = event.target.files[0].name;
				if (this.fastaFileName.length >0){
					this._qmpkb.receiveDataFromBackendSearch('/fastafileapi/?fastaFileContext=' + JSON.stringify(this.fastaFileContext)).subscribe((response: any)=>{
						this.savedfastaFileName=response.nameFile;
					}, error=>{
					this.errorStr = error;
					})					
				}

			}
			fileReader.readAsText(event.target.files[0]);
		};
	}

	constructor(
		private router: Router, 
		public dropdownservice: DropdownService , 
		private fb : FormBuilder,
		private _qmpkb:QmpkbService,
		private spinner: NgxSpinnerService,
		private http: HttpClient
		) {
		this.queryForm = this.fb.group({
				optionGroups : this.fb.array([
					this.fb.group({
						selectInput : ['', Validators.required],
						whereInput : ['', Validators.required],
						}),
				]),
		});
		this.selects = this.dropdownservice.getSelect();
		this.wheres=[];
	}



	private newOptionGroup() {
		return new FormGroup({
				selectInput: new FormControl(""),
				whereInput: new FormControl(""),
		});
	}

	onSelectSelect(selectInput: string , formIndex : number) : void{

		this.dropdownSettings = {
		  singleSelection: false,
		  idField: 'id',
		  textField: 'name',
		  enableCheckAll:false,
		  allowSearchFilter: true
		};
		this.wheres[selectInput] = this.dropdownservice.getWhere().filter((item)=> item.selectid == selectInput);
		this.parts[formIndex]=selectInput;
		let keys = Object.keys(this.parts);
		let values = keys.map(k => this.parts[k]);
		this.dropdownList =	this.wheres[selectInput];
		if (values.length > 1){
			let countDuplicate=0;
			for(let v of values){
				if (selectInput == v){
					countDuplicate++;
				}
				if (countDuplicate > 1){
					alert(this.fields[selectInput]+' already selected.');
					this.queryForm.get('optionGroups')['controls'][formIndex].patchValue({ selectInput: '', whereInput: ''});
					countDuplicate=0;
				} else {
					this.queryForm.get('optionGroups')['controls'][formIndex].patchValue({ selectInput: selectInput, whereInput: ''});
				}
		}
		}
		
	}
/*	log(event) {
		console.log(event);
	}
*/
}<file_sep>/backend/requirements.txt
adium-theme-ubuntu==0.3.4
appdirs==1.4.0
beautifulsoup4==4.5.3
biopython==1.68
bioservices==1.4.14
certifi==2018.10.15
chardet==3.0.4
click==6.7
click-conf==0.0.1
click-stream==0.0.6
colorama==0.3.7
coreapi==2.3.3
coreschema==0.0.4
coverage==5.0.3
demjson==2.2.4
diff-match-patch==20121119
dj-static==0.0.6
Django==1.11.16
django-crispy-forms==1.6.1
django-filter==1.0.1
django-import-export==0.5.1
django-ipware==1.1.6
django-rest-swagger==2.2.0
djangorestframework==3.9.1
docutils==0.14
easydev==0.9.30
elasticsearch==6.1.1
elasticsearch-loader==0.2.24
future==0.18.2
gevent==1.2.0
goatools==0.7.9
greenlet==0.4.11
grequests==0.3.0
gunicorn==19.10.0
idna==2.7
itypes==1.1.0
Jinja2==2.10
Markdown==2.6.6
MarkupSafe==1.1.0
more-itertools==4.3.0
names==0.3.0
nose==1.3.7
numpy==1.11.3
openapi-codec==1.3.2
pandas==0.20.3
patsy==0.4.1
pexpect==4.2.1
psutil==5.4.5
ptyprocess==0.5.1
pyaml==18.11.0
pycrypto==2.6.1
pygobject==3.20.0
pymssql==2.1.4
python-dateutil==2.6.1
pytz==2018.7
PyYAML==3.13
requests==2.20.1
requests-cache==0.4.13
rpy2==2.7.8
schedule==0.5.0
scipy==0.19.1
scour==0.32
selenium==3.0.1
sh==1.13.1
simplejson==3.16.0
singledispatch==3.4.0.3
six==1.11.0
static3==0.7.0
statistics==1.0.3.5
statsmodels==0.8.0
suds-jurko==0.6
tablib==0.11.2
unicodecsv==0.14.1
unity-lens-photos==1.0
uritemplate==3.0.0
urllib3==1.22
virtualenv==16.0.0
wget==3.2
wrapt==1.10.8
xlrd==1.1.0
XlsxWriter==1.0.0
xmltodict==0.10.2
<file_sep>/client/qmpkb-app/src/app/concentration/concentration.component.ts
import { Component, OnInit, OnDestroy, ViewChild, Renderer, HostListener} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as Plotly from 'plotly.js';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-concentration',
  templateUrl: './concentration.component.html',
  styleUrls: ['./concentration.component.css']
})
export class ConcentrationComponent implements OnInit {
  dtOptions: any = {};
  errorStr:Boolean;
  conclist:any;
  conclistlen:number;
  foundHits:number;
  sampleConcUnit:string;
  protList:any
  queryData:any;
  plotlyData:any=[];
  lenOfConcData:any;
  screenWidth:any;
  finalPlotData:any={};
  wildObj={
    'Wild type':'WT'
  };
  sexObj={
    'Male':'M',
    'Female':'F'
  };
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;

  plotDataOptions=[
       {num:0, name:'Concentration Data'},
       {num:1, name:'Log2(Concentration Data)'},
       {num:2, name:'Log10(Concentration Data)'},
  ];
/*  this.selectedLevel=this.plotDataOptions[0];*/
   selected=this.plotDataOptions[2];

  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=(window.innerWidth-50)+"px";
  }

  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService,
    private renderer: Renderer,
    ) { 
      this.getScreenSize();
  }

  ngOnInit() {
    this.spinner.show();

    this.queryData=this._qmpkb.queryStorage;
    this.conclist=this.queryData.conclist;
    this.conclistlen=Object.keys(this.conclist).length
    this.foundHits=this.queryData.foundHits;
    this.protList=this.queryData.protList;
    this.sampleConcUnit=this.queryData.concUnit;
    this.lenOfConcData= this.queryData.lenOfConcData;
    jQuery.extend( jQuery.fn.dataTable.ext.oSort, {
        "na-asc": function (str1, str2) {
            if(str1 == "NA")
                return 1;
            else if(str2 == "NA")
                return -1;
            else{
               var fstr1 = parseFloat(str1);
               var fstr2 = parseFloat(str2);
               return ((fstr1 < str2) ? -1 : ((fstr1 > fstr2) ? 1 : 0));
            }
           
        },
     
        "na-desc": function (str1, str2) {
            if(str1 == "NA")
                return 1;
            else if(str2 == "NA")
                return -1;
            else {
              var fstr1 = parseFloat(str1);
              var fstr2 = parseFloat(str2);
              return ((fstr1 < fstr2) ? 1 : ((fstr1 > fstr2) ? -1 : 0));
            }
            
        }
    } );
    this.dtOptions = {
      processing: true,
      serverSide: false,
      orderCellsTop: true,
      fixedHeader: true,
      pageLength: 10,
      pagingType: 'full_numbers',
      scrollX:true,
      scrollY:'650px',
      scrollCollapse:true,
      columnDefs:[
        {
          targets: 0,
          data: null,
          defaultContent: '',
          orderable: false,
          className: 'select-checkbox',
          searchable:false
        },
        {
          targets: 1,
          searchable:false,
          visible:false
        },
        {
          targets: 2,
          searchable:false,
          visible:false
        },
        {
          targets: 3,
          searchable:false,
          visible:false
        },
        {
          targets: 13,
          searchable:false,
          visible:false
        },
        {
          targets: 14,
          searchable:false,
          visible:false
        },
        {
          targets: 15,
          searchable:false,
          visible:false
        },        
        {
          targets: 16,
          searchable:false,
          visible:false
        },
        {
          targets: 17,
          searchable:false,
          visible:false
        },
        {type: 'na', targets: [8,9,10,11]} // define 'name' column as na type
      ],
      select:{
        style:'multi'
      },
      // Declare the use of the extension in the dom parameter
      dom: 'lBfrtip',
      buttons: [
          {
            extend:'csv',
            filename: 'ConcentrationMouseQuaPro',
            text:'Download all(CSV)',
            exportOptions:{
              columns:[1,2,3,4,5,6,7,8,9,10,11,12,15,16,17]
            }
          },
          {
            extend:'excel',
            filename: 'ConcentrationMouseQuaPro',
            text:'Download all(Excel)',
            exportOptions:{
              columns:[1,2,3,4,5,6,7,8,9,10,11,12,15,16,17]
            }
          },
          'selectAll',
          'selectNone'
      ],
      order: [],
      autoWidth:true
    };
    this.spinner.hide();
  }


  ngAfterViewInit(): void {      
    const self = this;
    self.datatableElement.dtInstance.then((dtInstance:any) => {
      
      dtInstance.rows(function(idx,data){
        const plotName=data[13].split('|');
        //plotName[0]=self.wildObj[plotName[0]];
        plotName[2]=self.sexObj[plotName[2]];
        const plotData=data[14];
        const plotDataSampleLLOQ=data[15];
        const sampleLLOQ=data[16];
        const ULOQ=data[17];
        const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
        self.plotlyData.push(tempPlotArray.join(';'));
        return idx >=0;
      }).select();
      self.prepareDatatoPlot(self.plotlyData);
    });
     self.datatableElement.dtInstance.then(table => {
      $('#dataTables-wrkld-concentration').on('select.dt', function (e,dt,type,indexes) {
        if (self.lenOfConcData == indexes.length){
           self.plotlyData=[];
           for(let j=0; j< indexes.length;j++){
              const plotName=dt.row(indexes[j]).data()[13].split('|');
              //plotName[0]=self.wildObj[plotName[0]];
              plotName[2]=self.sexObj[plotName[2]];
              const plotData=dt.row(indexes[j]).data()[14];
              const plotDataSampleLLOQ=dt.row(indexes[j]).data()[15];
              const sampleLLOQ=dt.row(indexes[j]).data()[16];
              const ULOQ=dt.row(indexes[j]).data()[17];
              const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
              self.plotlyData.push(tempPlotArray.join(';'));
              self.selected=self.plotDataOptions[0];
           }
           self.prepareDatatoPlot(self.plotlyData);

        } else {
          const plotName=dt.row(indexes[0]).data()[13].split('|');
          //plotName[0]=self.wildObj[plotName[0]];
          plotName[2]=self.sexObj[plotName[2]];
          const plotData=dt.row(indexes[0]).data()[14];
          const plotDataSampleLLOQ=dt.row(indexes[0]).data()[15];
          const sampleLLOQ=dt.row(indexes[0]).data()[16];
          const ULOQ=dt.row(indexes[0]).data()[17];
          const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
          self.plotlyData.push(tempPlotArray.join(';'));
          self.prepareDatatoPlot(self.plotlyData); 
          self.selected=self.plotDataOptions[0];       
        }

        
      });
      $('#dataTables-wrkld-concentration').on('deselect.dt', function (e,dt,type,indexes) {
        if (self.lenOfConcData == indexes.length || indexes.length>1 || self.plotlyData == indexes.length){
            self.plotlyData=[];
            self.prepareDatatoPlot(self.plotlyData);
        } else {
          const plotName=dt.row(indexes[0]).data()[13].split('|');
          //plotName[0]=self.wildObj[plotName[0]];
          plotName[2]=self.sexObj[plotName[2]];
          const plotData=dt.row(indexes[0]).data()[14];
          const plotDataSampleLLOQ=dt.row(indexes[0]).data()[15];
          const sampleLLOQ=dt.row(indexes[0]).data()[16];
          const ULOQ=dt.row(indexes[0]).data()[17];
          const tempPlotArray=[plotName.join('|'),plotData,plotDataSampleLLOQ,sampleLLOQ,ULOQ];
          const indexOfplotlyData=self.plotlyData.indexOf(tempPlotArray.join(';'));
          self.plotlyData.splice(indexOfplotlyData,1);
          self.prepareDatatoPlot(self.plotlyData);
          self.selected=self.plotDataOptions[0];        
        }

      });
    });

  }


    prepareDatatoPlot(rawData:any) {
      const tissueColor= {
        "Brain":"cyan",
        "Brown Adipose":"olive",
        "Epididymis":"slategray",
        "Eye":"rosybrown", 
        "Heart":"darksalmon",
        "Kidney":"lightcoral",
        "Liver Caudate and Right Lobe":"sandybrown",
        "Liver Left Lobe":"deepskyblue",
        "Lung":"tan",
        "Pancreas":"cadetblue",
        "Plasma":"greenyellow",
        "Ovary":"goldenrod",
        "RBCs":"seagreen",
        "Salivary Gland":"chocolate",
        "Seminal Vesicles":"khaki",
        "Skeletal Muscle":"indigo",
        "Skin":"thistle",
        "Spleen":"violet",
        "Testes":"lightpink",
        "White Adipose":"plum"
      };

      let prepareDatatoPlotDataArray=[];
      let prepareDatatoPlotDataArrayLog2=[];
      let prepareDatatoPlotDataArrayLog10=[];
      const yAxisTile='Concentration<br>(fmol target protein/µg extracted protein)';
      let layout={
        yaxis:{
        title:yAxisTile,
        zeroline:false,
        showlegend: true,
        legend :{
          x:rawData.length+1
        }
       },
       xaxis:{
         automargin: true
       }
      };

      let layout2={
        yaxis:{
        title:'Concentration<br>in Log2 Scale',
        zeroline:false,
        showlegend: true,
        legend :{
          x:rawData.length+1
        }
       },
       xaxis:{
         automargin: true
       }
      };

      let layout10={
        yaxis:{
        title:'Concentration<br>in Log10 Scale',
        zeroline:false,
        showlegend: true,
        legend :{
          x:rawData.length+1
        }
       },
       xaxis:{
         automargin: true
       }
      };
      const d3colors = Plotly.d3.scale.category10();


      for(let i=0; i< rawData.length;i++){
        const tempPlotDataArray=rawData[i].split(';');
        const plotDataArray=[];
        const plotDataArrayLog2=[];
        const plotDataArrayLog10=[];
        let tempArray=tempPlotDataArray[2].split('|');
        if (tempPlotDataArray[2] === 'NA' || tempPlotDataArray[2].trim().length == 0){
          tempArray=tempPlotDataArray[1].split('|');
        }
        for(let j=0; j< tempArray.length;j++){
           plotDataArray.push(parseFloat(tempArray[j]));
           plotDataArrayLog2.push(Math.log2(parseFloat(tempArray[j])));
           plotDataArrayLog10.push(Math.log10(parseFloat(tempArray[j])));
        }
        let prepareDatatoPlotData={};
        let prepareDatatoPlotDataLog2={};
        let prepareDatatoPlotDataLog10={};

        let boxSamLLOQData={};
        let boxSamLLOQDataLog2={};
        let boxSamLLOQDataLog10={};

        let boxULOQData={};
        let boxULOQDataLog2={};
        let boxULOQDataLog10={};

        let tempplotDataArray=plotDataArray.filter(value=> !Number.isNaN(value));
        if (tempPlotDataArray[2] === 'NA' || tempPlotDataArray[2].trim().length == 0){
          if (tempplotDataArray.length > 0){
            prepareDatatoPlotData={
              y:plotDataArray,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
            prepareDatatoPlotDataLog2={
              y:plotDataArrayLog2,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
            prepareDatatoPlotDataLog10={
              y:plotDataArrayLog10,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              type:'box',
              marker:{
                color:'black'
              },
              fillcolor:'rgba(0,0,0,0)',
              line:{
                color:'rgba(0,0,0,0)'
              },
              hoverinfo:'skip'
            };
          }

        } else {
          if (tempplotDataArray.length > 0){
            const tempColor=tissueColor[tempPlotDataArray[0].split('|')[0]];
            prepareDatatoPlotData={
              y:plotDataArray,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              boxmean:true,
              marker:{
                color:tempColor
              },
              type:'box'
            };
            prepareDatatoPlotDataLog2={
              y:plotDataArrayLog2,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              boxmean:true,
              marker:{
                color:tempColor
              },
              type:'box'
            };
            prepareDatatoPlotDataLog10={
              y:plotDataArrayLog10,
              name: tempPlotDataArray[0],
              boxpoints: 'all',
              jitter: 0,
              pointpos: 0,
              boxmean:true,
              marker:{
                color:tempColor
              },
              type:'box'
            };
          }
        }

        if (tempplotDataArray.length > 0){
            boxSamLLOQData={
              x:[tempPlotDataArray[0]],
              y:[parseFloat(tempPlotDataArray[3])],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };


            boxSamLLOQDataLog2={
              x:[tempPlotDataArray[0]],
              y:[Math.log2(parseFloat(tempPlotDataArray[3]))],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };

            boxSamLLOQDataLog10={
              x:[tempPlotDataArray[0]],
              y:[Math.log10(parseFloat(tempPlotDataArray[3]))],
              text: 'Sample LLOQ',
              marker:{
                color:'red',
                symbol:'triangle-up',
                size:8
              },
              showlegend:false
            };

            boxULOQData={
              x:[tempPlotDataArray[0]],
              y:[parseFloat(tempPlotDataArray[4])],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };


            boxULOQDataLog2={
              x:[tempPlotDataArray[0]],
              y:[Math.log2(parseFloat(tempPlotDataArray[4]))],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };

            boxULOQDataLog10={
              x:[tempPlotDataArray[0]],
              y:[Math.log10(parseFloat(tempPlotDataArray[4]))],
              text: 'ULOQ',
              marker:{
                color:'red',
                symbol:'triangle-down',
                size:8
              },
              showlegend:false
            };

          prepareDatatoPlotDataArray.push(prepareDatatoPlotData);
          prepareDatatoPlotDataArray.push(boxSamLLOQData);
          prepareDatatoPlotDataArray.push(boxULOQData);
          prepareDatatoPlotDataArrayLog2.push(prepareDatatoPlotDataLog2);
          prepareDatatoPlotDataArrayLog2.push(boxSamLLOQDataLog2);
          prepareDatatoPlotDataArrayLog2.push(boxULOQDataLog2);
          prepareDatatoPlotDataArrayLog10.push(prepareDatatoPlotDataLog10);
          prepareDatatoPlotDataArrayLog10.push(boxSamLLOQDataLog10);
          prepareDatatoPlotDataArrayLog10.push(boxULOQDataLog10);
        }
      }

     let finalprepareDatatoPlotDataArray={
       0:prepareDatatoPlotDataArray,
       1:prepareDatatoPlotDataArrayLog2,
       2:prepareDatatoPlotDataArrayLog10
     }

      let defaultPlotlyConfiguration={};
      defaultPlotlyConfiguration ={
        responsive: true,
        scrollZoom: true,
        showTips:true,
        modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
        displayLogo: false
      };

      this.finalPlotData={
        'plotData':finalprepareDatatoPlotDataArray,
        'plotLayout':[layout,layout2,layout10],
        'config':defaultPlotlyConfiguration
      };
      Plotly.newPlot('myDivConc',finalprepareDatatoPlotDataArray[2],layout10,defaultPlotlyConfiguration);

      if (rawData.length==0){
        Plotly.purge('myDivConc')
      }
    }
  onOptionsSelected(event){
      if(event.target){
        let tempPlotData=this.finalPlotData['plotData'];
        let tempPlotLayout=this.finalPlotData['plotLayout'];
        let tempConfig=this.finalPlotData['config'];
        if (this.selected.name == 'Concentration Data'){
          Plotly.purge('myDivConc')
          Plotly.newPlot('myDivConc',tempPlotData[0],tempPlotLayout[0],tempConfig)
        }

        if (this.selected.name == 'Log2(Concentration Data)'){
          Plotly.purge('myDivConc')
          Plotly.newPlot('myDivConc',tempPlotData[1],tempPlotLayout[1],tempConfig)
        }

        if (this.selected.name == 'Log10(Concentration Data)'){
          Plotly.purge('myDivConc')
          Plotly.newPlot('myDivConc',tempPlotData[2],tempPlotLayout[2],tempConfig)
        }
        
      }
    }

}
<file_sep>/backend/updatefile/runjob.py
import schedule
import time
import subprocess,shutil
def job():
	commandjob = "python generate_final_data_report_qmpkp.py"
	subprocess.Popen(commandjob, shell=True).wait()


schedule.every().day.at("04:00").do(job)

while 1:
	schedule.run_pending()
	time.sleep(1)
<file_sep>/backend/src/qmpkbapp/api/views.py
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework.permissions import IsAdminUser

from qmpkbapp.models import IpAddressInformation

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.schemas import SchemaGenerator
from rest_framework.permissions import AllowAny
import coreapi,coreschema
from rest_framework.schemas import ManualSchema
from rest_framework_swagger import renderers
import sys,re,os,glob,shutil,subprocess,socket
from django.conf import settings

import requests

from django.views import View
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required

def fileApi(request):
	return Response()<file_sep>/backend/updatefile/maketotalassaypep.py
import os,subprocess,psutil,re,shutil,datetime,sys,glob
from socket import error as SocketError
import errno
import random, time
import csv
import json
import pandas as pd
from collections import Counter
from itertools import combinations
import operator
import collections
import ctypes

def totalAssayPep():
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
	filename='ReportBook_mother_file.csv'
	pepfilepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)

	pepresult = csv.DictReader(open(pepfilepath,'r'), delimiter='\t')

	totalpepseq=[]
	for reppeprow in pepresult:
		totalpepseq.append(str(reppeprow['Peptide Sequence']).strip())
	unqtotalpepseq=list(set(totalpepseq))
	calfilename='totalpepassay.py'
	calmovefilepath=os.path.join(homedir, 'updatefile', calfilename)
	calfilepath = os.path.join(homedir, 'src/qmpkbapp', calfilename)

	totalassayresult={}
	totalassayresult['totalpepassay']=unqtotalpepseq

	calfileoutput=open(calfilename,'w')
	calfileoutput.write("totalpepassay=")
	calfileoutput.write(json.dumps(totalassayresult))
	calfileoutput.close()
	shutil.move(calmovefilepath,calfilepath)<file_sep>/backend/src/qmkbdjangulardb/urls.py
"""qmkbdjangulardb URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework import routers
from rest_framework_swagger.views import get_swagger_view
from qmpkbapp.views import basicSearch,advancedSearch,concentration,assaydetails,protVista,\
SwaggerRestAPIView,goterm,pathway,peptideUniqueness,pathwayview,contact,geneExp,foldChange,\
detailInformation,detailConcentration,saveFastaFile,submission,generateDownload

# from django.contrib.auth.decorators import login_required
# import django_cas_ng.views


schema_view= get_swagger_view(title="Rest API Documents")

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^resultsapi/$', basicSearch, name='result'),
    url(r'^advanceresultsapi/$', advancedSearch, name='advanceresult'),
    url(r'^seqfeaturesapi/$', protVista, name='seqfeatures'),
    url(r'^concentrationapi/$', concentration, name='concentration'),
    url(r'^assaydetailsapi/$', assaydetails, name='assaydetails'),
    url(r'^gotermapi/$', goterm, name='goterm'),
    url(r'^geneexpapi/$', geneExp, name='geneexp'),
    url(r'^pathwayapi/$', pathway, name='pathway'),
    url(r'^pathwayviewapi/$', pathwayview, name='pathwayview'),
    url(r'^peptideuniquenessapi/$', peptideUniqueness, name='peptideUniqueness'),
    url(r'^restapi/$', SwaggerRestAPIView.as_view()),
    url(r'^docapi/', schema_view),
    url(r'^fileapi/', include('qmpkbapp.api.urls')),
    url(r'^contactapi/$', contact, name='contact'),
    url(r'^foldChangeapi/$', foldChange, name='foldChange'),
    url(r'^detailinformationapi/$', detailInformation, name='detailinformation'),
    url(r'^detailConcentrationapi/$', detailConcentration, name='detailconcentration'),
    url(r'^fastafileapi/$', saveFastaFile, name='savefastafile'),
    url(r'^submissionapi/$', submission, name='submission'),
    url(r'^downloadapi/$', generateDownload, name='generateDownload'),
    #after login removed delete or intacivte remining url and active the inactive url
    url(r'^accounts/', include('django.contrib.auth.urls')),
    url(r'^.*',TemplateView.as_view(template_name="qmpkb_home.html"), name='home'),
    # url(r'^.*',login_required(TemplateView.as_view(template_name="qmpkb_home.html")), name='home'),
    # url(r'^accounts/login/$',cas_views.login, name='cas_ng_login'),
    # url(r'^accounts/login/$',cas_views.logout, name='cas_ng_logout'),
    # url(r'^accounts/login/$*',cas_views.callback, name='cas_ng_proxy_callback'),

]<file_sep>/client/qmpkb-app/src/app/subcell-location/subcell-location.component.ts
import { Component, OnInit, OnDestroy,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-subcell-location',
  templateUrl: './subcell-location.component.html',
  styleUrls: ['./subcell-location.component.css']
})
export class SubcellLocationComponent implements OnInit {

  subCellDataStatus=false;
  subCellQueryData:any;
  subcellInputData:any;
  subcellInputDataArray:any;


  filterredSubcell:any;
  filterSubCellStatus=false;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private _qmpkb:QmpkbService
    ) { }

  @Input()
  set subCelltermQuery(subcellLocalQuery:any){
      this.subCellQueryData=subcellLocalQuery;

  }

  ngOnInit() {
  	this.subCellDataStatus=true;
    this.subcellInputDataArray=this.subCellQueryData.subcellArray;
  	this.subcellInputData=this.subCellQueryData.subcell;
  }

  ngAfterViewInit(): void {
     var self= this;

      $("#myInputSubCell").on("keyup", function() {
        const valueSubCell = $(this).val().toString().toLowerCase();
        if (valueSubCell.trim().length > 0){
          self.filterSubCellStatus=true;
          const textArraySubCell=self.subcellInputDataArray;        
          const filterredSubCell=textArraySubCell.filter(function (elem) {
                return elem.toString().toLowerCase().indexOf(valueSubCell) > -1;
          });
          if (filterredSubCell.length >0){
              self.filterredSubcell=filterredSubCell.join('; '); 
          } else{
             self.filterredSubcell='Oopps. No result matched with your search criteria!'; 
          }      
        } 
        if (valueSubCell.trim().length == 0){
          self.filterSubCellStatus=false;
        }
      });
  }

}
<file_sep>/backend/updatefile/map_mouse_to_humanVUni.py
'''
this script based on uniprot homolog file
'''

import os,subprocess,psutil,re,shutil,datetime,sys,glob
import urllib,urllib2,urllib3,httplib
from socket import error as SocketError
import errno
from Bio import SeqIO
import random, time
import csv
import more_itertools as mit
import pickle
import cPickle
from xml.etree import cElementTree as ET
import xmltodict
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from bioservices.kegg import KEGG
import pandas as pd
import ctypes

def mapSpecies(mousepeptrackfilename):
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	uniproturl = 'https://www.uniprot.org/uploadlists/'

	RETRY_TIME = 20.0
	mdf= pd.read_csv(mousepeptrackfilename, delimiter='\t')
	mouseGenes=list(mdf['Gene'].unique())
	mouseGenes=[g for g in mouseGenes if str(g) !='nan']

	mousehumandic={}
	for gx in range(0,len(mouseGenes),1000):
		genecodes=' '.join(mouseGenes[gx:gx+1000])
		geneuniprotparams = {
		'from':'GENENAME',
		'to':'ACC',
		'format':'tab',
		'query':genecodes,
		'columns':'id,genes(PREFERRED),organism-id,reviewed'

		}
		while True:
			try:
				geneuniprotdata = urllib.urlencode(geneuniprotparams)
				geneuniprotrequest = urllib2.Request(uniproturl, geneuniprotdata)
				geneuniprotresponse = urllib2.urlopen(geneuniprotrequest)
				for guniprotline in geneuniprotresponse:
					gudata=guniprotline.strip()
					if not gudata.startswith("Entry"):
						guinfo=gudata.split("\t")
						if '9606' == guinfo[2].lower() and 'reviewed' == guinfo[3].lower() and guinfo[-1].lower() ==guinfo[1].lower() and len(guinfo[0].strip())>1:
							mousehumandic[guinfo[-1].strip()]=guinfo[0].strip()
				break
			except urllib2.HTTPError:
				time.sleep(RETRY_TIME)
				print ('Hey, I am trying again until succeeds to get data from uniprot data!',str(datetime.datetime.now()))
			except httplib.BadStatusLine:
				time.sleep(RETRY_TIME)
				print ('Hey, I am trying again until succeeds to get data from  uniprot data!',str(datetime.datetime.now()))


	colname=['UniProtKB Accession','Protein','Gene','Organism','Peptide Sequence','Summary Concentration Range Data','All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based','Peptide ID',\
	'Special Residues','Molecular Weight','GRAVY Score','Transitions','Retention Time','Analytical inofrmation',\
	'Gradients','AAA Concentration','CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ','Protocol','Trypsin','QC. Conc. Data','Human UniProtKB Accession']

	finalresult=[]
	finalresult.append(colname)
	humanUniprotID=[]
	with open(mousepeptrackfilename) as csvfile:
		reader = csv.DictReader(csvfile, delimiter='\t')
		for row in reader:
			templist=[]
			for i in colname[:-1]:
				tempdata=str(row[i]).strip()
				templist.append(tempdata)
			if len(str(templist[2]).strip())>0:
				if templist[2] in mousehumandic:
					huUniId=mousehumandic[templist[2]]
					humanUniprotID.append(huUniId)
					templist.append(huUniId)
				else:
					templist.append('NA')

			finalresult.append(templist)

	with open(mousepeptrackfilename,'wb') as pf:
		pwriter =csv.writer(pf,delimiter='\t')
		pwriter.writerows(finalresult)

	unqhumanUniprotID=list(set(humanUniprotID))
	humanUniprotfuncinfodic={}
	countProt=0
	for subcode in unqhumanUniprotID:
		time.sleep(2)
		drugbanklist=[]
		PN='NA'
		GN='NA'
		OG='NA'
		OGID='NA'
		dislist=[]
		GoIDList=[]
		GoNamList=[]
		GoTermList=[]
		try:
			countProt+=1
			if countProt%1000 ==0:
				print str(countProt), "th protein Protein Name, Gene, Organism Name,drug bank data,disease data job starts",str(datetime.datetime.now())

			SGrequestURL="https://www.uniprot.org/uniprot/"+str(subcode)+".xml"
			SGunifile=urllib.urlopen(SGrequestURL)
			SGunidata= SGunifile.read()
			SGunifile.close()

			try:
				SGunidata=minidom.parseString(SGunidata)
				try:
					drugdata=(SGunidata.getElementsByTagName('dbReference'))
					for duItem in drugdata:
						if (duItem.attributes['type'].value).upper() == 'DRUGBANK':
							try:
								drugname=(str(duItem.getElementsByTagName('property')[0].attributes['value'].value).strip())
								drugid=str(duItem.attributes['id'].value).strip()
								durl='<a target="_blank" href="https://www.drugbank.ca/drugs/'+drugid+'">'+drugname+'</a>'
								drugbanklist.append(durl)
							except:
								pass
						if (duItem.attributes['type'].value).strip() == 'NCBI Taxonomy':
							try:
								OGID=str(duItem.attributes['id'].value).strip()
							except:
								pass
				except IndexError:
					pass

				try:
					godata=(SGunidata.getElementsByTagName('dbReference'))
					for gItem in godata:
						if (gItem.attributes['type'].value).upper() == 'GO':
							try:
								gonamedetails=(str(gItem.getElementsByTagName('property')[0].attributes['value'].value).strip()).split(':')[1]
								gotermdetails=(str(gItem.getElementsByTagName('property')[0].attributes['value'].value).strip()).split(':')[0]
								GoNamList.append(gonamedetails)
								goid=str(gItem.attributes['id'].value).strip()
								GoIDList.append(goid)
								if gotermdetails.lower()=='p':
									GoTermList.append('Biological Process')
								if gotermdetails.lower()=='f':
									GoTermList.append('Molecular Function')
								if gotermdetails.lower()=='c':
									GoTermList.append('Cellular Component')
							except:
								pass

						if (gItem.attributes['type'].value).strip() == 'NCBI Taxonomy':
							try:
								OGID=str(gItem.attributes['id'].value).strip()
							except:
								pass
				except IndexError:
					pass

				try:
					try:
						PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('recommendedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

					except:
						PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('submittedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

				except IndexError:
					pass

				try:
					try:
						GN=((SGunidata.getElementsByTagName('gene')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
					except:
						GN='NA'
				except IndexError:
					pass

				try:
					try:
						OG=((SGunidata.getElementsByTagName('organism')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
					except:
						OG='NA'
				except IndexError:
					pass

				try:
					disdata=SGunidata.getElementsByTagName('disease')
					for dItem in disdata:
						disname=''
						disshort=''
						try:
							disname=(dItem.getElementsByTagName('name')[0]).firstChild.nodeValue
						except:
							pass
						try:
							disshort=(dItem.getElementsByTagName('acronym')[0]).firstChild.nodeValue
						except:
							pass
						if len(disname.strip())>0:
							dislist.append(str(disname.strip())+'('+str(disshort)+')')
				except IndexError:
					pass

			except ExpatError:
				pass
		except IOError:
			pass
		drugbankdata='NA'
		disdata='NA'
		goiddata='NA'
		gonamedata='NA'
		gotermdata='NA'
		if len(GoIDList)>0:
			goiddata='|'.join(list(set(GoIDList)))
		if len(GoNamList)>0:
			gonamedata='|'.join(list(set(GoNamList)))
		if len(GoTermList)>0:
			gotermdata='|'.join(list(set(GoTermList)))
		if len(drugbanklist)>0:
			drugbankdata='|'.join(list(set(drugbanklist)))
		if len(dislist)>0:
			disdata='|'.join(list(set(dislist)))

		humanUniprotfuncinfodic[subcode]=[PN,GN,OG,OGID,disdata,drugbankdata,goiddata,gonamedata,gotermdata]

	hudicfile='humanUniprotfuncinfodic.obj'
	hudicf = open(hudicfile, 'wb')
	pickle.dump(humanUniprotfuncinfodic, hudicf , pickle.HIGHEST_PROTOCOL)
	hudicf.close()	

	print ("Extracting KEGG pathway name, job starts",str(datetime.datetime.now()))
	hkeggdictfile={}
	hk = KEGG()
	for hkx in range(0,len(unqhumanUniprotID),2000):
		countProt+=hkx+2000
		if countProt%2000 ==0:
			print (str(countProt), "th protein kegg job starts",str(datetime.datetime.now()))

		huniprotcodes=' '.join(unqhumanUniprotID[hkx:hkx+2000])
		huniprotparams = {
		'from':'ACC',
		'to':'KEGG_ID',
		'format':'tab',
		'query':huniprotcodes
		}
		
		while True:
			try:
				hkuniprotdata = urllib.urlencode(huniprotparams)
				hkuniprotrequest = urllib2.Request(uniproturl, hkuniprotdata)
				hkuniprotresponse = urllib2.urlopen(hkuniprotrequest)
				for hkuniprotline in hkuniprotresponse:
					hkudata=hkuniprotline.strip()
					if not hkudata.startswith("From"):
						hkuinfo=hkudata.split("\t")
						if len(hkuinfo[1].strip()):
							hkegg=hk.get(hkuinfo[1].strip())
							hkudict_data = hk.parse(hkegg)
							try:
								try:
									if len(str(hkuinfo[0]).strip()) >5:
										hkeggdictfile[hkuinfo[0].strip()]=hkudict_data['PATHWAY'].values()
								except TypeError: 
									pass
							except KeyError:
								pass
				break
			except urllib2.HTTPError:
				time.sleep(RETRY_TIME)
				print ('Hey, I am trying again until succeeds to get data from KEGG!',str(datetime.datetime.now()))
				pass

	hkdicfile='humankeggdic.obj'
	hkdicf = open(hkdicfile, 'wb')
	pickle.dump(hkeggdictfile, hkdicf , pickle.HIGHEST_PROTOCOL)
	hkdicf.close()<file_sep>/client/qmpkb-app/src/app/qmpkb-service/qmpkb.service.ts
import { Injectable, OnDestroy } from '@angular/core';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { map, catchError,takeUntil } from 'rxjs/operators';
import { BehaviorSubject,Subject,Observable, throwError } from 'rxjs';

const endpoint = 'http://127.0.0.1:8000'

@Injectable({
  providedIn: 'root'
})
export class QmpkbService implements OnDestroy {
  public queryStorage:any;
  public dropDownStorage:any;
  private destroy$ = new Subject();
  constructor(
  	private http: HttpClient
  ) { }

  receiveDataFromBackendSearch(url){
    return this.http.get(url)
        .pipe(
            takeUntil(this.destroy$),
            map(responce=>responce),
            catchError(this.handleError)
        )

  }

  private handleError(error:any, caught:any): any{
      //console.log(error, caught)
      if(error.status == 404){
        alert("Oopps. Not found!");
      } else {
        alert("Something went wrong. Please try again.");
      }
  }

  ngOnDestroy(): void{
    this.destroy$.next(); // trigger the unsubscribe
    this.destroy$.complete(); // finalize and clean up the subject stream
  }
}<file_sep>/client/qmpkb-app/src/app/download-result/download-result.component.ts
import { Component, OnInit, OnDestroy,Input,Renderer} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

@Component({
  selector: 'app-download-result',
  templateUrl: './download-result.component.html',
  styleUrls: ['./download-result.component.css']
})
export class DownloadResultComponent implements OnInit {

  downloadResultJsonPath:any;
  downloadResultStatus=false;
  downloadPathLink:any;
  queryData:any;
  errorStr:Boolean;

  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private _qmpkb:QmpkbService,
    private renderer: Renderer,
    ) { 
  }

  @Input()
  set downloadTermQuery(dQuery:any){
      this.downloadResultJsonPath=dQuery;

  }

  async  getDownloadFileLink(){
    await this._qmpkb.receiveDataFromBackendSearch('/downloadapi/?jsonfile=' + this.downloadResultJsonPath).subscribe((response: any)=>{
      
      this.queryData=response;
      this.downloadPathLink='fileapi/resultFile/downloadResult/search/'+this.queryData.downloadFileName;

       this.downloadResultStatus=true;
    }, error=>{
      this.errorStr = error;
    })

  }
  ngOnInit() {
  	this.getDownloadFileLink();
  }

}
<file_sep>/client/qmpkb-app/src/app/results-query/results-query.component.ts
import { Component, OnInit, Input, Renderer } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import { NgxSpinnerService } from 'ngx-spinner';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-results-query',
  templateUrl: './results-query.component.html',
  styleUrls: ['./results-query.component.css']
})
export class ResultsQueryComponent implements OnInit {

  loadQuery:any;
  @Input()
  inputQuery:any;
  inputQueryStatus=0;
  inputFastaQuery:any;
  inputFastaQueryStatus=0;
  errorStr:Boolean;
  public alertIsVisible:boolean= false;
  public alertIsVisibleValidQuery:boolean=false;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private http: HttpClient,
    private renderer: Renderer,
    private _qmpkb:QmpkbService,
    private spinner: NgxSpinnerService
  ) { }

  async  getQuery(){
    await this.route.queryParams.subscribe(params=>{
      this.loadQuery =params;
      if (Object.keys(this.loadQuery).length > 0){
        this.spinner.show();
        setTimeout(() => {
          this.getProteinData(this.loadQuery);
        }, 100); 
      } else {
        this.spinner.hide();
        if(this.alertIsVisible){
          return;
        }
        this.alertIsVisible=true;
        setTimeout(()=>{
          this.alertIsVisible=false;
          this.router.navigate(['/']);
        },5000);
      }
    })
  }
  getProteinData(queryData:any){
    const queryParameters=Object.keys(this.loadQuery);
    if (queryParameters[0]=='searchterm' && Object.keys(queryParameters).length) {
      if (this.loadQuery.searchterm.trim().length >0 ){
        this._qmpkb.receiveDataFromBackendSearch('/resultsapi/?searchterm=' +this.loadQuery.searchterm).subscribe((response: any)=>{
            if (response.filename_proteincentric != null){
                this.inputQuery={
                  searchterm: this.loadQuery.searchterm,
                  filepath: response.filename_proteincentric,
                  totallist: response.totallist,
                  unqisostat: response.unqisostat,
                  subcell:response.subcell,
                  humandisease:response.humandisease,
                  updatedgo:response.updatedgo,
                  querystrainData:response.querystrainData,
                  querybioMatData:response.querybioMatData,
                  querynoOfDiseaseAssProt:response.querynoOfDiseaseAssProt,
                  querynoOfHumanOrtholog:response.querynoOfHumanOrtholog,
                  keggchart:response.keggchart,
                  foundHits:response.foundHits
                };
                this.inputQueryStatus=1;
            } else {
              this.spinner.hide();
              if(this.alertIsVisible){
                return;
              }
              this.alertIsVisible=true;
              setTimeout(()=>{
                this.alertIsVisible=false;
                this.router.navigate(['/']);
              },5000);
            }
          }, error=>{
            this.errorStr = error;
          })
        } else{
            this.spinner.hide();
            if(this.alertIsVisibleValidQuery){
              return;
            }
            this.alertIsVisibleValidQuery=true;
            setTimeout(()=>{
              this.alertIsVisibleValidQuery=false;
              this.router.navigate(['/']);
            },5000); 
        }
      } else {
       let buildAdvancedFormData=[];
       const advanceQueryParmsArray=['uniProtKBAccession','protein','gene','pepSeq','panel','strain','mutant','sex','biologicalMatrix','subCellLoc','keggPathway','disCausMut','goId','goTerm','goAspects','drugId','fastaFileName'];
       const userAdvanceQuery=Object.keys(this.loadQuery);
       for(let i=0; i<Object.keys(userAdvanceQuery).length;i++){
           if (advanceQueryParmsArray.includes(userAdvanceQuery[i]) && this.loadQuery[userAdvanceQuery[i]].trim().length>0){
              if (userAdvanceQuery[i]=='panel' || userAdvanceQuery[i]=='strain' ||userAdvanceQuery[i]=='mutant' || userAdvanceQuery[i]=='sex' || userAdvanceQuery[i]=='biologicalMatrix'){
                buildAdvancedFormData.push({selectInput:userAdvanceQuery[i],whereInput:this.loadQuery[userAdvanceQuery[i]].split('|')});
              } else{
                if (userAdvanceQuery[i] =='fastaFileName'){
                  if(this.loadQuery[userAdvanceQuery[i]] !== undefined){
                    buildAdvancedFormData.push({selectInput:userAdvanceQuery[i],whereInput:this.loadQuery[userAdvanceQuery[i]]});
                  }
                } else{
                  buildAdvancedFormData.push({selectInput:userAdvanceQuery[i],whereInput:this.loadQuery[userAdvanceQuery[i]]});
                }
              }
           }
       }
       let advancedFormData={
          queryformData:
            {optionGroups:buildAdvancedFormData
            }
        }
        if (Object.keys(buildAdvancedFormData).length>0){
          this._qmpkb.receiveDataFromBackendSearch('/advanceresultsapi/?advancedFormData=' + JSON.stringify(advancedFormData)).subscribe((response: any)=>{
            if (response.filename_proteincentric != null){
              if (response.unqfastaseqlen >0 ){
                this.inputFastaQuery={
                  searchterm: response.query,
                  filepath: response.filename_proteincentric,
                  totallist: response.totallist,
                  unqisostat: response.unqisostat,
                  subcell:response.subcell,
                  humandisease:response.humandisease,
                  updatedgo:response.updatedgo,
                  querystrainData:response.querystrainData,
                  querybioMatData:response.querybioMatData,
                  querynoOfDiseaseAssProt:response.querynoOfDiseaseAssProt,
                  querynoOfHumanOrtholog:response.querynoOfHumanOrtholog,            
                  keggchart:response.keggchart,
                  foundHits:response.foundHits,
                  fastafilename:response.fastafilename
                };
                this.inputFastaQueryStatus=1;
              } else {
                this.inputQuery={
                  searchterm: response.query,
                  filepath: response.filename_proteincentric,
                  totallist: response.totallist,
                  unqisostat: response.unqisostat,
                  subcell:response.subcell,
                  humandisease:response.humandisease,
                  updatedgo:response.updatedgo,
                  querystrainData:response.querystrainData,
                  querybioMatData:response.querybioMatData,
                  querynoOfDiseaseAssProt:response.querynoOfDiseaseAssProt,
                  querynoOfHumanOrtholog:response.querynoOfHumanOrtholog,
                  keggchart:response.keggchart,
                  foundHits:response.foundHits
                };
                this.inputQueryStatus=1;
              }
            } else {
              this.spinner.hide();
              if(this.alertIsVisible){
                return;
              }
              this.alertIsVisible=true;
              setTimeout(()=>{
                this.alertIsVisible=false;
                 this.router.navigate(['/']);
              },5000);
            }
      }, error=>{
        this.errorStr = error;
        })
      } else{
          this.spinner.hide();
          if(this.alertIsVisibleValidQuery){
            return;
          }
          this.alertIsVisibleValidQuery=true;
          setTimeout(()=>{
            this.alertIsVisibleValidQuery=false;
            this.router.navigate(['/']);
          },5000);
      }
    }
  }
  ngOnInit() {
    this.getQuery();
  }

}
<file_sep>/client/qmpkb-app/src/app/fold-change/fold-change.component.ts

import { Component, OnInit, Input,ViewChildren, QueryList, ElementRef } from '@angular/core';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { Subject } from 'rxjs';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as Plotly from 'plotly.js';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-fold-change',
  templateUrl: './fold-change.component.html',
  styleUrls: ['./fold-change.component.css']
})
export class FoldChangeComponent implements OnInit {

  	queryData:any;
    foldChangeQueryData:any;
  	errorStr:Boolean;
  	foldChangeStatus:Boolean;
  	plotStatus=true;
  	dataStatus=true;
  	foldchangeDataChecked:any=[];
  	selected:any='';
  	checkedValues:any;
  	filteredFoldData:any;
  	checkIfTwoAreSeleected=false;
    resetButton=true;
  	downloadFile:string;
  	plotDataLength=0;

    fieldArray: Array<number> = [0, 1];
    selectedOptions = new Set<string>();
  	@ViewChildren("selectValue") selectValue: QueryList<ElementRef<HTMLSelectElement>>;

  	constructor(
		private http: HttpClient,
		private _qmpkb:QmpkbService,
  	) { }

    @Input()
    set foldChangeResult(foldData:any){
    	let tempQueryData=foldData;
    	this.downloadFile=tempQueryData['DownloadPath'];
    	delete tempQueryData['DownloadPath'];
      this.foldChangeQueryData=tempQueryData['foldChangeQueryData'];
      delete tempQueryData['foldChangeQueryData'];
  		this.queryData=tempQueryData;
    }

    ngOnInit() {

    }


    onOptionsSelected(event){
      if(event.target){
        this.foldchangeDataChecked=[];
        this.checkIfTwoAreSeleected=false;
        this.resetButton=true;
        this.dataStatus=true;
        this.plotDataLength=0;
        this.selectedOptions.clear();
        this.scatterplot({},0,0,0);
      }
    }

   changed() {
      this.selectedOptions.clear();
      this.foldchangeDataChecked=[];
      this.selectValue.forEach(j => {
        const selectedVal = j.nativeElement.value;
        if (selectedVal && selectedVal !== "undefined"){ 
          this.selectedOptions.add(selectedVal);
          this.foldchangeDataChecked.push(selectedVal);
        }
      });

      if (this.foldchangeDataChecked.length==2 && this.foldchangeDataChecked[0] !=="undefined" && this.foldchangeDataChecked[1] !=="undefined") {
        this.checkIfTwoAreSeleected=true;
        this.resetButton=false;
        this.plotStatus=false;
        this.plotDataLength=1;
        this._qmpkb.receiveDataFromBackendSearch('/foldChangeapi/?dropDownTerm='  +this.selected.key +'&checkBoxTerm='+ this.foldchangeDataChecked.join() +'&fileName='+ this.downloadFile +'&queryData='+ JSON.stringify(this.foldChangeQueryData)).subscribe((response: any)=>{
          this.filteredFoldData=response;
          this.foldChangeStatus=response.foldChangeStatus;
          if (this.foldChangeStatus == true){
            this.scatterplot(this.filteredFoldData.log2FoldData,this.filteredFoldData.maxAbsValLog2,this.filteredFoldData.hLine,this.filteredFoldData.maxValPval);
          } else{
            this.plotStatus=true;
            this.dataStatus=false;
          }
        }, error=>{
          this.errorStr = error;
        })
      }
    }


    isSelected(opt: string) {
      return this.selectedOptions.has(opt);
    }

    scatterplot(plotData:any,maxAbsValLog2:any,hLine:any,maxValPval:any):void {

      let defaultPlotlyConfiguration={};
      defaultPlotlyConfiguration ={
        responsive: true,
        scrollZoom: true,
        showTips:true,
        modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
        displayLogo: false
      };


    	const plotDataArray=[];
    	for(let key in plotData){
    		if (plotData[key][0].length >0 ){
    			let trace={}
    			if (key == 'Yes'){
					trace = {
					  x: plotData[key][0],
					  y: plotData[key][1],
					  mode: 'markers',
					  type: 'scatter',
					  text: plotData[key][2],
					  marker: { size: 5,color:'red', opacity:0.5 },
					  hoverinfo:'x+y+text',
	          		  showlegend:false
					};
    			} else{
					trace = {
					  x: plotData[key][0],
					  y: plotData[key][1],
					  mode: 'markers',
					  type: 'scatter',
					  text: plotData[key][2],
					  marker: { size: 5,color:'blue', opacity:0.5 },
					  hoverinfo:'x+y+text',
	          		  showlegend:false
					};
    			}
				plotDataArray.push(trace);
    		}
    	}

    	let verLine1={
		  x: [-1,-1],
		  y: [0,maxValPval],
		  mode: 'lines',
		  line:{
		  		color: 'red',
		  		dash:'dot',
		  		width:1.5
		  },
          showlegend:false,
          hoverinfo:'skip'
    	};
    	let verLine2={
		  x: [1,1],
		  y: [0,maxValPval],
		  mode: 'lines',
		  line:{
		  		color: 'red',
		  		dash:'dot',
		  		width:1.5
		  },
          showlegend:false,
          hoverinfo:'skip'
    	};
    	let horZLine={
		  x: [-maxAbsValLog2-1, maxAbsValLog2+1],
		  y: [hLine,hLine],
		  mode: 'lines',
		  line:{
		  		color: 'red',
		  		dash:'dot',
		  		width:1.5
		  },
          showlegend:false,
          hoverinfo:'skip'
    	}
    	plotDataArray.push(verLine1);
    	plotDataArray.push(verLine2);
    	plotDataArray.push(horZLine);
		let layout = {
			title:{text:'Note: Blue and red circle represents dataset size greater than 1 and equal to 1 respectively.<br>When dataset size is one, we replaced p-value with 1.',font:{size:12}},
			xaxis: {range: [ -maxAbsValLog2-1, maxAbsValLog2+1 ],title: 'Log2 Fold Change'},
  		yaxis: {title:'-Log10(adjusted p-value using BH)'},
      autosize:false,
      width:600,
      height:350,
      margin:{
        l:100,
        r:100,
        b:40,
        t:90
      }
		};
		
		if (Object.keys(plotData).length >0){
			this.plotStatus=true;
      this.checkIfTwoAreSeleected=false;
		}

		Plotly.newPlot('myDiv', plotDataArray, layout, defaultPlotlyConfiguration);
		if (this.plotDataLength==0){
			this.dataStatus=true;
      this.checkIfTwoAreSeleected=false;
			Plotly.purge('myDiv')
		}
    }

}<file_sep>/client/qmpkb-app/src/app/peptideuniqueness/peptideuniqueness.component.html
<ngx-spinner
bdOpacity = 0.9
bdColor = "#333"
size = "medium"
color = "#fff"
type = "ball-atom"
fullScreen = "true"
>
<p style="color: white" > Loading... </p>
</ngx-spinner>

<app-navbar2></app-navbar2>
<div class="container-fluid">
	<div *ngIf="reachable ==true">
        <table datatable [dtOptions]="dtOptions" class="display cell-border" cellspacing="0" width="100%" id="pepUnqness">           
        </table>
	</div>
	<div *ngIf="reachable !==true">
		<p>This data entry is not available due to technical error in connecting to an external data resource. Please try again later.</p>
	</div>
</div><file_sep>/backend/src/qmpkbapp/filterSearch.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import Counter
from itertools import combinations
import ast
from operator import itemgetter
import operator
import json
import re,sys
import itertools
from collections import OrderedDict
import datetime
from statistics import mean
# function to generate peptidebased info into nested json format
def filterSearch(jfinaldata,searchterm,searchtype):
	sexQuery=''
	strainQuery=''
	bioMatQuery=''
	knockoutQuery=''
	panelQuery=''
	tempjfinaldata=[]
	filteredUniProtIDs=[]
	try:
		sexQuery=searchterm[searchtype.index('sex')].strip()
	except ValueError:
		pass
	try:
		strainQuery=searchterm[searchtype.index('strain')].strip()
	except ValueError:
		pass
	try:
		bioMatQuery=searchterm[searchtype.index('biologicalMatrix')].strip()
	except ValueError:
		pass
	try:
		knockoutQuery=searchterm[searchtype.index('knockout')].strip()
	except ValueError:
		pass
	try:
		panelQuery=searchterm[searchtype.index('panel')].strip()
	except ValueError:
		pass
	for jitem in jfinaldata:
		sumConData=str(jitem["Summary Concentration Range Data"])
		allConData=str(jitem["All Concentration Range Data"])
		allConDataSampleLLOQ=str(jitem["All Concentration Range Data-Sample LLOQ Based"])
		sumConDataInfo=sumConData.split(';')
		allConDataInfo=allConData.split(';')
		allConDataSampleLLOQInfo=allConDataSampleLLOQ.split(';')


		if len(bioMatQuery.strip()) >0 and bioMatQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  bioMatQuery.lower().split('|') if q == str(s).strip().lower().split('|')[2]]
			allConDataInfo=[s for s in allConDataInfo for q in  bioMatQuery.lower().split('|') if q == str(s).strip().lower().split('|')[2]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  bioMatQuery.lower().split('|') if q == str(s).strip().lower().split('|')[2]]

		if len(strainQuery.strip()) >0 and strainQuery.strip().lower() !='na':
			sumConDataInfo=[s  for s in sumConDataInfo for q in  strainQuery.lower().split('|') if q == str(s).strip().lower().split('|')[3]]
			allConDataInfo=[s for s in allConDataInfo for q in  strainQuery.lower().split('|') if q == str(s).strip().lower().split('|')[4]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  strainQuery.lower().split('|') if q == str(s).strip().lower().split('|')[4]]

		if len(sexQuery.strip()) >0 and sexQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  sexQuery.lower().split('|') if q==str(s).strip().lower().split('|')[4]]
			allConDataInfo=[s for s in allConDataInfo for q in  sexQuery.lower().split('|') if q==str(s).strip().lower().split('|')[5]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  sexQuery.lower().split('|') if q==str(s).strip().lower().split('|')[5]]

		if len(knockoutQuery.strip()) >0 and knockoutQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  knockoutQuery.lower().split('|') if q.split(' ')[0] in  str(s).strip().lower().split('|')[1].split(' ')[0]]
			allConDataInfo=[s for s in allConDataInfo for q in  knockoutQuery.lower().split('|') if q.split(' ')[0] in str(s).strip().lower().split('|')[1].split(' ')[0]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  knockoutQuery.lower().split('|') if q.split(' ')[0] in str(s).strip().lower().split('|')[1].split(' ')[0]]

		if len(panelQuery.strip()) >0 and panelQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  panelQuery.lower().split('|') if q in str(s).strip().lower().split('|')[0]]
			allConDataInfo=[s for s in allConDataInfo for q in  panelQuery.lower().split('|') if q in str(s).strip().lower().split('|')[0]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  panelQuery.lower().split('|') if q in str(s).strip().lower().split('|')[0]]
		
		
		if len(sumConDataInfo)>0:
			jitem["Summary Concentration Range Data"]=';'.join(sumConDataInfo)
		else:
			jitem["Summary Concentration Range Data"]='NA'

		if len(allConDataInfo)>0:
			jitem["All Concentration Range Data"]=';'.join(allConDataInfo)
		else:
			jitem["All Concentration Range Data"]='NA'

		if len(allConDataInfo)>0:
			jitem["All Concentration Range Data-Sample LLOQ Based"]=';'.join(allConDataSampleLLOQInfo)
		else:
			jitem["All Concentration Range Data-Sample LLOQ Based"]='NA'


		if len(jitem["Summary Concentration Range Data"].strip())>0  and (str(jitem["Summary Concentration Range Data"]).strip()).lower() !='na':
			coninfo=(jitem["Summary Concentration Range Data"].strip()).split(';')
			if len(coninfo)>0:
				subconinfo=coninfo[0].split('|')
				condata="Mean Conc.:"+str(subconinfo[6])+"<br/>Matix:"+str(subconinfo[2])
				tempSampleLLOQInfo=str(jitem['Sample LLOQ'].strip()).split(';')
				if str(subconinfo[6]) =='NA':
					for samLLOQ in tempSampleLLOQInfo:
						if str(subconinfo[2]) in samLLOQ.split('|'):
							condata="<"+str(samLLOQ.split('|')[1].strip())+"(Sample LLOQ)<br/>Matix:"+str(subconinfo[2])
				jitem["Concentration View"]=condata
				strainlist=[]
				sexlist=[]
				matrixlist=[]
				panellist=[]
				knockoutlist=[]
				meanConclist=[]
				unitlist=[]
				for i in coninfo:
					l=i.split('|')
					strainlist.append(l[3])
					sexlist.append(l[4])
					matrixlist.append(l[2])
					panellist.append(l[0])
					knockoutlist.append(l[1])
					meanConcData=l[6]
					unitlist.append(l[6].split(' (')[-1])
					if meanConcData !='NA':
						meanConclist.append(l[2]+':'+str(meanConcData))
					else:
						for samXLLOQ in tempSampleLLOQInfo:
							if str(l[2]) in samXLLOQ.split('|'):
								meanConclist.append("<"+str(samXLLOQ.split('|')[1].strip())+"(Sample LLOQ-"+str(l[2])+")")
				if len(strainlist)>0:
					jitem["Strain"]='<br>'.join(list(set(strainlist)))
					jitem["Sex"]='<br>'.join(list(set(sexlist)))
					jitem["Biological Matrix"]='<br>'.join(list(set(matrixlist)))
					panellist=[x for p in panellist for x in p.split(',')]
					jitem["Panel"]=';'.join(list(set(panellist)))
					jitem["knockout"]=';'.join(list(set(knockoutlist)))
					countSampleLLOQ=len([mc for mc in meanConclist if 'Sample LLOQ' in mc])
					if len(meanConclist) ==countSampleLLOQ:
						meanConclist=list(set(meanConclist))
						jitem['Concentration Range']='<br/>'.join(meanConclist[:2])
					else:
						meanConclist=[m for m in meanConclist if 'Sample LLOQ' not in m]
						meanConclist=list(set(meanConclist))
						jitem['Concentration Range']='<br/>'.join(meanConclist[:2])

				else:
					jitem["Strain"]='NA'
					jitem["Sex"]='NA'
					jitem["Biological Matrix"]='NA'
					jitem["Panel"]='NA'
					jitem["knockout"]='NA'
					jitem["Concentration Range"]='NA'

			jitem["Summary Concentration Range Data"]=jitem["Summary Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
			jitem["Summary Concentration Range Data"]=jitem["Summary Concentration Range Data"].replace('ug protein/u','µg protein/µ')
			jitem["Summary Concentration Range Data"]=jitem["Summary Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

			jitem["All Concentration Range Data"]=jitem["All Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
			jitem["All Concentration Range Data"]=jitem["All Concentration Range Data"].replace('ug protein/u','µg protein/µ')
			jitem["All Concentration Range Data"]=jitem["All Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

			jitem["All Concentration Range Data-Sample LLOQ Based"]=jitem["All Concentration Range Data-Sample LLOQ Based"].replace('fmol target protein/u','fmol target protein/µ')
			jitem["All Concentration Range Data-Sample LLOQ Based"]=jitem["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/u','µg protein/µ')
			jitem["All Concentration Range Data-Sample LLOQ Based"]=jitem["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/mg','µg protein/mg')

			jitem["Concentration View"]=jitem["Concentration View"].replace('fmol target protein/u','fmol target protein/µ')
			jitem["Concentration Range"]=jitem["Concentration Range"].replace('fmol target protein/u','fmol target protein/µ')
			
			tempjfinaldata.append(jitem)
		else:
			filteredUniProtIDs.append(jitem["UniProtKB Accession"])

	return tempjfinaldata,filteredUniProtIDs


def filterConcentration(jfinaldata,searchterm,searchtype):
	sexQuery=''
	strainQuery=''
	bioMatQuery=''
	knockoutQuery=''
	tempjfinaldata=[]
	try:
		sexQuery=searchterm[searchtype.index('sex')].strip()
	except ValueError:
		pass
	try:
		strainQuery=searchterm[searchtype.index('strain')].strip()
	except ValueError:
		pass
	try:
		bioMatQuery=searchterm[searchtype.index('biologicalMatrix')].strip()
	except ValueError:
		pass
	try:
		knockoutQuery=searchterm[searchtype.index('knockout')].strip()
	except ValueError:
		pass


	for jitem in jfinaldata:
		sumConData=str(jitem["Summary Concentration Range Data"])
		allConData=str(jitem["All Concentration Range Data"])
		allConDataSampleLLOQ=str(jitem["All Concentration Range Data-Sample LLOQ Based"])
		sumConDataInfo=sumConData.split(';')
		allConDataInfo=allConData.split(';')
		allConDataSampleLLOQInfo=allConDataSampleLLOQ.split(';')

		if len(bioMatQuery.strip()) >0 and bioMatQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  bioMatQuery.lower().split('|') if q == str(s).strip().lower().split('|')[2]]
			allConDataInfo=[s for s in allConDataInfo for q in  bioMatQuery.lower().split('|') if q == str(s).strip().lower().split('|')[2]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  bioMatQuery.lower().split('|') if q == str(s).strip().lower().split('|')[2]]

		if len(strainQuery.strip()) >0 and strainQuery.strip().lower() !='na':
			sumConDataInfo=[s  for s in sumConDataInfo for q in  strainQuery.lower().split('|') if q == str(s).strip().lower().split('|')[3]]
			allConDataInfo=[s for s in allConDataInfo for q in  strainQuery.lower().split('|') if q == str(s).strip().lower().split('|')[4]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  strainQuery.lower().split('|') if q == str(s).strip().lower().split('|')[4]]

		if len(sexQuery.strip()) >0 and sexQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  sexQuery.lower().split('|') if q==str(s).strip().lower().split('|')[4]]
			allConDataInfo=[s for s in allConDataInfo for q in  sexQuery.lower().split('|') if q==str(s).strip().lower().split('|')[5]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  sexQuery.lower().split('|') if q==str(s).strip().lower().split('|')[5]]

		if len(knockoutQuery.strip()) >0 and knockoutQuery.strip().lower() !='na':
			sumConDataInfo=[s for s in sumConDataInfo for q in  knockoutQuery.lower().split('|') if q.split(' ')[0] in  str(s).strip().lower().split('|')[1].split(' ')[0]]
			allConDataInfo=[s for s in allConDataInfo for q in  knockoutQuery.lower().split('|') if q.split(' ')[0] in str(s).strip().lower().split('|')[1].split(' ')[0]]
			if 'NA' != ''.join(list(set(allConDataSampleLLOQInfo))):
				allConDataSampleLLOQInfo=[s for s in allConDataSampleLLOQInfo if 'NA' !=str(s).strip().upper() for q in  knockoutQuery.lower().split('|') if q.split(' ')[0] in str(s).strip().lower().split('|')[1].split(' ')[0]]

		
		if len(sumConDataInfo)>0:
			jitem["Summary Concentration Range Data"]=';'.join(sumConDataInfo)
		else:
			jitem["Summary Concentration Range Data"]='NA'

		if len(allConDataInfo)>0:
			jitem["All Concentration Range Data"]=';'.join(allConDataInfo)
		else:
			jitem["All Concentration Range Data"]='NA'
		if len(allConDataInfo)>0:
			jitem["All Concentration Range Data-Sample LLOQ Based"]=';'.join(allConDataSampleLLOQInfo)
		else:
			jitem["All Concentration Range Data-Sample LLOQ Based"]='NA'
	
		tempjfinaldata.append(jitem)

	return tempjfinaldata<file_sep>/client/qmpkb-app/src/app/data-load-page/data-load-page.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';

@Component({
  selector: 'app-data-load-page',
  templateUrl: './data-load-page.component.html',
  styleUrls: ['./data-load-page.component.css']
})
export class DataLoadPageComponent implements OnInit {

  loadQuery:string;
  errorStr:Boolean;
  public alertIsVisible:boolean= false;
  constructor(
	private route: ActivatedRoute,
	private router: Router,
	private spinner: NgxSpinnerService,
	private location: Location,
	private _qmpkb:QmpkbService
  ) { }
  
  ngOnInit() {
	this.spinner.show();
	this.route.params.subscribe(params=>{
		this.loadQuery =params['slug']
		if (this.loadQuery.includes('biomat_')) {
			this.location.go('/results/');
			let biomatArray=this.loadQuery.split('_');
			let updatedBiomatQuery=biomatArray[1]+'_mus'
			this._qmpkb.receiveDataFromBackendSearch('/resultsapi/?searchterm=' + updatedBiomatQuery).subscribe((response: any)=>{
				if (response.filename_proteincentric != null){
		            this._qmpkb.queryStorage={
		              searchterm: biomatArray[1],
		              filepath: response.filename_proteincentric,
		              totallist: response.totallist,
		              unqisostat: response.unqisostat,
		              subcell:response.subcell,
		              updatedgo:response.updatedgo,
		              querystrainData:response.querystrainData,
		              querybioMatData:response.querybioMatData,
		              querynoOfDiseaseAssProt:response.querynoOfDiseaseAssProt,
		              querynoOfHumanOrtholog:response.querynoOfHumanOrtholog,		              
		              keggchart:response.keggchart,
		              foundHits:response.foundHits
		            }
		            this.router.navigate(['/results/']);
				} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
				}
			}, error=>{
				this.errorStr = error;
			})
		} else if (this.loadQuery.includes('concentration_')) {
			this.location.go('/concentration/')
			let concentrationArray=this.loadQuery.split('concentration_');
			this._qmpkb.receiveDataFromBackendSearch('/concentrationapi/?query=' + concentrationArray[1]).subscribe((response: any)=>{
				let conclist= response.conclist
				let protList= response.protList
				let foundHits=response.foundHits
				let concUnit = response.concUnit
				let lenOfConcData= response.lenOfConcData
				if (foundHits > 0){
		            this._qmpkb.queryStorage={
					  protList: protList,
					  conclist: conclist,
					  foundHits:foundHits,
					  concUnit: concUnit,
					  lenOfConcData: lenOfConcData
		            }
		            this.router.navigate(['/concentration/']);
				} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
				}
			}, error=>{
				this.errorStr = error;
			})
		} else if (this.loadQuery.includes('userpepseq_')) {
			this.location.go('/peptideuniqueness/')
			let userpepseqArray=this.loadQuery.split('_');
			let filename = userpepseqArray.slice(3).join("_"); 
			this._qmpkb.receiveDataFromBackendSearch('/peptideuniquenessapi/?Uniprotkb=' + userpepseqArray[1]+
				'&pepseq='+ userpepseqArray[2]+
				'&fastafile='+ filename
				).subscribe((response: any)=>{
				let pepunqdata= response.pepunqdata
				let reachable= response.reachable
				if (reachable != false) {
		            this._qmpkb.queryStorage={
						pepunqdata:pepunqdata,
						reachable :reachable
		            }
		            this.router.navigate(['/peptideuniqueness/']);
				} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
				}
			}, error=>{
				this.errorStr = error;
			})
		} else if (this.loadQuery.includes('advanceSearchData_')) {
			/*this.location.go('/results/')*/
			let advanceSearchDataArray=this.loadQuery.split('_');
			let advancedFormData={
				queryformData:
					{optionGroups:
						[
							{selectInput:"gene",whereInput:advanceSearchDataArray[1]}
						]
					}
			}
	        this._qmpkb.receiveDataFromBackendSearch('/advanceresultsapi/?advancedFormData=' + JSON.stringify(advancedFormData)).subscribe((response: any)=>{
	        	if (response.filename_proteincentric != null){
		        	this._qmpkb.queryStorage={
		              searchterm: response.query,
		              filepath: response.filename_proteincentric,
		              totallist: response.totallist,
		              unqisostat: response.unqisostat,
		              subcell:response.subcell,
		              querystrainData:response.querystrainData,
		              querybioMatData:response.querybioMatData,
		              querynoOfDiseaseAssProt:response.querynoOfDiseaseAssProt,
		              querynoOfHumanOrtholog:response.querynoOfHumanOrtholog,		            
		              updatedgo:response.updatedgo,
		              keggchart:response.keggchart,
		              foundHits:response.foundHits,
		              fastafilename:response.fastafilename
		            }
		            this.router.navigate(['/results/']);
	        	
	        	} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
	        	}
	      	}, error=>{
	        this.errorStr = error;
	      	})

		}  else if (this.loadQuery.includes('googleChartData_')) {
			/*this.location.go('/results/')*/
			let googleChartDataArray=this.loadQuery.split('_');
			let advancedFormData:any={};
			let tempinputArrayArray=[];
			if (googleChartDataArray[2]=='strain' || googleChartDataArray[2]=='biologicalMatrix'){
				tempinputArrayArray.push(googleChartDataArray[1]);
				advancedFormData={
					queryformData:
						{optionGroups:
							[
								{selectInput:googleChartDataArray[2],whereInput:tempinputArrayArray}
							]
						}
				}

			} else {
				advancedFormData={
					queryformData:
						{optionGroups:
							[
								{selectInput:googleChartDataArray[2],whereInput:googleChartDataArray[1]}
							]
						}
				}
			}

	        this._qmpkb.receiveDataFromBackendSearch('/advanceresultsapi/?advancedFormData=' + JSON.stringify(advancedFormData)).subscribe((response: any)=>{
	        	if (response.filename_proteincentric != null){
		        	this._qmpkb.queryStorage={
		              searchterm: response.query,
		              filepath: response.filename_proteincentric,
		              totallist: response.totallist,
		              unqisostat: response.unqisostat,
		              subcell:response.subcell,
		              querystrainData:response.querystrainData,
		              querybioMatData:response.querybioMatData,
		              querynoOfDiseaseAssProt:response.querynoOfDiseaseAssProt,
		              querynoOfHumanOrtholog:response.querynoOfHumanOrtholog,	
		              updatedgo:response.updatedgo,
		              keggchart:response.keggchart,
		              foundHits:response.foundHits,
		              fastafilename:response.fastafilename
		            }
		            this.router.navigate(['/results/']);
	        	
	        	} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
	        	}
	      	}, error=>{
	        this.errorStr = error;
	      	})

		} else if (this.loadQuery.includes('detailinformation_')) {
			this.location.go('/detailinformation/')
			let userQuery=this.loadQuery.split('_');
			let resFile=userQuery.slice(3,).join('_');
			this._qmpkb.receiveDataFromBackendSearch('/detailinformationapi/?uniProtKb=' + userQuery[2]+
				'&fileName='+ resFile +'&fastafilename='+userQuery[1]
				).subscribe((response: any)=>{
				let resultFilePath= response.resultFilePath;
				let proteinName=response.proteinName;
		    	let geneName=response.geneName;
		    	let uniprotkb=response.uniprotkb;
		    	let foundHits=response.foundHits;
				let orthologData=response.orthologData;
				let subcell=response.subcell;
				let humanDiseaseUniProt = response.humanDiseaseUniProt;
				let humanDiseaseDisGeNet = response.humanDiseaseDisGeNet;
				let drugBankData = response.drugBankData;
				let fastafilename = response.fastafilename;
				let orgID = response.orgID;

				if (foundHits > 0){ 
		            this._qmpkb.queryStorage={
		            	resultFilePath:resultFilePath,
						proteinName:proteinName,
						geneName:geneName,
						uniprotkb:uniprotkb,
						foundHits:foundHits,
						orthologData:orthologData,
						subcell:subcell,
						humanDiseaseUniProt:humanDiseaseUniProt,
						humanDiseaseDisGeNet:humanDiseaseDisGeNet,
						drugBankData:drugBankData,
						fastafilename:fastafilename,
						orgID:orgID
		            }
		            this.router.navigate(['/detailinformation/']);
				} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
				}
			}, error=>{
				this.errorStr = error;
			})
		}  else if (this.loadQuery.includes('pathwayview_')) {
			this.location.go('/pathwayview/')
			let pathwayviewArray=this.loadQuery.split('_');
			this._qmpkb.receiveDataFromBackendSearch('/pathwayviewapi/?Uniprotkb=' + pathwayviewArray[1]+
				'&organismid='+ pathwayviewArray[3]+
				'&pathwayid='+ pathwayviewArray[2]+
				'&pathwayname='+ pathwayviewArray[4]
				).subscribe((response: any)=>{
				let uniprotid= response.uniprotid
				let uniprotname= response.uniprotname
				let keggimagedict=response.keggimagedict
				let otherkeggcolor = response.otherkeggcolor
				let notpresentkeggcolor = response.notpresentkeggcolor
				let reachable = response.reachable
				if (reachable != false) {
		            this._qmpkb.queryStorage={
						uniprotid:uniprotid,
						uniprotname:uniprotname,
						keggimagedict:keggimagedict,
						otherkeggcolor:otherkeggcolor,
						notpresentkeggcolor:notpresentkeggcolor,
						reachable :reachable
		            }
		            this.router.navigate(['/pathwayview/']);
				} else {
			        this.spinner.hide();
			        if(this.alertIsVisible){
			          return;
			        }
			        this.alertIsVisible=true;
			        setTimeout(()=>{
			          this.alertIsVisible=false;
			           this.router.navigate(['/']);
			        },2000);
				}
			}, error=>{
				this.errorStr = error;
			})
		}

	})
  }

}<file_sep>/client/qmpkb-app/src/app/mouse-anatomy/mouse-anatomy.component.ts
import { Component, OnInit, HostListener } from '@angular/core';

@Component({
  selector: 'app-mouse-anatomy',
  templateUrl: './mouse-anatomy.component.html',
  styleUrls: ['./mouse-anatomy.component.css']
})
export class MouseAnatomyComponent implements OnInit {
  
  screenWidth:any;
  screenHeight:any;
  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=Math.round(window.innerWidth/4)+"px";
    this.screenHeight=Math.round(window.innerWidth/2)+"px";
  }
  constructor() {
    this.getScreenSize();
  }

  ngOnInit() {
  }

}
<file_sep>/client/qmpkb-app/src/app/gene-expression/gene-expression.component.ts
import { Component, OnInit, OnDestroy, ViewChild, Renderer, HostListener,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as Plotly from 'plotly.js';
import { Subject } from 'rxjs';
import * as $ from "jquery";
declare var jquery: any;

@Component({
  selector: 'app-gene-expression',
  templateUrl: './gene-expression.component.html',
  styleUrls: ['./gene-expression.component.css']
})
export class GeneExpressionComponent  implements OnInit {

  dtOptions: any = {};
  errorStr:Boolean;
  geneExplist:any;
  geneExplistlen:number;
  foundHits:number;
  protList:any
  queryData:any;
  plotlyData:any=[];
  screenWidth:any;
  lenOfGeneExpData:any;
  queryGeneExpUniProtKB:any;
  geneExpDataStatus=false;
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;

  plotDataOptions=[
       {num:0, name:'Concentration Data'},
       {num:1, name:'Log2(Concentration Data)'},
       {num:2, name:'Log10(Concentration Data)'},
  ];
  selectedLevel=this.plotDataOptions[0];

  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=(window.innerWidth-50)+"px";
  }

  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService,
    private renderer: Renderer,
    ) { 
      this.getScreenSize();
  }

  @Input()
  set geneexptermQuery(geneExpUniProtKB:any){
      this.queryGeneExpUniProtKB=geneExpUniProtKB;

  }
  async  generateTable(){
    await this._qmpkb.receiveDataFromBackendSearch('/geneexpapi/?uniProtKb=' + this.queryGeneExpUniProtKB).subscribe((response: any)=>{
      
      this.queryData=response;
      this.geneExplist=this.queryData.geneExplist;
      this.geneExplistlen=Object.keys(this.geneExplist).length
      this.foundHits=this.queryData.foundHits;
      this.protList=this.queryData.protList;
      this.lenOfGeneExpData= this.queryData.lenOfGeneExpData;
      this.dtOptions = {
        processing: true,
        serverSide: false,
        orderCellsTop: true,
        fixedHeader: true,
        pageLength: 10,
        pagingType: 'full_numbers',
        scrollX:true,
        scrollY:'650px',
        scrollCollapse:true,
        columnDefs:[
          {
            targets: 0,
            data: null,
            defaultContent: '',
            orderable: false,
            className: 'select-checkbox',
            searchable:false
          },
          {
            targets: 1,
            searchable:false,
            visible:false
          },
          {
            targets: 2,
            searchable:false,
            visible:false
          }
        ],
        select:{
          style:'multi'
        },
        // Declare the use of the extension in the dom parameter
        dom: 'lBfrtip',
        buttons: [
            {
              extend:'csv',
              filename: 'GeneExpressionMouseQuaPro',
              text:'Download all(CSV)',
              exportOptions:{
                columns:[1,2,3,4]
              }
            },
            {
              extend:'excel',
              filename: 'GeneExpressionQMPKB',
              text:'Download all(Excel)',
              exportOptions:{
                columns:[1,2,3,4]
              }
            },
            'selectAll',
            'selectNone'
        ],
        order: [],
        autoWidth:true
      };
      if (this.lenOfGeneExpData > 0){
           setTimeout(() => {this.dataTableGenerated()}, 100); 
       }
       this.geneExpDataStatus=true;
    }, error=>{
      this.errorStr = error;
    })

  }
  ngOnInit() {
     this.generateTable();
  }

  dataTableGenerated(): void {
    const self = this;
    self.datatableElement.dtInstance.then((dtInstance:any) => {
      
      dtInstance.rows(function(idx,data){
        const plotName=data[3];
        const plotData=data[4];
        const tempPlotArray=[plotName,plotData];
        self.plotlyData.push(tempPlotArray.join(';'));
        return idx >=0;
      }).select();
      self.barplot(self.plotlyData);
    });
     self.datatableElement.dtInstance.then(table => {
      $('#dataTables-wrkld-geneExp').on('select.dt', function (e,dt,type,indexes) {
        if (self.lenOfGeneExpData == indexes.length){
           self.plotlyData=[];
           for(let j=0; j< indexes.length;j++){
              const plotName=dt.row(indexes[j]).data()[3];
              const plotData=dt.row(indexes[j]).data()[4];
              const tempPlotArray=[plotName,plotData];
              self.plotlyData.push(tempPlotArray.join(';'));
           }
           self.barplot(self.plotlyData);

        } else {
          const plotName=dt.row(indexes[0]).data()[3];
          const plotData=dt.row(indexes[0]).data()[4];
          const tempPlotArray=[plotName,plotData];
          self.plotlyData.push(tempPlotArray.join(';'));
          self.barplot(self.plotlyData);          
        }

        
      });
      $('#dataTables-wrkld-geneExp').on('deselect.dt', function (e,dt,type,indexes) {
        if (self.lenOfGeneExpData == indexes.length || indexes.length>1 || self.plotlyData == indexes.length){
            self.plotlyData=[];
            self.barplot(self.plotlyData);
        } else {
          const plotName=dt.row(indexes[0]).data()[3];
          const plotData=dt.row(indexes[0]).data()[4];
          const tempPlotArray=[plotName,plotData];
          const indexOfplotlyData=self.plotlyData.indexOf(tempPlotArray.join(';'));
          self.plotlyData.splice(indexOfplotlyData,1);
          self.barplot(self.plotlyData);          
        }

      });
    });


  }

  barplot(dataToPlot:any):void {
      let defaultPlotlyConfiguration:any={};
      defaultPlotlyConfiguration ={
        scrollZoom: true, // lets us scroll to zoom in and out - works
        showTips:true,
        modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
        //modeBarButtonsToAdd: ['lasso2d'],
        displayLogo: false, // this one also seems to not work
      };
      let xAxisData=[];
      let yAxisData=[];
      for(let i=0; i< dataToPlot.length;i++){
        const tempPlotDataArray=dataToPlot[i].split(';');
        xAxisData.push(tempPlotDataArray[0])
        yAxisData.push(tempPlotDataArray[1])
      }
    let expPlotData=[];
    const expTraceData={
      x:xAxisData,
      y:yAxisData,
      type:'bar',
      marker:{
        color:'rgb(142,124,195)'
      }
    }
    expPlotData=[expTraceData];
    const layout={
      title:'Gene Expression',
      font:{
        family:'Raleway, sans-serif'
      },
      showlegend:false,
      xaxis:{
        tickangle:-45
      },
      yaxis:{
        title:'Mean RPKM',
        zeroline:false,
        gridwidth:2
      },
      bargap:0.05
    }


    Plotly.newPlot('myDivGeneExp',expPlotData,layout,defaultPlotlyConfiguration);

    if (dataToPlot.length==0){
      Plotly.purge('myDivGeneExp')
    }
  }
}
<file_sep>/backend/updatefile/compileSkylineDataToFit.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
import datetime,glob
import time
import os,subprocess,psutil,re,sys,shutil
import csv
from map_mouse_to_human import mapSpecies
import datetime
from Bio.SeqUtils.ProtParam import molecular_weight,ProteinAnalysis
import urllib,urllib2,urllib3,datetime
import more_itertools as mit
import pickle
import cPickle
from xml.etree import cElementTree as ET
import xmltodict
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from statistics import mean
from tissueInfo import *
import ctypes

def compileSkylineFile():
	print ("Skyline Data compilation, job starts",str(datetime.datetime.now()))
	curr_dir=os.getcwd()
	colname=['UniProtKB Accession','Protein','Gene','Organism','Peptide Sequence','Summary Concentration Range Data','All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based','Peptide ID',\
	'Special Residues','Molecular Weight','GRAVY Score','Transitions','Retention Time','Analytical inofrmation',\
	'Gradients','AAA Concentration','CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ','Protocol','Trypsin','QC. Conc. Data']
	gradData='Time[min]|A[%]|B[%];0.00|98.00|2.00;2.00|93.00|7.00;50.00|70.00|30.00;53.00|55.00|45.00;53.00|20.00|80.00;55.00|20.00|80.00;56.00|98.00|2.00'

	skylineMouseConcfile=''
	pathwayConcenRes='/home/bioinf/datastoreageiv/bioinformatics/mouse_concen_results/data'
	listOfFileConcen=[]
	if os.path.exists(pathwayConcenRes):
		listOfFileConcen=os.listdir(pathwayConcenRes)
	else:
		mountsCMD='echo "xxxxx" | sudo -S mount -t cifs -o username=xxxxx,password=<PASSWORD> //datastorage /yourlocalDIR/'
		subprocess.Popen(mountsCMD,shell=True).wait()
		listOfFileConcen=os.listdir(pathwayConcenRes)

	updatedConcenDataList=[]
	onlyUpdatedConcenFileList=[]
	currentdate=datetime.datetime.now().strftime("%B-%d-%Y")
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))

	updatedConcenDatafilename='updatedConcenDataInfo.txt'
	with open(updatedConcenDatafilename,'r') as f:
		for l in f:
			d=l.strip()
			updatedConcenDataList.append(d)
			onlyUpdatedConcenFileList.append(d.split(' ')[0])

	for c in listOfFileConcen:
		if c not in onlyUpdatedConcenFileList:
			skylineMouseConcfile=c
			updatedConcenDataList.append(c+' '+currentdate)

	if len(skylineMouseConcfile.strip())>0:
		mouseConcDic={}
		finalresult=[]
		finalresult.append(colname)
		skylineMouseConcfilePath=pathwayConcenRes+'/'+skylineMouseConcfile
		with open(skylineMouseConcfilePath,'r') as skMCfile:
			skMCcsvreader = csv.DictReader(skMCfile)
			headers = skMCcsvreader.fieldnames
			for skMCrow in skMCcsvreader:
				skylineMouseConcDic={}
				sex=str(skMCrow['Sex']).strip()
				if sex=='M':
					sex='Male'
				if sex=='F':
					sex='Female'
				knockout=str(skMCrow['Knockout']).strip()
				panel=str(skMCrow['Panel']).strip()
				panel=panel.replace(';',',')
				strain=str(skMCrow['Strain']).strip()

				concData=str(skMCrow['Conc. Data']).strip()
				sampleConcData=str(skMCrow['Conc. Data SampleLLOQ-Based']).strip()
				updatedMatrix=str(skMCrow['Matrix']).strip()
				sampleProteinContent=[]
				calculatedProteinContent=[]
				allConcentrationRange=[]

				concDataInfo=concData.split(';')
				sampleCountWithoutSampleLLOQ=0
				for conItem in concDataInfo[1:]:
					sampleCountWithoutSampleLLOQ+=1
					tempallConcentrationRange=[str(sampleCountWithoutSampleLLOQ),strain,sex]
					subConInfo=conItem.split('|')
					for ukey in unitDic:
						if ukey in skMCrow['Matrix'].strip().lower():
							tempallConcentrationRange.append(str(subConInfo[0])+unitDic[ukey][0])
							tempallConcentrationRange.append(str(subConInfo[1])+unitDic[ukey][1])
							tempallConcentrationRange.append(str(subConInfo[2])+unitDic[ukey][2])


					tempallConcentrationRange.insert(0,updatedMatrix)
					tempallConcentrationRange.insert(0,knockout)
					tempallConcentrationRange.insert(0,panel)
					allConcentrationRange.append('|'.join(map(str,tempallConcentrationRange)))
				sampleCountWithoutSampleLLOQ=0

				allSampleConcentrationRange=[]
				sampleConcDataInfo=sampleConcData.split(';')
				sampleCountWithSampleLLOQ=0
				if len(sampleConcDataInfo) > 1:
					for sconItem in sampleConcDataInfo[1:]:
						sampleCountWithSampleLLOQ+=1
						sampleTempallConcentrationRange=[str(sampleCountWithSampleLLOQ),strain,sex]
						subSampleConInfo=sconItem.split('|')
						for ukey in unitDic:
							if ukey in skMCrow['Matrix'].strip().lower():
								sampleTempallConcentrationRange.append(str(subSampleConInfo[0])+unitDic[ukey][0])
								sampleTempallConcentrationRange.append(str(subSampleConInfo[1])+unitDic[ukey][1])
								sampleTempallConcentrationRange.append(str(subSampleConInfo[2])+unitDic[ukey][2])


						sampleTempallConcentrationRange.insert(0,updatedMatrix)
						sampleTempallConcentrationRange.insert(0,knockout)
						sampleTempallConcentrationRange.insert(0,panel)
						sampleProteinContent.append(float(subSampleConInfo[1]))
						calculatedProteinContent.append(float(subSampleConInfo[0]))
						allSampleConcentrationRange.append('|'.join(map(str,sampleTempallConcentrationRange)))
				sampleCountWithSampleLLOQ=0

				minsampleProteinContent='NA'
				maxsampleProteinContent='NA'
				meansampleProteinContent='NA'
				if len(sampleProteinContent)>0:
					minsampleProteinContent=str(min(sampleProteinContent))
					maxsampleProteinContent=str(max(sampleProteinContent))
					meansampleProteinContent=str(round(mean(sampleProteinContent),2))


				mincalculatedProteinContent='NA'
				maxcalculatedProteinContent='NA'
				meancalculatedProteinContent='NA'
				if len(calculatedProteinContent)>0:
					mincalculatedProteinContent=str(min(calculatedProteinContent))
					maxcalculatedProteinContent=str(max(calculatedProteinContent))
					meancalculatedProteinContent=str(round(mean(calculatedProteinContent),2))

				sumConcentrationRange=[]
				for ukey in unitDic:
					 if ukey in skMCrow['Matrix'].strip().lower():
						if len(str(skMCrow['Mean Conc.']).strip()) >0 and str(skMCrow['Mean Conc.']).strip().upper() !='NA':
							skMCrow['Mean Conc.']=str(skMCrow['Mean Conc.']).strip()+unitDic[ukey][2]
						if len(str(skMCrow['Min Conc.']).strip()) >0 and str(skMCrow['Min Conc.']).strip().upper() !='NA':
							skMCrow['Min Conc.']=str(skMCrow['Min Conc.']).strip()+unitDic[ukey][2]
						if len(str(skMCrow['Max Conc.']).strip()) >0 and str(skMCrow['Max Conc.']).strip().upper() !='NA':
							skMCrow['Max Conc.']=str(skMCrow['Max Conc.']).strip()+unitDic[ukey][2]
						if len(str(skMCrow['LLOQ']).strip()) >0 and str(skMCrow['LLOQ']).strip().upper() !='NA':
							skMCrow['LLOQ']=str(skMCrow['LLOQ']).strip()+unitDic[ukey][0]
						if len(str(skMCrow['ULOQ']).strip()) >0 and str(skMCrow['ULOQ']).strip().upper() !='NA':
							skMCrow['ULOQ']=str(skMCrow['ULOQ']).strip()+unitDic[ukey][0]
						if len(str(skMCrow['Sample LLOQ']).strip()) >0 and str(skMCrow['Sample LLOQ']).strip().upper() !='NA':
							skMCrow['Sample LLOQ']=str(skMCrow['Sample LLOQ']).strip()+unitDic[ukey][0]
						if len(sampleProteinContent) >0:
							minsampleProteinContent=minsampleProteinContent+unitDic[ukey][1]
							maxsampleProteinContent=maxsampleProteinContent+unitDic[ukey][1]
							meansampleProteinContent=meansampleProteinContent+unitDic[ukey][1]

						if len(calculatedProteinContent) >0:
							mincalculatedProteinContent=mincalculatedProteinContent+unitDic[ukey][0]
							maxcalculatedProteinContent=maxcalculatedProteinContent+unitDic[ukey][0]
							meancalculatedProteinContent=meancalculatedProteinContent+unitDic[ukey][0]

				LLOQ=str(skMCrow['LLOQ']).strip()
				sampleLLOQ=str(skMCrow['Sample LLOQ']).strip()
				ULOQ=str(skMCrow['ULOQ']).strip()
				
				meanConc=str(skMCrow['Mean Conc.']).strip()
				minConc=str(skMCrow['Min Conc.']).strip()
				maxConc=str(skMCrow['Max Conc.']).strip()
				tempnrSamples=str(skMCrow['Nr. samples']).strip()
				nrSamples=str(tempnrSamples.split('/')[-1])+'/'+str(tempnrSamples.split('/')[0])
				sumConcentrationRange=[panel,knockout,updatedMatrix,strain,sex,nrSamples,meancalculatedProteinContent,meansampleProteinContent,meanConc,mincalculatedProteinContent,minsampleProteinContent,minConc,maxcalculatedProteinContent,maxsampleProteinContent,maxConc]
				if len(sumConcentrationRange)>0:
					skylineMouseConcDic['Summary Concentration Range Data']='|'.join(sumConcentrationRange)
				else:
					skylineMouseConcDic['Summary Concentration Range Data']='NA'

				if len(allConcentrationRange)>0:
					skylineMouseConcDic['All Concentration Range Data']=';'.join(allConcentrationRange)
				else:
					skylineMouseConcDic['All Concentration Range Data']='NA'


				if len(allSampleConcentrationRange)>0:
					skylineMouseConcDic['All Concentration Range Data-Sample LLOQ Based']=';'.join(allSampleConcentrationRange)
				else:
					skylineMouseConcDic['All Concentration Range Data-Sample LLOQ Based']='NA'

				skylineMouseConcDic['Special Residues']= 'NA'
				molw=molecular_weight(str(skMCrow['Peptide Sequence']).strip().upper(), "protein", monoisotopic=True)
				molw=round(molw,2)
				skylineMouseConcDic['Molecular Weight']= str(molw)
				protanalys=ProteinAnalysis(str(skMCrow['Peptide Sequence']).strip().upper())
				gravScore=round((protanalys.gravy()),2)
				skylineMouseConcDic['GRAVY Score']= str(gravScore)

				transitionData=str(skMCrow['Transition Data']).strip()
				instrument=str(skMCrow['Instrument']).strip()
				transitionDataList=[]
				if len(transitionData)>0 and transitionData.upper() !='NA':
					subTransDataInfo=transitionData.split(';')
					subTransDataHeader='Instrument|'+subTransDataInfo[0]
					transitionDataList.append(subTransDataHeader)
					for t in subTransDataInfo[1:]:
						subTDInfo=t.split('|')
						subTDInfo.insert(0,instrument)
						transitionDataList.append('|'.join(subTDInfo))

				if len(transitionDataList)>0:
					skylineMouseConcDic['Transitions']= ';'.join(list(set(transitionDataList)))
				else:
					skylineMouseConcDic['Transitions']= 'NA'
				skylineMouseConcDic['Retention Time']= str(skMCrow['Retention Time']).strip()
				skylineMouseConcDic['Analytical inofrmation']= 'Agilent Zorbax Eclipse Plus C18 RRHD 2.1 x 150mm 1.8um'
				skylineMouseConcDic['Gradients']= gradData
				skylineMouseConcDic['AAA Concentration']= 'NA'
				skylineMouseConcDic['CZE Purity']= 'NA'
				panel=panel.replace(',',';')
				skylineMouseConcDic['Panel']= panel
				skylineMouseConcDic['Knockout']= knockout
				skylineMouseConcDic['LLOQ']= updatedMatrix+'|'+LLOQ
				skylineMouseConcDic['ULOQ']= updatedMatrix+'|'+ULOQ
				skylineMouseConcDic['Sample LLOQ']= updatedMatrix+'|'+sampleLLOQ
				skylineMouseConcDic['Protocol']= str(skMCrow['Protocol']).strip()
				skylineMouseConcDic['Trypsin']= str(skMCrow['Trypsin']).strip()
				skylineMouseConcDic['QC. Conc. Data']= str(skMCrow['QC. Conc. Data']).strip()
				skylineConcKey=str(skMCrow['Accession Number']).strip()+'_'+str(skMCrow['Peptide Sequence']).strip().upper()
				if mouseConcDic.has_key(skylineConcKey):
					mouseConcDic[skylineConcKey].append(skylineMouseConcDic)
				else:
					mouseConcDic[skylineConcKey]=[skylineMouseConcDic]
		countProt=0
		for mckey in mouseConcDic:
			tempConcDic={}
			tempConcDic['UniProtKB Accession']=mckey.split('_')[0]
			tempConcDic['Peptide Sequence']=mckey.split('_')[1]
			currdate=str(datetime.datetime.now())
			currdate=currdate.replace('-','')
			currdate=currdate.replace(' ','')
			currdate=currdate.replace(':','')
			currdate=currdate.replace('.','')
			generatePepid='PEP'+currdate+'FAKE'
			tempConcDic['Peptide ID']= generatePepid
			subDickey=['Summary Concentration Range Data','All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based',\
			'Special Residues','Molecular Weight','GRAVY Score','Transitions','Retention Time','Analytical inofrmation',\
			'Gradients','AAA Concentration','CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ','Protocol','Trypsin','QC. Conc. Data']
			sumConcData=[]
			allConcData=[]
			sampleAllConcData=[]
			spRes=[]
			molW=[]
			gravScore=[]
			transData=[]
			retTime=[]
			analytInfo=[]
			grad=[]
			aaConc=[]
			czePur=[]
			panel=[]
			lloq=[]
			uloq=[]
			samlloq=[]
			protocol=[]
			tryps=[]
			qcConcData=[]
			knockoutData=[]
			for item in mouseConcDic[mckey]:
				sumConcData.append(item['Summary Concentration Range Data'])
				for ac in item['All Concentration Range Data'].split(';'):
					allConcData.append(ac)
				for s in item['All Concentration Range Data-Sample LLOQ Based'].split(';'):
					sampleAllConcData.append(s)
				spRes.append(item['Special Residues'])
				molW.append(item['Molecular Weight'])
				gravScore.append(item['GRAVY Score'])
				for t in item['Transitions'].split(';'):
					transData.append(t)
				for r in item['Retention Time'].split(';'):
					retTime.append(r)
				analytInfo.append(item['Analytical inofrmation'])
				grad.append(item['Gradients'])
				aaConc.append(item['AAA Concentration'])
				czePur.append(item['CZE Purity'])
				for p in item['Panel'].split(';'):
					panel.append(p)
				lloq.append(item['LLOQ'])
				uloq.append(item['ULOQ'])
				samlloq.append(item['Sample LLOQ'])
				protocol.append(item['Protocol'])
				tryps.append(item['Trypsin'])
				qcConcData.append(item['QC. Conc. Data'])
				knockoutData.append(item['Knockout'])

			panel =list(set(panel))
			if len(panel)>1:
				 panel=[y for x in panel for y in x.split(';') if 'na' != y.lower()]
			knockoutData =list(set(knockoutData))
			if len(knockoutData)>1:
				knockoutData=[x for x in knockoutData if 'na' != x.lower()]
			transHeader='Instrument|Isotope Label Type|Precursor Mz|Collision Energy|Fragment Ion|Product Charge|Product Mz'
			transData=list(set(transData))
			transData.sort()
			del transData[transData.index(transHeader)]
			retTime.sort()
			sampleAllConcData.sort()
			allConcData.sort()
			panel.sort()
			tempConcDic['Summary Concentration Range Data']=';'.join(map(str,list(set(sumConcData))))
			tempConcDic['All Concentration Range Data']=';'.join(map(str,list(set(allConcData))))
			tempConcDic['All Concentration Range Data-Sample LLOQ Based']=';'.join(map(str,list(set(sampleAllConcData))))
			tempConcDic['Special Residues']=';'.join(map(str,list(set(spRes))))
			tempConcDic['Molecular Weight']=';'.join(map(str,list(set(molW))))
			tempConcDic['GRAVY Score']=';'.join(map(str,list(set(gravScore))))
			tempConcDic['Transitions']=transHeader+';'+';'.join(map(str,list(set(transData))))
			tempConcDic['Retention Time']=';'.join(map(str,list(set(retTime))))
			tempConcDic['Analytical inofrmation']=';'.join(map(str,list(set(analytInfo))))
			tempConcDic['Gradients']=';'.join(map(str,list(set(grad))))
			tempConcDic['AAA Concentration']=';'.join(map(str,list(set(aaConc))))
			tempConcDic['CZE Purity']=';'.join(map(str,list(set(czePur))))
			tempConcDic['Panel']=';'.join(map(str,list(set(panel))))
			tempConcDic['LLOQ']=';'.join(map(str,list(set(lloq))))
			tempConcDic['ULOQ']=';'.join(map(str,list(set(uloq))))

			tempConcDic['Sample LLOQ']=';'.join(map(str,list(set(samlloq))))
			tempConcDic['Protocol']=';'.join(map(str,list(set(protocol))))
			tempConcDic['Trypsin']=';'.join(map(str,list(set(tryps))))
			tempConcDic['QC. Conc. Data']=';'.join(map(str,list(set(qcConcData))))
			tempConcDic['Knockout']=';'.join(map(str,list(set(knockoutData))))


			time.sleep(2)
			PN='NA'
			GN='NA'
			OG='NA'
			uacc=str(mckey.split('_')[0]).strip()
			subcode=uacc.split('-')[0]
			try:
				countProt+=1
				if countProt%1000 ==0:
					print str(countProt), "th protein Protein Name, Gene, Organism Name job starts",str(datetime.datetime.now())

				SGrequestURL="https://www.uniprot.org/uniprot/"+str(subcode)+".xml"
				SGunifile=urllib.urlopen(SGrequestURL)
				SGunidata= SGunifile.read()
				SGunifile.close()

				try:
					SGunidata=minidom.parseString(SGunidata)

					try:
						try:
							PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('recommendedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

						except:
							PN=(((SGunidata.getElementsByTagName('protein')[0]).getElementsByTagName('submittedName')[0]).getElementsByTagName('fullName')[0]).firstChild.nodeValue

					except IndexError:
						pass

					try:
						try:
							GN=((SGunidata.getElementsByTagName('gene')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
						except:
							GN='NA'
					except IndexError:
						pass

					try:
						try:
							OG=((SGunidata.getElementsByTagName('organism')[0]).getElementsByTagName('name')[0]).firstChild.nodeValue
						except:
							OG='NA'
					except IndexError:
						pass

				except ExpatError:
					pass
			except IOError:
				pass

			tempConcDic['Protein']=str(PN)
			tempConcDic['Gene']=str(GN)
			tempConcDic['Organism']=str(OG)

			tempList=[]
			for col in colname: 
				tempList.append(tempConcDic[col])
			finalresult.append(tempList)

		outputresultpeptrack='mouse_report_peptrack_data.csv'
		with open(outputresultpeptrack,'wb') as pf:
			pwriter =csv.writer(pf,delimiter='\t')
			pwriter.writerows(finalresult)

		with open(updatedConcenDatafilename,'w') as ufile:
			for i in updatedConcenDataList:
				ufile.write(i+"\n")

		mapSpecies(outputresultpeptrack)
		print ("Skyline Data compilation, job done",str(datetime.datetime.now()))
		return 1

	else:
		return 0<file_sep>/client/qmpkb-app/src/app/pathwayview/pathwayview.component.ts
import { Component, OnInit, OnDestroy, HostListener } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var jquery: any;


@Component({
  selector: 'app-pathwayview',
  templateUrl: './pathwayview.component.html',
  styleUrls: ['./pathwayview.component.css']
})
export class PathwayviewComponent implements OnInit {

  errorStr:Boolean;
  uniprotid:any;
  uniprotname:any;
  keggimagedict:any;
  keggimagedictlen:number;
  keggurl:any;
  reachable:Boolean;
  queryData:any;
  screenWidth:any;
  loadQuery:any;
  public alertIsVisible:boolean= false;

  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=Math.round(window.innerWidth-50)+"px";
  }
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { 
        this.getScreenSize();
  }

  async  getQuery(){
    await this.route.queryParams.subscribe(params=>{
      this.loadQuery =params;
      if (Object.keys(this.loadQuery).length > 0){
        this.spinner.show();
        setTimeout(() => {
          this.getPathwayData(this.loadQuery);
        }, 100); 
      } else {
        this.spinner.hide();
        if(this.alertIsVisible){
          return;
        }
        this.alertIsVisible=true;
        setTimeout(()=>{
          this.alertIsVisible=false;
          this.router.navigate(['/']);
        },5000);
      }
    })
  }

  getPathwayData(queryData:any){
    const queryParameters=Object.keys(this.loadQuery);
    let qUniProtKB='NA';
    let qOrgID='NA';
    let qPathWayID='NA';
    let qPathWayName='NA';
    for(let i=0; i< queryParameters.length ;i++){
      if (queryParameters[i]=='Uniprotkb'){
        qUniProtKB=queryData[queryParameters[i]];
      } else if (queryParameters[i]=='organismid'){
        qOrgID=queryData[queryParameters[i]];
      } else if (queryParameters[i]=='pathwayid'){
        qPathWayID=queryData[queryParameters[i]];
      } else if (queryParameters[i]=='pathwayname'){
        qPathWayName=queryData[queryParameters[i]];
      }
    }
    if (qUniProtKB.trim().length <6 || qUniProtKB.trim() =='NA' || qOrgID.trim() !=='10090' || qOrgID.trim() =='NA' || !qPathWayID.includes('mmu')){
        this.spinner.hide();
        if(this.alertIsVisible){
          return;
        }
        this.alertIsVisible=true;
        setTimeout(()=>{
          this.alertIsVisible=false;
           this.router.navigate(['/']);
        },5000);
    } else {
      this._qmpkb.receiveDataFromBackendSearch('/pathwayviewapi/?Uniprotkb=' + qUniProtKB+
        '&organismid='+ qOrgID+
        '&pathwayid='+ qPathWayID+
        '&pathwayname='+ qPathWayName
        ).subscribe((response: any)=>{
        this.queryData=response;
        this.reachable =this.queryData.reachable;
        if (this.reachable != false){
          this.uniprotid=this.queryData.uniprotid;
          this.uniprotname=this.queryData.uniprotname;
          this.keggimagedict=this.queryData.keggimagedict;
          this.keggurl= this.queryData.keggurl;
          this.keggimagedictlen=Object.keys(this.keggimagedict).length;
          this.spinner.hide();
        } else {
          this.spinner.hide();
          if(this.alertIsVisible){
            return;
          }
          this.alertIsVisible=true;
          setTimeout(()=>{
            this.alertIsVisible=false;
             this.router.navigate(['/']);
          },5000);
          
        }

      }, error=>{
          this.errorStr = error;
      });
    }
  }
  ngOnInit() {
    this.getQuery();
  }

}<file_sep>/backend/src/qmpkbapp/summaryStat.py
#!/usr/bin/env.python
# -*- coding: utf-8 -*-
# encoding: utf-8
from __future__ import unicode_literals
from collections import Counter
from itertools import combinations
import ast
from operator import itemgetter
from summaryKeggCoverage import *
import operator
import json
import re
import itertools
from collections import OrderedDict
import datetime
from functools import partial

# function to generate stat based on user search result
def summaryStatcal(pepresult):
	specieslist=[]
	unqisostat=[]
	subcell={}
	godic={}
	diseasedic={}
	statKeggDic={}
	prodataseries={}
	pepseqdataseries={}
	strainData=[]
	bioMatData=[]
	noOfHumanOrtholog=0
	noOfDiseaseAssProt=0
	databaseNameList=['Peptide ID']
	pattern = re.compile(r"-\d+")
	mouseQuaReplace=('<br/>','|'),('<br>','|')
	utf8 = partial(unicode.encode, encoding="utf8")
	

	listOfSubcell=list((object['SubCellular'] for object in pepresult)) #reading subcellular data from result
	listOfSubcell=filter(None, listOfSubcell) #filter out empty value
	if len(listOfSubcell)>0:
		listOfSubcell=filter(lambda k: 'NA' != k.upper(), listOfSubcell) #filter out NA value
		if len(listOfSubcell)>0:
			subcellcount=Counter((('|'.join(listOfSubcell)).split('|'))) #split subcellular location then count the occurance
			tempsortedsubcell=OrderedDict(sorted(dict(subcellcount).items(), key=lambda x: x[1],reverse=True)) #sorting dictionary based on number of unique items in dict and reverse order
			listOfSubcell=(dict(itertools.islice(tempsortedsubcell.items(), 0, 50))).keys() # only top 50 restult will be displayed

	listOfSpecies=list((object['Organism'] for object in pepresult)) #reading organism data from result
	listOfSpecies=list(set(filter(None, listOfSpecies))) #filter out empty value

	listOfGoName=list((object['Mouse Go Name'] for object in pepresult)) #reading GO name data from result
	listOfGoName=filter(None, listOfGoName) #filter out empty value
	if len(listOfGoName)>0:
		listOfGoName=filter(lambda k: 'NA' != k.upper(), listOfGoName) #filter out NA value
		if len(listOfGoName)>0:
			listOfGoNamecount=Counter((('|'.join(listOfGoName)).split('|'))) #split data then count the occurance
			tempsortedgo=OrderedDict(sorted(dict(listOfGoNamecount).items(), key=lambda x: x[1],reverse=True)) #sorting dictionary based on number of unique items in dict and reverse order
			listOfGoName=(dict(itertools.islice(tempsortedgo.items(), 0, 50))).keys() # only top 50 restult will be displayed

	listOfKeggName=list((object['Mouse Kegg Pathway Name'] for object in pepresult)) #reading kegg data from result
	listOfKeggName=filter(None, listOfKeggName) #filter out empty value
	if len(listOfKeggName)>0:
		listOfKeggName=filter(lambda k: 'NA' != k.upper(), listOfKeggName) #filter out NA value
		if len(listOfKeggName)>0:
			listOfKeggNamecount=Counter((('|'.join(listOfKeggName)).split('|'))) #split data then count the occurance
			tempsortedkegg=OrderedDict(sorted(dict(listOfKeggNamecount).items(), key=lambda x: x[1],reverse=True)) #sorting dictionary based on number of unique items in dict and reverse order
			listOfKeggName=(dict(itertools.islice(tempsortedkegg.items(), 0, 20))).keys()# only top 20 restult will be displayed



	listOfHumanOrtholog=list((object['Human UniProtKB Accession'] for object in pepresult)) #reading human homolog data from result
	listOfHumanOrtholog=filter(None, listOfHumanOrtholog) #filter out empty value
	listOfHumanOrtholog=list(set(listOfHumanOrtholog))
	if 'NA' in listOfHumanOrtholog:
		listOfHumanOrtholog.remove('NA')
	noOfHumanOrtholog=len(listOfHumanOrtholog)
	

	listOfHumanAssocDis=list((object['Human Disease Name'] for object in pepresult)) #reading disease data from result
	listOfHumanAssocDis=filter(None, listOfHumanAssocDis) #filter out empty value
	listOfHumanAssocDis='|'.join(listOfHumanAssocDis)
	listOfHumanAssocDis=list(set(listOfHumanAssocDis.split('|')))
	if 'NA' in listOfHumanAssocDis:
		listOfHumanAssocDis.remove('NA')
	noOfDiseaseAssProt=len(listOfHumanAssocDis)
	if len(listOfHumanAssocDis)>0:
		listOfHumanAssocDiscount=Counter(listOfHumanAssocDis)
		tempsortedHumanDis=OrderedDict(sorted(dict(listOfHumanAssocDiscount).items(), key=lambda x: x[1],reverse=True)) #sorting dictionary based on number of unique items in dict and reverse order
		listOfHumanAssocDis=(dict(itertools.islice(tempsortedHumanDis.items(), 0, 20))).keys()# only top 20 restult will be displayed

	listOfBiomatrix=list((object['Biological Matrix'] for object in pepresult)) #reading tissues data from result
	listOfBiomatrix=filter(None, listOfBiomatrix) #filter out empty value
	listOfBiomatrix='|'.join(listOfBiomatrix)
	listOfBiomatrix=reduce(lambda a,kv: a.replace(*kv), mouseQuaReplace, listOfBiomatrix)
	listOfBiomatrix=list(set(listOfBiomatrix.split('|')))



	listOfStrain=list((object['Strain'] for object in pepresult)) #reading strain data from result
	listOfStrain=filter(None, listOfStrain) #filter out empty value
	listOfStrain='|'.join(listOfStrain)
	listOfStrain=reduce(lambda a,kv: a.replace(*kv), mouseQuaReplace, listOfStrain)
	listOfStrain=list(set(listOfStrain.split('|')))

	for i in listOfBiomatrix:
		subdatafilter=filter(lambda pepdata: str(i).strip().lower() in (str(pepdata["Biological Matrix"]).strip()).lower(), pepresult)
		subdataprot=list((object['UniProtKB Accession'] for object in subdatafilter))
		subdatapep=list((object['Peptide Sequence'] for object in subdatafilter))
		subdataprot=list(set([pattern.sub("", item) for item in subdataprot]))
		subdatapep=list(set([pattern.sub("", item) for item in subdatapep]))
		#bioMatData.append([i,len(subdataprot),len(subdatapep)])
		bioMatData.append([i,len(subdataprot)])

	for i in listOfStrain:
		subdatafilter=filter(lambda pepdata: str(i).strip().lower() in (str(pepdata["Strain"]).strip()).lower(), pepresult)
		subdataprot=list((object['UniProtKB Accession'] for object in subdatafilter))
		subdatapep=list((object['Peptide Sequence'] for object in subdatafilter))
		subdataprot=list(set([pattern.sub("", item) for item in subdataprot]))
		subdatapep=list(set([pattern.sub("", item) for item in subdatapep]))
		strainData.append([i,len(subdataprot),len(subdatapep)])

	for i in listOfSubcell:
		subdatafilter=filter(lambda pepdata: (str(i).strip()).lower() in (str(pepdata['SubCellular']).strip()).lower().split('|'), pepresult)
		subdata=list((object['UniProtKB Accession'] for object in subdatafilter))
		subcell[str(i).strip()]=len(list(set([pattern.sub("", item) for item in subdata])))

	for i in listOfSpecies:
		subdatafilter=filter(lambda pepdata: str(i).strip().lower() in (str(pepdata["Organism"]).strip()).lower(), pepresult)
		subdataprot=list((object['UniProtKB Accession'] for object in subdatafilter))
		subdatapep=list((object['Peptide Sequence'] for object in subdatafilter))
		subdataprot=list(set([pattern.sub("", item) for item in subdataprot]))
		subdatapep=list(set([pattern.sub("", item) for item in subdatapep]))
		specieslist.append([i,len(subdataprot),len(subdatapep)])

	for i in listOfKeggName:
		subdatafilter=filter(lambda pepdata: str(i).strip().lower() in (str(pepdata["Mouse Kegg Pathway Name"]).strip()).lower().split('|'), pepresult)
		subdata=list((object['UniProtKB Accession'] for object in subdatafilter))
		statKeggDic[str(i).strip()]=list(set([pattern.sub("", item) for item in subdata]))

	for i in listOfGoName:
		subdatafilter=filter(lambda pepdata: str(i).strip().lower() in (str(pepdata["Mouse Go Name"]).strip()).lower().split('|'), pepresult)
		subdata=list((object['UniProtKB Accession'] for object in subdatafilter))
		godic[str(i).strip()]=len(list(set([pattern.sub("", item) for item in subdata])))

	for i in listOfHumanAssocDis:
		subdatafilter=filter(lambda pepdata: str(i).strip().lower() in map(str,map(utf8,pepdata["Human Disease Name"].strip().lower().split('|'))), pepresult)
		subdata=list((object['UniProtKB Accession'] for object in subdatafilter))
		diseasedic[str(i).strip()]=len(list(set([pattern.sub("", item) for item in subdata])))

	for i in databaseNameList:
		subdatafilter=filter(lambda pepdata: ((str(pepdata[i]).strip()).lower() !='na' and len(str(pepdata[i]).strip()) >0), pepresult)
		subdataprot=list((object['UniProtKB Accession'] for object in subdatafilter))
		subdatapep=list((object['Peptide Sequence'] for object in subdatafilter))
		prodataseries[(str(i).strip()).split(' ')[0]]=list(set([pattern.sub("", item) for item in subdataprot]))
		pepseqdataseries[(str(i).strip()).split(' ')[0]]=list(set([pattern.sub("", item) for item in subdatapep]))

		isostatus=list((object['Present in isoforms'] for object in subdatafilter))

		unqstatus=list((object['Unique in protein'] for object in subdatafilter))
		tempcalunq='0.0%'
		tempcaliso='0.0%'
		if len(isostatus)>0:
			isostatus = map(lambda x: 'NA' if x.strip() == '' else x, isostatus)
			tempcaliso=str(100-(round((100.00-(float(isostatus.count('NA'))/float(len(isostatus)))*100),2)))+'%'
		if len(unqstatus)>0:
			tempcalunq=str(round(((float(unqstatus.count('Yes'))/float(len(unqstatus)))*100),2))+'%'
		unqisostat.append([(str(i).strip()).split(' ')[0],tempcalunq,tempcaliso])

	sortedKeggStatdic=OrderedDict(sorted(statKeggDic.items(), key=lambda x: len(x[1]), reverse=True))
	top10keggdict=dict(itertools.islice(sortedKeggStatdic.items(), 0, 10))
	keggchart=summarykeggcal(top10keggdict,prodataseries)

	statfinalresult={}
	statfinalresult['total']=[len(set(reduce(operator.concat, prodataseries.values()))),len(set(reduce(operator.concat, pepseqdataseries.values())))]
	statfinalresult['pepseqdataseries']=pepseqdataseries
	statfinalresult['prodataseries']=prodataseries
	statfinalresult['specieslist']=specieslist
	statfinalresult['unqisostat']=unqisostat
	statfinalresult['keggchart']=keggchart
	#statfinalresult['BioMat']=[['Biological Matrix','Total unique proteins','Total unique peptide']]+bioMatData
	statfinalresult['BioMat']=[['Biological Matrix','No. of assays']]+bioMatData
	statfinalresult['Strain']=[['Strain','Total unique proteins', 'Total unique peptide']]+strainData
	statfinalresult['noOfHumanortholog']=noOfHumanOrtholog
	statfinalresult['noOfDiseaseAssProt']=noOfDiseaseAssProt
	sortedGodic=OrderedDict(sorted(godic.items(), key=lambda x: x[1],reverse=True))

	sortedSubcelldic=OrderedDict(sorted(subcell.items(), key=lambda x: x[1],reverse=True))
	sortedDiseasedic=OrderedDict(sorted(diseasedic.items(), key=lambda x: x[1],reverse=True))

	statfinalresult['subcell']=[['SubCellular localization','No. of proteins covered']]+map(list,(sorted(list(sortedSubcelldic.items()),key=lambda l:l[1], reverse=True))[:10])
	statfinalresult['godic']=[['GO Term Name','No. of proteins covered']]+map(list,(sorted(sortedGodic.items(),key=lambda l:l[1], reverse=True))[:10])
	statfinalresult['disdic']=[['Disease Name','No. of proteins associated']]+map(list,(sorted(sortedDiseasedic.items(),key=lambda l:l[1], reverse=True))[:10])
	return statfinalresult<file_sep>/backend/src/qmkbdjangulardb/settings/store_password.py
SECRET_KEY = 'xxxxx'
EMAIL_HOST="smtp.gmail.com"
DEFAULT_FROM_EMAIL = '<EMAIL>'
DJANGO_ADMIN_USERNAME="xxxxx"
DJANGO_ADMIN_PASSWORD="<PASSWORD>"


EMAIL_HOST_USER="<EMAIL>"
EMAIL_HOST_PASSWORD="<PASSWORD>"<file_sep>/client/qmpkb-app/src/app/peptideuniqueness/peptideuniqueness.component.ts
import { Component, OnInit, OnDestroy, ViewChild} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var require: any
declare var jquery: any;


@Component({
  selector: 'app-peptideuniqueness',
  templateUrl: './peptideuniqueness.component.html',
  styleUrls: ['./peptideuniqueness.component.css']
})
export class PeptideuniquenessComponent implements OnInit  {
  private routeSub:any;
  dtOptions: any = {};
  pepunqdata:any;
  errorStr:Boolean;
  reachable:Boolean;
  queryData:any;
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { }

  ngOnInit() {
    this.spinner.show();
    this.location.go('/peptideuniqueness/')
    this.queryData=this._qmpkb.queryStorage;
    this.pepunqdata=JSON.parse(this.queryData.pepunqdata)
    this.reachable=this.queryData.reachable
    this.dtOptions = {
      data: this.pepunqdata.data,
      columns: [
         {   title: 'Show Highlighted Peptide Sequence',
             className: 'details-control',
             orderable: false,
             data: null,
             defaultContent: '',
             render: function () {
                 return '<i class="fa fa-plus-square" aria-hidden="true"></i>';
             },
             width:"15px"
         },
         { 
           title: 'Protein ID',
           data: "proteinID" 
         },
         { 
           title: 'Peptide Sequence',
           data: "peptideSequence" 
         },
         {
           title: 'Start',
           data: "start"
         },
         {
           title: 'End',
           data: "end"
         },
         {
           title: 'Sequence Length',
           data: "seqlen"
         },
         { 
           title: 'Peptide unique in protein',
           data: "peptideuniqueinprotein"
         },
         {
           title: 'Data source',
           data: "datasource"
         }
      ],
      autoWidth:true
    };
    this.spinner.hide();
  }

  private format(d){     
   // `d` is the original data object for the row
   return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
       '<tr>' +
           '<td>Fasta:</td>' +
           '<td>' + d.highlightedpepseq + '</td>' +
       '</tr>' +
   '</table>';  
  }

  ngAfterViewInit(): void {

    const self = this;
    this.datatableElement.dtInstance.then(table => {
       // Add event listener for opening and closing details
       $('#pepUnqness tbody').on('click', 'td.details-control', function () {
           var tr = $(this).closest('tr');
           var tdi = tr.find("i.fa");
           var row = table.row(tr);

           if (row.child.isShown()) {
               // This row is already open - close it
               row.child.hide();
               tr.removeClass('shown');
               tdi.first().removeClass('fa-minus-square');
               tdi.first().addClass('fa-plus-square');
           }
           else {
               // Open this row
               row.child(self.format(row.data())).show();
               tr.addClass('shown');
               tdi.first().removeClass('fa-plus-square');
               tdi.first().addClass('fa-minus-square');
           }
       });

       table.on("user-select", function (e, dt, type, cell, originalEvent) {
           if ($(cell.node()).hasClass("details-control")) {
               e.preventDefault();
           }
       });
    }); 
   
  }


}



<file_sep>/client/qmpkb-app/src/app/detail-information/detail-information.component.ts
import { Component, OnInit, OnDestroy, ViewChild, Renderer, HostListener} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";
declare var jquery: any;

@Component({
  selector: 'app-detail-information',
  templateUrl: './detail-information.component.html',
  styleUrls: ['./detail-information.component.css']
})
export class DetailInformationComponent implements OnInit {
  loadQuery:any;
  dtOptionsortholog:any ={};
  dtOptionsSubCell: any = {};
  dtOptionsDisease: any = {};
  dtOptionsDrugBank: any = {};
  diseaseQuery:any;
  errorStr:Boolean;
  proteinName:any;
  geneName:any;
  uniprotkb:any;
  foundHits:number;
  orthologData:any;
  subcell:any;
  subcellArray:any;
  subCellQuery:any;
  humanDiseaseUniProt:any;
  humanDiseaseDisGeNet:any;
  drugBankData:any;
  drugbankQuery:any;
  drugBankDataArray:any;
  queryData:any;
  plotlyData:any=[];
  screenWidth:any;
  lenOfGeneExpData:any;
  goUniProtKB:any;
  geneExpUniProtKB:any;
  protVistaUniProtKB:any;
  assayQuery:any;
  concenQuery:any;
  resultFilePath:any;
  fastafilename:any;
  pathwayQueryTerm:any;
  orgID:any;
  filterredDrugBankData:any;
  filterredSubcell:any;
  filterDrugBankDataStatus=false;
  filterSubCellStatus=false;
  qsideBar:string;
  sideBarLink:string;
  strainStat:number;
  bioMatStat:number;
  assayStat:number;
  availableOtherAssayStatus=0;

  public alertIsVisible:boolean= false;

  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;


  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=(window.innerWidth-50)+"px";
  }

  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService,
    private renderer: Renderer,
    ) { 
      this.getScreenSize();
  }

  async  getQuery(){
    await this.route.queryParams.subscribe(params=>{
      this.loadQuery =params;
      if (Object.keys(this.loadQuery).length > 0){
        this.spinner.show();
        setTimeout(() => {
          this.getProteinData(this.loadQuery);
        }, 100); 
      } else {
        this.spinner.hide();
        if(this.alertIsVisible){
          return;
        }
        this.alertIsVisible=true;
        setTimeout(()=>{
          this.alertIsVisible=false;
          this.router.navigate(['/']);
        },5000);
      }
    })
  }
  getProteinData(queryData:any){
    const queryParameters=Object.keys(this.loadQuery);
    let qUniProtKB='NA';
    let qresultID='NA';
    let qseqID='NA';
    for(let i=0; i< queryParameters.length ;i++){
      if (queryParameters[i]=='uniProtKb'){
        qUniProtKB=queryData[queryParameters[i]];
      } else if (queryParameters[i]=='resultID'){
        qresultID=queryData[queryParameters[i]];
      } else if (queryParameters[i]=='seqID'){
        qseqID=queryData[queryParameters[i]];
      }
    }
    if (this.router.url.includes('#')){
      this.qsideBar=this.router.url.split('#')[1];
      this.sideBarLink=this.router.url.split('#')[0].split('?')[1];
    } else{
      this.qsideBar='NA';
      this.sideBarLink=this.router.url.split('?')[1];
    }
    if (qUniProtKB.trim().length <6 || qUniProtKB.trim() =='NA'){
        this.spinner.hide();
        if(this.alertIsVisible){
          return;
        }
        this.alertIsVisible=true;
        setTimeout(()=>{
          this.alertIsVisible=false;
           this.router.navigate(['/']);
        },5000);
    } else {
      this._qmpkb.receiveDataFromBackendSearch('/detailinformationapi/?uniProtKb=' + qUniProtKB+'&fileName='+ qresultID +'&fastafilename='+qseqID).subscribe((response: any)=>{
        this.queryData=response;
        this.foundHits=this.queryData.foundHits;
        if (this.foundHits > 0){
            this.resultFilePath=this.queryData.resultFilePath;
            this.proteinName=this.queryData.proteinName;
            this.geneName=this.queryData.geneName;
            this.uniprotkb=this.queryData.uniprotkb;
            this.orthologData=this.queryData.orthologData;
            this.subcellArray=this.queryData.subcell;
            this.subcell=this.queryData.subcell.join("; ");
            this.subCellQuery={
              subcell:this.subcell,
              subcellArray:this.subcellArray
            }
            this.humanDiseaseUniProt=this.queryData.humanDiseaseUniProt;
            this.humanDiseaseDisGeNet=this.queryData.humanDiseaseDisGeNet;
            this.drugBankDataArray=this.queryData.drugBankData;
            this.drugBankData=this.queryData.drugBankData.join("; ");
            this.drugbankQuery={
              drugBankDataArray:this.drugBankDataArray,
              drugBankData:this.drugBankData
            }
            this.fastafilename=this.queryData.fastafilename;
            this.goUniProtKB=this.uniprotkb;
            this.geneExpUniProtKB=this.uniprotkb;
            this.protVistaUniProtKB=this.uniprotkb;
            this.orgID=this.queryData.orgID;
            this.assayQuery=this.uniprotkb+'|'+this.resultFilePath+'|'+this.fastafilename;
            this.concenQuery=this.uniprotkb+'|'+this.resultFilePath;
            this.pathwayQueryTerm=this.uniprotkb;
            this.diseaseQuery={
              humanDiseaseUniProt:this.humanDiseaseUniProt,
              humanDiseaseDisGeNet:this.humanDiseaseDisGeNet

            }
            if(this.orthologData[0].pepPresentInHumanortholog == 'No' && this.orthologData[0].availableAssayInHumanortholog !='NA') {
              this.availableOtherAssayStatus=1;
            }
            this.assayStat=this.queryData.assayStat;
            this.bioMatStat=this.queryData.bioMatStat;
            this.strainStat=this.queryData.strainStat;
            let datatableElement = this.datatableElement;
            this.dtOptionsortholog = {
               searching: false,
               info: false,
               ordering: false,
               paging: false,
               autoWidth:true 
            };
            if (!this.router.url.includes('#')){
              this.spinner.hide();
            }
            
        } else {
          this.spinner.hide();
          if(this.alertIsVisible){
            return;
          }
          this.alertIsVisible=true;
          setTimeout(()=>{
            this.alertIsVisible=false;
             this.router.navigate(['/']);
          },5000);
          
        }

      }, error=>{
          this.errorStr = error;
      });
    }
  }
  ngOnInit() {
    this.getQuery();
    if (this.router.url.includes('#')){
      const link=this.router.url.split('#')[1];
      if (link.length >0){
          this.preCSS(link);
      }
    }
  }


 preCSS(hashLink:any):void {
    var self= this;
    setTimeout(()=>{
      if ($('#'+hashLink).length){
        $('#'+hashLink).css({'padding-top':'51px'});
        location.href=self.router.url;
        this.spinner.hide();
      }

    },2000);
/*    if (hashLink=='subcell' || hashLink=='pathway' || hashLink=='go' || hashLink=='disease' || hashLink=='drug'){
      setTimeout(()=>{
        if ($('#'+hashLink).length){
          $('#'+hashLink).css({'padding-top':'51px'});
          location.href=self.router.url;
          this.spinner.hide();
        }

      },5000);

    } else{
      setTimeout(()=>{
        if ($('#'+hashLink).length){
          $('#'+hashLink).css({'padding-top':'51px'});
          location.href=self.router.url;
          this.spinner.hide();
        }

      },2000);
    }*/
 }

  gethref(evt, linkName) {
      const hrefIDArray=['protein','assay','concentration','genExp','protvista','subcell','pathway','go','disease','drug']
      $('#'+linkName).css({'padding-top':'51px'});
      for(let i=0; i<hrefIDArray.length;i++){
        if(hrefIDArray[i] !==linkName){
          $('#'+hrefIDArray[i]).css({'padding-top':''});
        }
      }
  }
}
<file_sep>/client/qmpkb-app/src/app/result-page-user-seq/result-page-user-seq.component.ts
import { Component, OnInit, OnDestroy, ViewChild, Renderer,HostListener,Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { DataTableDirective } from 'angular-datatables';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { Subject } from 'rxjs';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import { NgxSpinnerService } from 'ngx-spinner';
import * as Plotly from 'plotly.js';
import * as $ from "jquery";

declare var jquery: any;
declare let google: any;

@Component({
  selector: 'app-result-page-user-seq',
  templateUrl: './result-page-user-seq.component.html',
  styleUrls: ['./result-page-user-seq.component.css']
})
export class ResultPageUserSeqComponent implements OnInit,OnDestroy {
  dtOptions: any = {};
  dtOptionssummarystatUnq:any={};
  dtOptionsOther:any={};
  queryResPath: string;
  private routeSub:any;
  private req:any;
  errorStr:Boolean;
  uniprotacc:string;
  fileDownloadUrl;
  totallist:any;
  unqisostat:any;
  subcell:any;
  humandisease:any;
  querystrainData:any;
  querybioMatData:any;
  querynoOfDiseaseAssProt:any;
  querynoOfHumanOrtholog:any;
  updatedgo:any;
  keggchart:any;
  foundHits:number;
  fastafilename:any;
  queryData:any;

  mProtVal:any;
  mGenVal:any;
  mUKBVal:any;
  mPepassVal:any;
  mStrVal:any;
  mKoutVal:any;
  mBioTisVal:any;
  mGenderVal:any;
  mGenExpVal:any;
  hProtVal:any;
  hUKBVal:any;
  hPresPepVal:any;
  mSCellVal:any;
  mPathVal:any;
  hDisVal:any;
  mGOVal:any;
  hDrugVal:any;

  query: string;

  screenWidth:any;
  plotlyData:any=[];
  plotDataUnit: string;
  userQueryFastaResult:any;
  downloadResultQuery:any;

  @ViewChild(DataTableDirective)

  datatableElement: DataTableDirective;

  plotDataOptions=[
       {num:0, name:'Concentration Data'},
       {num:1, name:'Log2(Concentration Data)'},
       {num:2, name:'Log10(Concentration Data)'},
  ];
  selectedLevel=this.plotDataOptions[0];

  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=(window.innerWidth-50)+"px";
  }

  constructor(
  private route: ActivatedRoute,
  private location: Location,
  private http: HttpClient,
  private renderer: Renderer,
  private router: Router,
  private _qmpkb:QmpkbService,
  private spinner: NgxSpinnerService,
  ){ 
      this.getScreenSize();
  }
  @Input()
  set resultFastaTermQuery(resultFastaQuery:any){
      this.userQueryFastaResult=resultFastaQuery;

  }
  ngOnInit() {
    this.spinner.show();
    //this.location.go('/resultsseq/')
    this.queryData=this.userQueryFastaResult;
    this.query = this.queryData.searchterm;
    this.queryResPath=this.queryData.filepath;
    this.totallist=this.queryData.totallist;
    this.unqisostat=this.queryData.unqisostat;
    this.subcell=this.queryData.subcell;
    this.humandisease=this.queryData.humandisease;
    this.querystrainData=this.queryData.querystrainData;
    this.querybioMatData=this.queryData.querybioMatData;
    this.querynoOfDiseaseAssProt=this.queryData.querynoOfDiseaseAssProt;
    this.querynoOfHumanOrtholog=this.queryData.querynoOfHumanOrtholog;
    this.updatedgo=this.queryData.updatedgo;
    this.keggchart=this.queryData.keggchart;
    this.foundHits=this.queryData.foundHits;
    this.fastafilename=this.queryData.fastafilename;
    this.downloadResultQuery=this.queryResPath+'|Fasta';

    this.barplot(this.querybioMatData,this.querystrainData,this.subcell,this.updatedgo,this.humandisease);

    let destPath='fileapi/resultFile/jsonData/resultJson/'+this.queryResPath;
    let queryfastafilename=this.fastafilename;
    //let destPath='assets/'+this.queryResPath
    let detailResFile=this.queryResPath.split('/')[2].split('_search')[0];
    let datatableElement = this.datatableElement;
    this.dtOptions = {
      processing: true,
      serverSide: false,
      orderCellsTop: true,
      fixedHeader: true,
      pageLength: 10,
      pagingType: 'full_numbers',
      ajax: destPath,
      columns: [
        { 
          title: 'Protein',
          render: function (data, type, row) {
            if ((row["Protein"].trim()).length > 0){
              return row["Protein"].trim();
            } else {
              return 'NA';
            }
          }
        },
        { 
          title: 'Gene',
          data: 'Gene'
        },
        { 
          title: 'UniProtKB accession',
          render: function (data, type, row) {
            return '<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#protein">' + row["UniProtKB Accession"].trim() + '</a>';
          }
        },
        { 
          title: 'Peptide assay',
          className: 'details-control-pep',
          orderable: true,
          data: null,
          defaultContent: '',
          render: function (data: any, type: any, row: any, meta) {
            if (row["Peptide Sequence"].trim().length > 0 ){
              const tempPepseq=row["Peptide Sequence"].trim();
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#assay"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const temprowdata=[tempPepseq,tempURL];
              return temprowdata.join("<br>");
            } else {
              ('<font color="black">No</font>');
            }
          },
          width:"15px"
        },
        { 
          title: 'Strain',
          className: 'details-control-strainCol',
          orderable: true,
          data: null,
          defaultContent: '',
          render: function (data, type, row) {
            if ((row["Strain"].trim()).length > 0 && (row["Strain"].trim()) != "NA"){
              const array =(row["Strain"].trim()).split('|');
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#concentration"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const temprowdata=[array.join("<br>"),tempURL];
              return temprowdata.join("<br>");
            } else {
              return ('<font color="black">NA</font>');
            }
          },
          width:"15px"
        },
        { 
          title: 'Mutant',
          className: 'details-control-knockoutCol',
          orderable: true,
          data: null,
          defaultContent: '',
          render: function (data, type, row) {
            if ((row["Knockout"].trim()).length > 0 && (row["Knockout"].trim()) != "NA"){
              const array =(row["Knockout"].trim()).split(';');
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#concentration"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const temprowdata=[array.join("<br>"),tempURL];
              return temprowdata.join("<br>");
            } else {
              return ('<font color="black">NA</font>');
            }
          },
          width:"15px"
        },
        { 
          title: 'Biological matrix',
          className: 'details-control-biomatrix',
          orderable: true,
          data: null,
          defaultContent: '',
          render: function (data: any, type: any, row: any, meta) {
            if (row["Biological Matrix"].trim() != "NA" ){
               const tempbiomat=row["Biological Matrix"].trim();
               const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#concentration"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
               const temprowdata=[tempbiomat,tempURL];
               return temprowdata.join("<br>");
            } else {
              return ('<font color="black">NA</font>');
            }
          },
           width:"15px"
        },
        { 
          title: 'Sex',
          className: 'details-control-sexCol',
          orderable: true,
          data: null,
          defaultContent: '',
          render: function (data, type, row) {
            if ((row["Sex"].trim()).length > 0 && (row["Sex"].trim()) != "NA"){
              const array =(row["Sex"].trim()).split('|');
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#concentration"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const temprowdata=[array.join("<br>"),tempURL];
              return temprowdata.join("<br>");
            } else {
              return ('<font color="black">NA</font>');
            }
          },
          width:"15px"
        },
        { 
          title: 'Gene expression',
          className: 'details-control-expCol',
          orderable: true,
          data: null,
          defaultContent: '',
          render: function (data, type, row) {
            if ((row["Gene Expression View"].trim()).length > 0 && (row["Gene Expression View"].trim()) != "No"){
                const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#genExp">....more</a>';
                const tempdata=row["Gene Expression View"].trim();
                //const temprowdata=[tempdata,tempURL];
                const temprowdata=[tempURL];
                return temprowdata.join("<br>");
            } else {
              return 'No';
            }
          },
          width:"15px"
        },
        { 
          title: 'Human ortholog',
          render: function (data, type, row) {
            if ((row["Human ProteinName"].trim()).length > 0 && (row["Human ProteinName"].trim()) != "NA"){
              const array =(row["Human ProteinName"].trim()).split('|');
              return array.join("<br>");
            } else {
              return 'NA';
            }
          }
        },
        { 
          title: 'UniProtKB accession human ortholog',
          render: function (data, type, row) {
            if ((row["Human UniProtKB Accession"].trim()).length > 0 && (row["Human UniProtKB Accession"].trim()) != "NA"){
              const array =(row["Human UniProtKB Accession"].trim()).split(',');
              array.forEach(function(element, index) {
              array[index] = '<a target="_blank" routerLinkActive="active" href="https://www.uniprot.org/uniprot/' + element+'">'+element+ '</a>';
              });
              return array.join("<br>");
            } else {
              return 'NA';
            }
          }
        },
        { 
          title: 'Peptide present in human ortholog',
          render: function (data, type, row) {
            return row["Present in human ortholog"];
          }
        },
        { 
          title: 'Subcellular localization',
          render: function (data, type, row) {
            if ((row["SubCellular"].trim()).length > 0){
              return (row["SubCellular"].trim()).split('|').join("<br>");
            } else {
              return 'NA';
            }
          }
        },
        { 
          title: 'Involvement in pathways',
          render: function (data, type, row) {
            if ((row["Mouse Kegg Pathway Name"].trim()).length > 0 && (row["Mouse Kegg Pathway Name"].trim()) != "NA"){
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#pathway"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const tempdata=(row["Mouse Kegg Pathway Name"].trim()).split("|").slice(0, 3).join("<br>");
              const temprowdata=[tempdata,tempURL];
              return temprowdata.join("<br>");
            } else {
              return 'NA';
            }
            
          }
        },
        { 
          title: 'Go term associations',
          render: function (data, type, row) {
            if ((row["Mouse Go Name"].trim()).length > 0 && (row["Mouse Go Name"].trim()) != "NA"){
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#go"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const tempdata=(row["Mouse Go Name"].trim()).split("|").slice(0, 3).join("<br>");
              const temprowdata=[tempdata,tempURL];
              return temprowdata.join("<br>");
            } else {
              return 'NA';
            }

          }
        },
        { 
          title: 'Involvement in disease',
          render: function (data, type, row) {
            if ((row["Human Disease Name"].trim()).length > 0 && (row["Human Disease Name"].trim()) != "NA"){
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#disease"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';
              const tempdata=(row["Human Disease Name"].trim()).split("|").slice(0, 3).join("<br>");
              const temprowdata=[tempdata,tempURL];
              return temprowdata.join("<br>");
            } else {
              return 'NA';
            }
            
          }
        }, 
        { 
          title: 'Drug associations',
          render: function (data, type, row) {
            if ((row["Human Drug Bank"].trim()).length > 0 && (row["Human Drug Bank"].trim()) != "NA"){
              const tempURL ='<a target="_blank" routerLinkActive="active" href="/detailinformation?uniProtKb=' + row["UniProtKB Accession"].trim() + '&resultID=' + detailResFile +'&seqID=' + queryfastafilename +'#drug"><i class="fa fa-plus-square" aria-hidden="true"></i></a>';              
              const tempdata=(row["Human Drug Bank"].trim()).split('|').slice(0, 3).join("<br>");
              const temprowdata=[tempdata,tempURL];
              return temprowdata.join("<br>");

            }else {
              return 'NA';
            }
          }
        },
        { 
          title: 'Search Pathway(s) Mouse',
          className: 'noVis',
          render: function (data, type, row) {
            if ((row["Mouse Kegg Pathway Name"].trim()).length > 0 && (row["Mouse Kegg Pathway Name"].trim()) != "NA"){
              const tempdata=(row["Mouse Kegg Pathway Name"].trim()).split("|").join("<br>");
              return tempdata;
            } else {
              return 'NA';
            }
            
          },
          visible:false
          
        },
        { 
          title: 'Search Go Term Name-Mouse',
          className: 'noVis',
          render: function (data, type, row) {
            if ((row["Mouse Go Name"].trim()).length > 0 && (row["Mouse Go Name"].trim()) != "NA"){
              const tempdata=(row["Mouse Go Name"].trim()).split("|").join("<br>");
              return tempdata;
            } else {
              return 'NA';
            }

          },
          visible:false
        },
        { 
          title: 'Search Involvement in disease-ortholog',
          className: 'noVis',
          render: function (data, type, row) {
            if ((row["Human Disease Name"].trim()).length > 0 && (row["Human Disease Name"].trim()) != "NA"){
              const tempdata=(row["Human Disease Name"].trim()).split("|").join("<br>");
              return tempdata;
            } else {
              return 'NA';
            }
            
          },
          visible:false
        },              
        { 
          title: 'Search Drug Bank-ortholog',
          className: 'noVis',
          render: function (data, type, row) {
            if ((row["Human Drug Bank"].trim()).length > 0 && (row["Human Drug Bank"].trim()) != "NA"){
              const tempdata=(row["Human Drug Bank"].trim()).split('|').join("<br>");
              return tempdata;
            }else {
              return 'NA';
            }
          },
          visible:false
        }      
      ], 
      scrollX:true,
      scrollY:'650px',
      scrollCollapse:true,
      // Declare the use of the extension in the dom parameter
      dom: 'lBrtip',
      // Configure the buttons
      buttons: [
        {
          extend:'colvis',
          columns:':not(.noVis)'
        }
      ],
      autoWidth:true
    };
    if (Object.keys(this.keggchart).length >0 ){
      this.drawChart(this.keggchart);
    }
    this.dtOptionssummarystatUnq = {
        searching: false,
        info: false,
        ordering: false,
        paging: false,
        autoWidth:true  
    };
    this.dtOptionsOther = {
      order:[[1,'desc']],
      autoWidth:true
    };
    this.spinner.hide();

  }

    ngAfterViewInit(): void {

    const self = this;
    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
      dtInstance.columns().every(function () {
      const that = this;
      $( 'table thead'  ).on( 'keyup', ".column_search",function () {
        let colIndex:any;
        colIndex=$(this).parent().index();
        console.log(colIndex,this['value']);
        if (colIndex == 13){
            self.datatableElement['dt'].columns( 17 ).search(this['value']).draw();
        } else if (colIndex == 14){
            self.datatableElement['dt'].columns( 18 ).search(this['value']).draw();
        } else if (colIndex == 15){
            self.datatableElement['dt'].columns( 19 ).search(this['value']).draw();
        } else if (colIndex == 16){
            self.datatableElement['dt'].columns( 20 ).search(this['value']).draw();
        } else {
            self.datatableElement['dt'].columns( colIndex ).search(this['value']).draw();
        } 
      });
      });
    });

  }

    drawChart(keggchart) {
      const self = this;
      google.charts.load('current', {packages: ['corechart', 'bar']});
      google.charts.setOnLoadCallback(drawKeggChart);

      function drawKeggChart() {
         var tempdatakegg=keggchart;
           var dataPlot = google.visualization.arrayToDataTable(tempdatakegg);
           const options = {
              'height':400,
              bar: {groupWidth: "100%"},
              legend: {position: 'none'},
              hAxis: {
                title: 'No. of proteins covered',
                 minValue: 0,
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              axes: {
                  x: {
                    0: { side: 'top'}
                  }
              },
              vAxis: {
                title: 'KEGG pathway',
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              bars: 'horizontal'
            };
            const chart = new google.charts.Bar(document.getElementById('chart_div_pathway'));
            const container = document.getElementById('chart_div_pathway');
            var axislabels:any=[];
            google.visualization.events.addListener(chart, 'onmouseover', uselessHandler);
            
            function uselessHandler() {
              $('#chart_div_pathway path').css('cursor','pointer')
              $('#chart_div_pathway text').css('cursor','pointer')
             }
            
              google.visualization.events.addListener(chart, 'select', selectHandler);
              google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
              google.visualization.events.addListener(chart, 'onmouseout', onmouseoutHandler);
       
             // use the 'ready' event to modify the chart once it has been drawn
            google.visualization.events.addListener(chart, 'ready', function () {
              axislabels = container.getElementsByTagName('text');
             });
       
       
             function selectHandler(e) {
              var selection = chart.getSelection();
                if (selection.length > 0) {
                  var colLabelSelect = dataPlot.getColumnLabel(selection[0].column);
                  var mydataSelect= dataPlot.getValue(selection[0].row,0);
                  var tempGoogleDataURL='/dataload/googleChartData_'+mydataSelect+'_keggPathway';
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();                  
                  //window.open(tempGoogleDataURL,'_blank');
                  self.mPathVal=mydataSelect;
                  self.datatableElement['dt'].columns( 17 ).search(mydataSelect).draw();               
                  chart.setSelection([])
               }
             }        
            
             function onmouseoverHandler(propertiesOver) {
              var hooverOverSelection= propertiesOver;
              if (Object.keys(hooverOverSelection).length > 0 && typeof hooverOverSelection.column !== "undefined") {
                var colLabelOver=dataPlot.getColumnLabel(hooverOverSelection.column);
                  var mydataOver =dataPlot.getValue(hooverOverSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOver) {
                      axislabels[i].setAttribute('font-weight', 'bold');
                    }
                  }
              }
             }
          
             function onmouseoutHandler(propertiesOut) {
              var hooverOutSelection= propertiesOut;
              if (Object.keys(hooverOutSelection).length > 0 && typeof hooverOutSelection.column !== "undefined") {
                  var mydataOut =dataPlot.getValue(hooverOutSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOut) {
                      axislabels[i].removeAttribute('font-weight', 'bold');
                    }
                  }
              }
             }
          
            container.addEventListener('click', clickHandlerLabel);
            container.addEventListener("mouseover", mouseOverLabel);
            container.addEventListener("mouseout", mouseOutrLabel);
         
            function mouseOverLabel(propertiesLabel) {
             if (propertiesLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesLabel.target.textContent) {
                        axislabels[i].setAttribute('font-weight', 'bold');
                        const findArray =tempdatakegg.filter(p => p[0] == propertiesLabel.target.textContent);
                        var textY=propertiesLabel.target.getAttribute("y");
                        var textX=propertiesLabel.target.getAttribute("x");
                        var customTextToolTip='<b>'+propertiesLabel.target.textContent+'</b>'+'<br>'+tempdatakegg[0][1]+':'+'<br>'+findArray[0][1];                        
                        var bars = container.getElementsByTagName('path');
                        for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesLabel.target.textContent){
                            bars[j].setAttribute('fill','#3871cf');
                            $('.tooltiptextLabel').css('visibility','visible');
                            $('.tooltiptextLabel').css('position', 'absolute');
                            $('.tooltiptextLabel').css('top',textY+'px');
                            $('.tooltiptextLabel').css('left',textX+'px');
                            $('.tooltiptextLabel').html(customTextToolTip);  
                          }
                        }
                    }
              }
          }
             }
            function mouseOutrLabel(propertiesOutLabel) {
             if (propertiesOutLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesOutLabel.target.textContent) {
                       axislabels[i].removeAttribute('font-weight', 'bold');
                       var bars = container.getElementsByTagName('path');
                       for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesOutLabel.target.textContent){
                            bars[j].setAttribute('fill','#4285f4');
                            $('.tooltiptextLabel').html('');
                            $('.tooltiptextLabel').css('visibility','hidden');
                            $('.tooltiptextLabel').css('top',0);
                            $('.tooltiptextLabel').css('left',0);

                          }
                       }
                    }
                
                  }
            }
         }  
      
           function clickHandlerLabel(e) {
            if (e.target.tagName === 'text') {
              const findArray =tempdatakegg.filter(p => p[0] == e.target.textContent);
              if (typeof findArray[0] != "undefined"){
                if (tempdatakegg.indexOf(findArray[0])){
                    var tempGoogleDataURL='/dataload/googleChartData_'+e.target.textContent+'_keggPathway';
                    $('tfoot input').val('');
                    self.datatableElement['dt'].columns().search('').draw();
                    self.datatableElement['dt'].search('').draw();                    
                    self.mPathVal=e.target.textContentt;
                    self.datatableElement['dt'].columns( 17 ).search(e.target.textContent).draw();                  
                      //window.open(tempGoogleDataURL,'_blank');

                }
              }
            }
           }
             chart.draw(dataPlot, google.charts.Bar.convertOptions(options));
          }
          $(document).ready(function() {
            $(window).resize(function() {
              drawKeggChart();
            })
          })

    }

    barplot(matrixData:any,mouseStrainData:any,subCellData:any,goData:any,humanDiseaseData:any):void {
      const self = this;

      google.charts.load('current', {packages: ['bar']});
      google.charts.setOnLoadCallback(drawMatrixChart);
      google.charts.setOnLoadCallback(drawStrainChart);
      google.charts.setOnLoadCallback(drawSubCellChart);
      google.charts.setOnLoadCallback(drawGOChart);
      google.charts.setOnLoadCallback(drawDisChart);

      function drawMatrixChart() {
         var tempdatamatrix=matrixData;
         var dataPlot = google.visualization.arrayToDataTable(tempdatamatrix);
         const options = {
              'height':400,
              bar: {groupWidth: "100%"},
              legend: {position: 'none'},
              hAxis: {
                title: 'No. of assays',
                 minValue: 0,
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              vAxis: {
                title: 'Biological Matrix',
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              bars: 'horizontal'
           };
           const chart = new google.charts.Bar(document.getElementById('chart_div_matrix'));
            
             const container = document.getElementById('chart_div_matrix');
             var axislabels:any=[];
             google.visualization.events.addListener(chart, 'onmouseover', uselessHandler);
            
             function uselessHandler() {
              $('#chart_div_matrix path').css('cursor','pointer')
              $('#chart_div_matrix text').css('cursor','pointer')
            }
            
             google.visualization.events.addListener(chart, 'select', selectHandler);
             google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
             google.visualization.events.addListener(chart, 'onmouseout', onmouseoutHandler);
       
            // use the 'ready' event to modify the chart once it has been drawn
           google.visualization.events.addListener(chart, 'ready', function () {
              axislabels = container.getElementsByTagName('text');
            });
       
       
            function selectHandler(e) {
              var selection = chart.getSelection();
                if (selection.length > 0) {
                  var colLabelSelect = dataPlot.getColumnLabel(selection[0].column);
                  var mydataSelect= dataPlot.getValue(selection[0].row,0);
                  var tempGoogleDataURL='/dataload/googleChartData_'+mydataSelect+'_biologicalMatrix';
                  //window.open(tempGoogleDataURL,'_blank');
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();                  
                  self.mBioTisVal=mydataSelect;
                  self.datatableElement['dt'].columns( 6 ).search(mydataSelect).draw();                 
                  chart.setSelection([]);
               }
            }        
            
            function onmouseoverHandler(propertiesOver) {
              var hooverOverSelection= propertiesOver;
              if (Object.keys(hooverOverSelection).length > 0 && typeof hooverOverSelection.column !== "undefined") {
                var colLabelOver=dataPlot.getColumnLabel(hooverOverSelection.column);
                  var mydataOver =dataPlot.getValue(hooverOverSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOver) {
                      axislabels[i].setAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
            function onmouseoutHandler(propertiesOut) {
              var hooverOutSelection= propertiesOut;
              if (Object.keys(hooverOutSelection).length > 0 && typeof hooverOutSelection.column !== "undefined") {
                  var mydataOut =dataPlot.getValue(hooverOutSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOut) {
                      axislabels[i].removeAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
           container.addEventListener('click', clickHandlerLabel);
           container.addEventListener("mouseover", mouseOverLabel);
           container.addEventListener("mouseout", mouseOutrLabel);
         
           function mouseOverLabel(propertiesLabel) {
             if (propertiesLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesLabel.target.textContent) {
                        axislabels[i].setAttribute('font-weight', 'bold');
                        const findArray =tempdatamatrix.filter(p => p[0] == propertiesLabel.target.textContent);
                        var textY=propertiesLabel.target.getAttribute("y");
                        var textX=propertiesLabel.target.getAttribute("x");
                        var customTextToolTip='<b>'+propertiesLabel.target.textContent+'</b>'+'<br>'+tempdatamatrix[0][1]+':'+'<br>'+findArray[0][1]+'<br>'+tempdatamatrix[0][2]+':'+'<br>'+findArray[0][2];                    
                        var bars = container.getElementsByTagName('path');
                        for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesLabel.target.textContent){
                            bars[j].setAttribute('fill','#3871cf');
                            $('.tooltiptextLabel').css('visibility','visible');
                            $('.tooltiptextLabel').css('position', 'absolute');
                            $('.tooltiptextLabel').css('top',textY+'px');
                            $('.tooltiptextLabel').css('left',textX+'px');
                            $('.tooltiptextLabel').html(customTextToolTip);                              
                          }
                        }
                        //this block of code for proteins and peptide              
/*                        for(var j = 0; j<bars.length; j+=2){
                          if(dataPlot.getValue(j/2,0) == propertiesLabel.target.textContent){
                            bars[j].setAttribute('fill','#3871cf');
                            bars[j+1].setAttribute('fill','#ba3a2f');
                            $('.tooltiptextLabel').css('visibility','visible');
                            $('.tooltiptextLabel').css('position', 'absolute');
                            $('.tooltiptextLabel').css('top',textY+'px');
                            $('.tooltiptextLabel').css('left',textX+'px');
                            $('.tooltiptextLabel').html(customTextToolTip); 
                          }
                        } */                       
                    }
              }
          }
            }
           function mouseOutrLabel(propertiesOutLabel) {
             if (propertiesOutLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesOutLabel.target.textContent) {
                       axislabels[i].removeAttribute('font-weight', 'bold');
                       var bars = container.getElementsByTagName('path');
                       for(var j = 0; j<bars.length; j++){
                         if(dataPlot.getValue(j,0) == propertiesOutLabel.target.textContent){
                           bars[j].setAttribute('fill','#4285f4');
                           $('.tooltiptextLabel').html('');
                           $('.tooltiptextLabel').css('visibility','hidden');
                           $('.tooltiptextLabel').css('top',0);
                           $('.tooltiptextLabel').css('left',0);      

                         }
                       }
                       //this block of code for proteins and peptide                        
/*                       for(var j = 0; j<bars.length; j+=2){
                          if(dataPlot.getValue(j/2,0) == propertiesOutLabel.target.textContent){
                            bars[j].setAttribute('fill','#4285f4');
                            bars[j+1].setAttribute('fill','#db4437');
                            $('.tooltiptextLabel').html('');
                            $('.tooltiptextLabel').css('visibility','hidden');
                            $('.tooltiptextLabel').css('top',0);
                            $('.tooltiptextLabel').css('left',0);

                          }
                       }  */                     
                    }
                
                  }
            }
        }  
      
          function clickHandlerLabel(e) {
            if (e.target.tagName === 'text') {
              const findArray =tempdatamatrix.filter(p => p[0] == e.target.textContent);
              if (typeof findArray[0] != "undefined"){
                if (tempdatamatrix.indexOf(findArray[0])){
                    var tempGoogleDataURL='/dataload/googleChartData_'+e.target.textContent+'_biologicalMatrix';
                    $('tfoot input').val('');
                    self.datatableElement['dt'].columns().search('').draw();
                    self.datatableElement['dt'].search('').draw();                    
                    self.mBioTisVal=e.target.textContent;
                    self.datatableElement['dt'].columns( 6 ).search(e.target.textContent).draw();                     
                      //window.open(tempGoogleDataURL,'_blank');

                }
              }
            }
          }
          chart.draw(dataPlot, google.charts.Bar.convertOptions(options));

      }

      function drawStrainChart() {
         var tempdatastrain=mouseStrainData;
           var dataPlot = google.visualization.arrayToDataTable(tempdatastrain);
         const options = {
              'height':400,
              bar: {groupWidth: "100%"},
              legend: {position: 'none'},
              hAxis: {
                title: 'No. of assays',
                 minValue: 0,
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },      
              vAxis: {
                title: 'Strain',
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              bars: 'horizontal'
           };
           const chart = new google.charts.Bar(document.getElementById('chart_div_strain'));
             const container = document.getElementById('chart_div_strain');
             var axislabels:any=[];
             google.visualization.events.addListener(chart, 'onmouseover', uselessHandler);
            
             function uselessHandler() {
              $('#chart_div_strain path').css('cursor','pointer')
              $('#chart_div_strain text').css('cursor','pointer')
            }
            
             google.visualization.events.addListener(chart, 'select', selectHandler);
             google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
             google.visualization.events.addListener(chart, 'onmouseout', onmouseoutHandler);
       
            // use the 'ready' event to modify the chart once it has been drawn
           google.visualization.events.addListener(chart, 'ready', function () {
              axislabels = container.getElementsByTagName('text');
            });
       
       
            function selectHandler(e) {
              var selection = chart.getSelection();
                if (selection.length > 0) {
                  var colLabelSelect = dataPlot.getColumnLabel(selection[0].column);
                  var mydataSelect= dataPlot.getValue(selection[0].row,0);
                  var tempGoogleDataURL='/dataload/googleChartData_'+mydataSelect+'_strain';
                  //window.open(tempGoogleDataURL,'_blank');
                  chart.setSelection([])
               }
            }        
            
            function onmouseoverHandler(propertiesOver) {
              var hooverOverSelection= propertiesOver;
              if (Object.keys(hooverOverSelection).length > 0 && typeof hooverOverSelection.column !== "undefined") {
                var colLabelOver=dataPlot.getColumnLabel(hooverOverSelection.column);
                  var mydataOver =dataPlot.getValue(hooverOverSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOver) {
                      axislabels[i].setAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
            function onmouseoutHandler(propertiesOut) {
              var hooverOutSelection= propertiesOut;
              if (Object.keys(hooverOutSelection).length > 0 && typeof hooverOutSelection.column !== "undefined") {
                  var mydataOut =dataPlot.getValue(hooverOutSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOut) {
                      axislabels[i].removeAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
           container.addEventListener('click', clickHandlerLabel);
           container.addEventListener("mouseover", mouseOverLabel);
           container.addEventListener("mouseout", mouseOutrLabel);
         
           function mouseOverLabel(propertiesLabel) {
             if (propertiesLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesLabel.target.textContent) {
                        axislabels[i].setAttribute('font-weight', 'bold');
                        const findArray =tempdatastrain.filter(p => p[0] == propertiesLabel.target.textContent);
                        var textY=propertiesLabel.target.getAttribute("y");
                        var textX=propertiesLabel.target.getAttribute("x");
                        var customTextToolTip='<b>'+propertiesLabel.target.textContent+'</b>'+'<br>'+tempdatastrain[0][1]+':'+'<br>'+findArray[0][1]+'<br>'+tempdatastrain[0][2]+':'+'<br>'+findArray[0][2];                    
                        var bars = container.getElementsByTagName('path');
                        for(var j = 0; j<bars.length; j+=2){
                          if(dataPlot.getValue(j/2,0) == propertiesLabel.target.textContent){
                            bars[j].setAttribute('fill','#3871cf');
                            bars[j+1].setAttribute('fill','#ba3a2f');
                            $('.tooltiptextLabel').css('visibility','visible');
                            $('.tooltiptextLabel').css('position', 'absolute');
                            $('.tooltiptextLabel').css('top',textY+'px');
                            $('.tooltiptextLabel').css('left',textX+'px');
                            $('.tooltiptextLabel').html(customTextToolTip); 
                          }
                        }                        
                    }
              }
          }
            }
           function mouseOutrLabel(propertiesOutLabel) {
             if (propertiesOutLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesOutLabel.target.textContent) {
                       axislabels[i].removeAttribute('font-weight', 'bold');
                       var bars = container.getElementsByTagName('path');
                       for(var j = 0; j<bars.length; j+=2){
                          if(dataPlot.getValue(j/2,0) == propertiesOutLabel.target.textContent){
                            bars[j].setAttribute('fill','#4285f4');
                            bars[j+1].setAttribute('fill','#db4437');
                            $('.tooltiptextLabel').html('');
                            $('.tooltiptextLabel').css('visibility','hidden');
                            $('.tooltiptextLabel').css('top',0);
                            $('.tooltiptextLabel').css('left',0);

                          }
                       }                        
                    }
                
                  }
            }
        }  
      
          function clickHandlerLabel(e) {
            if (e.target.tagName === 'text') {
              const findArray =tempdatastrain.filter(p => p[0] == e.target.textContent);
              if (typeof findArray[0] != "undefined"){
                if (tempdatastrain.indexOf(findArray[0])){
                    var tempGoogleDataURL='/dataload/googleChartData_'+e.target.textContent+'_strain';
                    //window.open(tempGoogleDataURL,'_blank');

                }
              }
            }
          }
          chart.draw(dataPlot, google.charts.Bar.convertOptions(options));
      }

      function drawSubCellChart() {
         var tempdatasubCell=subCellData;
           var dataPlot = google.visualization.arrayToDataTable(tempdatasubCell);
         const options = {
              'height':300,
              bar: {groupWidth: "100%"},
              legend: {position: 'none'},
              hAxis: {
                title: 'No. of proteins covered',
                 minValue: 0,
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              vAxis: {
                title: 'SubCellular localization',
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              bars: 'horizontal'
           };
           const chart = new google.charts.Bar(document.getElementById('chart_div_subcell'));
             const container = document.getElementById('chart_div_subcell');
             var axislabels:any=[];
             google.visualization.events.addListener(chart, 'onmouseover', uselessHandler);
            
             function uselessHandler() {
              $('#chart_div_subcell path').css('cursor','pointer')
              $('#chart_div_subcell text').css('cursor','pointer')
            }
            
             google.visualization.events.addListener(chart, 'select', selectHandler);
             google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
             google.visualization.events.addListener(chart, 'onmouseout', onmouseoutHandler);
       
            // use the 'ready' event to modify the chart once it has been drawn
           google.visualization.events.addListener(chart, 'ready', function () {
              axislabels = container.getElementsByTagName('text');
            });
       
       
            function selectHandler(e) {
              var selection = chart.getSelection();
                if (selection.length > 0) {
                  var colLabelSelect = dataPlot.getColumnLabel(selection[0].column);
                  var mydataSelect= dataPlot.getValue(selection[0].row,0);
                  var tempGoogleDataURL='/dataload/googleChartData_'+mydataSelect+'_subCellLoc';
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();                  
                  self.mSCellVal=mydataSelect;
                  self.datatableElement['dt'].columns( 12 ).search(mydataSelect).draw();                 
                  //window.open(tempGoogleDataURL,'_blank');
                  chart.setSelection([])
               }
            }        
            
            function onmouseoverHandler(propertiesOver) {
              var hooverOverSelection= propertiesOver;
              if (Object.keys(hooverOverSelection).length > 0 && typeof hooverOverSelection.column !== "undefined") {
                var colLabelOver=dataPlot.getColumnLabel(hooverOverSelection.column);
                  var mydataOver =dataPlot.getValue(hooverOverSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOver) {
                      axislabels[i].setAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
            function onmouseoutHandler(propertiesOut) {
              var hooverOutSelection= propertiesOut;
              if (Object.keys(hooverOutSelection).length > 0 && typeof hooverOutSelection.column !== "undefined") {
                  var mydataOut =dataPlot.getValue(hooverOutSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOut) {
                      axislabels[i].removeAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
           container.addEventListener('click', clickHandlerLabel);
           container.addEventListener("mouseover", mouseOverLabel);
           container.addEventListener("mouseout", mouseOutrLabel);
         
           function mouseOverLabel(propertiesLabel) {
             if (propertiesLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesLabel.target.textContent) {
                        axislabels[i].setAttribute('font-weight', 'bold');
                        const findArray =tempdatasubCell.filter(p => p[0] == propertiesLabel.target.textContent);
                        var textY=propertiesLabel.target.getAttribute("y");
                        var textX=propertiesLabel.target.getAttribute("x");
                        var customTextToolTip='<b>'+propertiesLabel.target.textContent+'</b>'+'<br>'+tempdatasubCell[0][1]+':'+'<br>'+findArray[0][1];
                        var bars = container.getElementsByTagName('path');
                        for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesLabel.target.textContent){
                            bars[j].setAttribute('fill','#3871cf');
                            $('.tooltiptextLabel').css('visibility','visible');
                            $('.tooltiptextLabel').css('position', 'absolute');
                            $('.tooltiptextLabel').css('top',textY+'px');
                            $('.tooltiptextLabel').css('left',textX+'px');
                            $('.tooltiptextLabel').html(customTextToolTip); 
                          }
                        }                        
                    }
              }
          }
            }
           function mouseOutrLabel(propertiesOutLabel) {
             if (propertiesOutLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesOutLabel.target.textContent) {
                       axislabels[i].removeAttribute('font-weight', 'bold');
                       var bars = container.getElementsByTagName('path');
                       for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesOutLabel.target.textContent){
                            bars[j].setAttribute('fill','#4285f4');
                            $('.tooltiptextLabel').html('');
                            $('.tooltiptextLabel').css('visibility','hidden');
                            $('.tooltiptextLabel').css('top',0);
                            $('.tooltiptextLabel').css('left',0);

                          }
                       }                        
                    }
                
                  }
            }
        }  
      
          function clickHandlerLabel(e) {
            if (e.target.tagName === 'text') {
              const findArray =tempdatasubCell.filter(p => p[0] == e.target.textContent);
              if (typeof findArray[0] != "undefined"){
                if (tempdatasubCell.indexOf(findArray[0])){
                  var tempGoogleDataURL='/dataload/googleChartData_'+e.target.textContent+'_subCellLoc';
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();                  
                  self.mSCellVal=e.target.textContent;
                  self.datatableElement['dt'].columns( 12 ).search(e.target.textContent).draw();                  
                  //window.open(tempGoogleDataURL,'_blank');

                }
              }
            }      
          }
          chart.draw(dataPlot, google.charts.Bar.convertOptions(options));
      }

      function drawGOChart() {
         var tempdataGO=goData;
           var dataPlot = google.visualization.arrayToDataTable(tempdataGO);
         const options = {
              'height':300,
              bar: {groupWidth: "100%"},
              legend: {position: 'none'},
              hAxis: {
                title: 'No. of proteins covered',
                 minValue: 0,
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              vAxis: {
                title: 'GO Term Name',
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              bars: 'horizontal'
           };
           const chart = new google.charts.Bar(document.getElementById('chart_div_GO'));
             const container = document.getElementById('chart_div_GO');
             var axislabels:any=[];
             google.visualization.events.addListener(chart, 'onmouseover', uselessHandler);
            
             function uselessHandler() {
              $('#chart_div_GO path').css('cursor','pointer')
              $('#chart_div_GO text').css('cursor','pointer')
            }
            
             google.visualization.events.addListener(chart, 'select', selectHandler);
             google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
             google.visualization.events.addListener(chart, 'onmouseout', onmouseoutHandler);
       
            // use the 'ready' event to modify the chart once it has been drawn
           google.visualization.events.addListener(chart, 'ready', function () {
              axislabels = container.getElementsByTagName('text');
            });
       
       
            function selectHandler(e) {
              var selection = chart.getSelection();
                if (selection.length > 0) {
                  var colLabelSelect = dataPlot.getColumnLabel(selection[0].column);
                  var mydataSelect= dataPlot.getValue(selection[0].row,0);
                  var tempGoogleDataURL='/dataload/googleChartData_'+mydataSelect+'_goTermName';
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();                  
                  self.mGOVal=mydataSelect;
                  self.datatableElement['dt'].columns( 18 ).search(mydataSelect).draw();                  
                  //window.open(tempGoogleDataURL,'_blank');
                  chart.setSelection([])
               }
            }        
            
            function onmouseoverHandler(propertiesOver) {
              var hooverOverSelection= propertiesOver;
              if (Object.keys(hooverOverSelection).length > 0 && typeof hooverOverSelection.column !== "undefined") {
                var colLabelOver=dataPlot.getColumnLabel(hooverOverSelection.column);
                  var mydataOver =dataPlot.getValue(hooverOverSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOver) {
                      axislabels[i].setAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
            function onmouseoutHandler(propertiesOut) {
              var hooverOutSelection= propertiesOut;
              if (Object.keys(hooverOutSelection).length > 0 && typeof hooverOutSelection.column !== "undefined") {
                  var mydataOut =dataPlot.getValue(hooverOutSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == mydataOut) {
                      axislabels[i].removeAttribute('font-weight', 'bold');
                    }
                  }
              }
            }
          
           container.addEventListener('click', clickHandlerLabel);
           container.addEventListener("mouseover", mouseOverLabel);
           container.addEventListener("mouseout", mouseOutrLabel);
         
           function mouseOverLabel(propertiesLabel) {
             if (propertiesLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesLabel.target.textContent) {
                        axislabels[i].setAttribute('font-weight', 'bold');
                        const findArray =tempdataGO.filter(p => p[0] == propertiesLabel.target.textContent);
                        var textY=propertiesLabel.target.getAttribute("y");
                        var textX=propertiesLabel.target.getAttribute("x");
                        var customTextToolTip='<b>'+propertiesLabel.target.textContent+'</b>'+'<br>'+tempdataGO[0][1]+':'+'<br>'+findArray[0][1];
                        var bars = container.getElementsByTagName('path');
                        for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesLabel.target.textContent){
                            bars[j].setAttribute('fill','#3871cf');
                            $('.tooltiptextLabel').css('visibility','visible');
                            $('.tooltiptextLabel').css('position', 'absolute');
                            $('.tooltiptextLabel').css('top',textY+'px');
                            $('.tooltiptextLabel').css('left',textX+'px');
                            $('.tooltiptextLabel').html(customTextToolTip); 
                          }
                        }                        
                    }
              }
          }
            }
           function mouseOutrLabel(propertiesOutLabel) {
             if (propertiesOutLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                    if (axislabels[i].textContent == propertiesOutLabel.target.textContent) {
                       axislabels[i].removeAttribute('font-weight', 'bold');
                       var bars = container.getElementsByTagName('path');
                       for(var j = 0; j<bars.length; j++){
                          if(dataPlot.getValue(j,0) == propertiesOutLabel.target.textContent){
                            bars[j].setAttribute('fill','#4285f4');
                            $('.tooltiptextLabel').html('');
                            $('.tooltiptextLabel').css('visibility','hidden');
                            $('.tooltiptextLabel').css('top',0);
                            $('.tooltiptextLabel').css('left',0);

                          }
                       }                        
                    }
                
                  }
            }
        }  
      
          function clickHandlerLabel(e) {
            if (e.target.tagName === 'text') {
              const findArray =tempdataGO.filter(p => p[0] == e.target.textContent);
              if (typeof findArray[0] != "undefined"){
                if (tempdataGO.indexOf(findArray[0])){
                  var tempGoogleDataURL='/dataload/googleChartData_'+e.target.textContent+'_goTermName';
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();                  
                  self.mGOVal=e.target.textContent;
                  self.datatableElement['dt'].columns( 18 ).search(e.target.textContent).draw();                  
                  //window.open(tempGoogleDataURL,'_blank');

                }
              }
            } 
          }
          chart.draw(dataPlot, google.charts.Bar.convertOptions(options));
      }

      function drawDisChart() {
          var tempdataDis=humanDiseaseData;
          var dataPlot = google.visualization.arrayToDataTable(tempdataDis);
          const options = {
              'height':400,
              bar: {groupWidth: "100%"},
              legend: {position: 'none'},
              hAxis: {
                  title: 'No. of proteins associated',
                   minValue: 0,
                    textStyle : {
                        fontSize: 16 // or the number you want
                    },
              },
              vAxis: {
                title: 'Disease Name',
                  textStyle : {
                      fontSize: 16 // or the number you want
                  },
              },
              bars: 'horizontal'
          };
          const chart = new google.charts.Bar(document.getElementById('chart_div_disease'));
          const container = document.getElementById('chart_div_disease');
          var axislabels:any=[];
          google.visualization.events.addListener(chart, 'onmouseover', uselessHandler);
          
          function uselessHandler() {
              $('#chart_div_disease path').css('cursor','pointer')
              $('#chart_div_disease text').css('cursor','pointer')
          }
          
          google.visualization.events.addListener(chart, 'select', selectHandler);
          google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);
          google.visualization.events.addListener(chart, 'onmouseout', onmouseoutHandler);
     
          // use the 'ready' event to modify the chart once it has been drawn
          google.visualization.events.addListener(chart, 'ready', function () {
              axislabels = container.getElementsByTagName('text');
          });
     
     
          function selectHandler(e) {
              var selection = chart.getSelection();
              if (selection.length > 0) {
                  var colLabelSelect = dataPlot.getColumnLabel(selection[0].column);
                  var mydataSelect= dataPlot.getValue(selection[0].row,0);
                  var tempDisogleDataURL='/dataload/googleChartData_'+mydataSelect+'_disTermName';
                  //window.open(tempDisogleDataURL,'_blank');
                  $('tfoot input').val('');
                  self.datatableElement['dt'].columns().search('').draw();
                  self.datatableElement['dt'].search('').draw();
                  self.hDisVal=mydataSelect;
                  self.datatableElement['dt'].columns( 19 ).search(mydataSelect).draw();
                  chart.setSelection([])
              }
          }        
          
          function onmouseoverHandler(propertiesOver) {
              var hooverOverSelection= propertiesOver;
              if (Object.keys(hooverOverSelection).length > 0 && typeof hooverOverSelection.column !== "undefined") {
                  var colLabelOver=dataPlot.getColumnLabel(hooverOverSelection.column);
                  var mydataOver =dataPlot.getValue(hooverOverSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                      if (axislabels[i].textContent == mydataOver) {
                          axislabels[i].setAttribute('font-weight', 'bold');
                      }
                  }
              }
          }
        
          function onmouseoutHandler(propertiesOut) {
              var hooverOutSelection= propertiesOut;
              if (Object.keys(hooverOutSelection).length > 0 && typeof hooverOutSelection.column !== "undefined") {
                  var mydataOut =dataPlot.getValue(hooverOutSelection.row,0);
                  for (var i = 0; i < axislabels.length; i++) {
                      if (axislabels[i].textContent == mydataOut) {
                          axislabels[i].removeAttribute('font-weight', 'bold');
                      }
                  }
              }
          }
        
          container.addEventListener('click', clickHandlerLabel);
          container.addEventListener("mouseover", mouseOverLabel);
          container.addEventListener("mouseout", mouseOutrLabel);
       
          function mouseOverLabel(propertiesLabel) {
              if (propertiesLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                      if (axislabels[i].textContent == propertiesLabel.target.textContent) {
                          axislabels[i].setAttribute('font-weight', 'bold');
                          const findArray =tempdataDis.filter(p => p[0] == propertiesLabel.target.textContent);
                          var textY=propertiesLabel.target.getAttribute("y");
                          var textX=propertiesLabel.target.getAttribute("x");
                          var customTextToolTip='<b>'+propertiesLabel.target.textContent+'</b>'+'<br>'+tempdataDis[0][1]+':'+'<br>'+findArray[0][1];
                          var bars = container.getElementsByTagName('path');
                          for(var j = 0; j<bars.length; j++){
                            if(dataPlot.getValue(j,0) == propertiesLabel.target.textContent){
                              bars[j].setAttribute('fill','#3871cf');
                              $('.tooltiptextLabel').css('visibility','visible');
                              $('.tooltiptextLabel').css('position', 'absolute');
                              $('.tooltiptextLabel').css('top',textY+'px');
                              $('.tooltiptextLabel').css('left',textX+'px');
                              $('.tooltiptextLabel').html(customTextToolTip); 
                            }
                          }
                      }
                      const findArray =tempdataDis.filter(p => p[0] == propertiesLabel.target.textContent);
                  }
              }
          }
          function mouseOutrLabel(propertiesOutLabel) {
              if (propertiesOutLabel.target.tagName === 'text') {
                  for (var i = 0; i < axislabels.length; i++) {
                      if (axislabels[i].textContent == propertiesOutLabel.target.textContent) {
                          axislabels[i].removeAttribute('font-weight', 'bold');
                          var bars = container.getElementsByTagName('path');
                          for(var j = 0; j<bars.length; j++){
                             if(dataPlot.getValue(j,0) == propertiesOutLabel.target.textContent){
                               bars[j].setAttribute('fill','#4285f4');
                               $('.tooltiptextLabel').html('');
                               $('.tooltiptextLabel').css('visibility','hidden');
                               $('.tooltiptextLabel').css('top',0);
                               $('.tooltiptextLabel').css('left',0);      

                             }
                          }                       
                      }
              
                  }
              }
          }  
    
          function clickHandlerLabel(e) {
              if (e.target.tagName === 'text') {
                const findArray =tempdataDis.filter(p => p[0] == e.target.textContent);
                if (typeof findArray[0] != "undefined"){
                  if (tempdataDis.indexOf(findArray[0])){
                    var tempDisogleDataURL='/dataload/googleChartData_'+e.target.textContent+'_disTermName';
                    $('tfoot input').val('');
                    self.datatableElement['dt'].columns().search('').draw();
                    self.datatableElement['dt'].search('').draw();
                    self.hDisVal=e.target.textContent;
                    self.datatableElement['dt'].columns( 19 ).search(e.target.textContent).draw();
                    //window.open(tempGoogleDataURL,'_blank');

                  }
                }
              } 
          }
        chart.draw(dataPlot, google.charts.Bar.convertOptions(options));
      }
        $(document).ready(function() {
          $(window).resize(function() {
            drawMatrixChart();
            drawStrainChart();
            drawSubCellChart();
            drawGOChart();
            drawDisChart();
          })
        })
      }

  toggleAccordian(event) {
      var element = event.target;
      element.classList.toggle("active");     
      var panel = element.nextElementSibling;
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
      }
 }
  clearFilterSearch(){
    $('tfoot input').val('');
    this.mProtVal='';
    this.mGenVal='';
    this.mUKBVal='';
    this.mPepassVal='';
    this.mStrVal='';
    this.mKoutVal='';
    this.mBioTisVal='';
    this.mGenderVal='';
    this.mGenExpVal='';
    this.hProtVal='';
    this.hUKBVal='';
    this.hPresPepVal='';
    this.mSCellVal='';
    this.mPathVal='';
    this.hDisVal='';
    this.mGOVal='';
    this.hDrugVal='';
    this.datatableElement['dt'].columns().search('').draw();
    this.datatableElement['dt'].search('').draw();
  }
  ngOnDestroy(){
    this.routeSub.unsubscribe();
  }
}
<file_sep>/client/qmpkb-app/src/app/home/home.component.ts
import { Component, OnInit, OnDestroy, HostListener, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, Observer } from 'rxjs';
import { share } from 'rxjs/operators';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as Plotly from 'plotly.js';
import { NgxSpinnerService } from 'ngx-spinner';
import * as $ from "jquery";

declare var jquery: any;


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit,OnDestroy {
  private queryRes:any;
  private advReq:any;
  unqProteins;
  unqpeptides;
  unqassays;
  pepSeqPresenceHumanOrtholog;
  pepSeqPresenceHumanOrthologUniId;
  screenWidth:any;
  plotlyData:any=[];
  allBioMat:any;
  allStrain:any;
  interval:any;
  autoPlotStatus:boolean= false;
  plotIndex:number=0;
  progress:number=0;
  finalPlotData:any={};
  public show:boolean = false;
  public buttonName:any = 'Advanced search';

  public number: number = 0;
  public observable: Observable<boolean>;
  private observer: Observer<boolean>;
  qmpkbLogoImage ='static/ang/assets/images/logo/logo.png'
  isCollapsed:boolean=true;

  plotDataOptions=[
       {num:0, name:'Brain'},
       {num:1, name:'Brown Adipose'},
       {num:2, name:'Epididymis'},
       {num:3, name:'Eye'},
       {num:4, name:'Heart'},
       {num:5, name:'Kidney'},
       {num:6, name:'Liver Caudate and Right Lobe'},
       {num:7, name:'Liver Left Lobe'},
       {num:8, name:'Lung'},
       {num:9, name:'Ovary'},
       {num:10, name:'Pancreas'},
       {num:11, name:'Plasma'},
       {num:12, name:'RBCs'},
       {num:13, name:'Salivary Gland'},
       {num:14, name:'Seminal Vesicles'},
       {num:15, name:'Skeletal Muscle'},
       {num:16, name:'Skin'},
       {num:17, name:'Spleen'},
       {num:18, name:'Testes'},
       {num:19, name:'White Adipose'}

  ];

  unitDic={
        'Brain':' (fmol target protein/µg extracted protein)',
        'Brown Adipose': ' (fmol target protein/µg extracted protein)',
        'Eye':' (fmol target protein/µg extracted protein)',
        'Epididymis':' (fmol target protein/µg extracted protein)',
        'Heart':' (fmol target protein/µg extracted protein)',
        'Kidney': ' (fmol target protein/µg extracted protein)',
        'Liver Caudate and Right Lobe':' (fmol target protein/µg extracted protein)',
        'Liver Left Lobe':' (fmol target protein/µg extracted protein)',
        'Lung':' (fmol target protein/µg extracted protein)',
        'Ovary': ' (fmol target protein/µg extracted protein)',
        'Pancreas':' (fmol target protein/µg extracted protein)',
        'Plasma':' (fmol target protein/µg extracted protein)',
        'RBCs':' (fmol target protein/µg extracted protein)',
        'Salivary Gland': ' (fmol target protein/µg extracted protein)',
        'Seminal Vesicles':' (fmol target protein/µg extracted protein)',
        'Skeletal Muscle':' (fmol target protein/µg extracted protein)',
        'Skin':' (fmol target protein/µg extracted protein)',
        'Spleen':' (fmol target protein/µg extracted protein)',
        'Testes':' (fmol target protein/µg extracted protein)',
        'White Adipose': ' (fmol target protein/µg extracted protein)'
    };

  defaultPlotlyConfiguration ={
      responsive: true,
      scrollZoom: true,
      showTips:true,
      modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
      displayLogo: false
  };

  selected=this.plotDataOptions[0];

  @HostListener('window.resize', ['$event'])

  getScreenSize(event?){
    this.screenWidth=Math.round(window.innerWidth/2)+"px";
  }

  constructor(private router:Router, private http:HttpClient,private _qmpkb:QmpkbService,private spinner: NgxSpinnerService, private cdRef:ChangeDetectorRef) { 
        this.observable = new Observable<boolean>((observer: any) => this.observer = observer);
        this.getScreenSize();

        // For auto mode
        //setTimeout(() => this.number += this.number, 5000); // Update on 5 seconds
  }

  ngOnInit() {
  this.spinner.show();
  this.queryRes=this.http.get('/fileapi/resultFile/jsonData/preLoadData/preloadHomeData.json')
    .subscribe((resp:any) => {
      this.allBioMat=resp.data[1]["BioMat"].split('|');
      this.allStrain=resp.data[2]["Strain"].split('|');
      this.unqassays=resp.data[0]["uniqueAssays"];
      this.unqProteins=resp.data[0]["uniqueProtein"];
      this.unqpeptides=resp.data[0]["uniquePeptide"];
      this.pepSeqPresenceHumanOrtholog=resp.data[0]["pepSeqPresenceHumanOrtholog"];
      this.pepSeqPresenceHumanOrthologUniId=resp.data[0]["pepSeqPresenceHumanOrthologUniId"];
      this.plotlyData.push(resp.data[1]);
      this.plotlyData.push(resp.data[3]);
      this.plotlyData.push(resp.data[2]);

      let rawData = resp.data[4];
      let bioMatData = resp.data[5];
      let finalData:any={};
      for (let x in this.allBioMat){
         finalData[this.allBioMat[x]]=[];
      }
      let bioMatKey=Object.keys(bioMatData).sort();
      for (let z in bioMatKey){
        let plotDataArrayTrace:any={};
        plotDataArrayTrace={
          y:bioMatData[bioMatKey[z]]['MeanConcData'].split('|'),
          x:bioMatData[bioMatKey[z]]['MeanProtein'].split('|'),
          name:'Mean Concentration',
          type:'Scatter',
          mode:'markers',
          marker:{
            size:6,
            symbol:Array(bioMatData[bioMatKey[z]]['MeanProtein'].length).fill("diamond-open-dot"),
          },
          //text:bioMatData[bioMatKey[z]]['MeanProtein'].split('|') //name of Uniprot ID and Gene
        };
        finalData[bioMatKey[z]].push(plotDataArrayTrace);
      }
      let number=0;
      let tempKey=Object.keys(rawData).sort()
      for (let i in tempKey){
        number++;
        for (let j=0; j<rawData[tempKey[i]].length; j++){
          let tempBioMat=rawData[tempKey[i]][j];
          let tempBioMatKey=(Object.keys(tempBioMat))[0];
          let tempBioMatVal=(Object.values(tempBioMat))[0];
          let plotDataArrayMaleTrace:any={};
          let plotDataArrayFemaleTrace:any={};
          try{
            plotDataArrayMaleTrace={
              y:tempBioMatVal['Male']['MeanConcData'].split('|'),
              x:tempBioMatVal['Male']['MeanProtein'].split('|'),
              name:'Male '+tempKey[i],
              type:'Scatter',
              mode:'markers',
              marker:{
                size:6,
                symbol:Array(tempBioMatVal['Male']['MeanProtein'].length).fill("circle-open-dot"),
              },
              //text:tempBioMatVal['Male']['MeanProtein'].split('|') //name of Uniprot ID and Gene
            };
            finalData[tempBioMatKey].push(plotDataArrayMaleTrace);
          } catch (e){

          }
          try{
            plotDataArrayFemaleTrace={
              y:tempBioMatVal['Female']['MeanConcData'].split('|'),
              x:tempBioMatVal['Female']['MeanProtein'].split('|'),
              name:'Female '+tempKey[i],
              type:'Scatter',
              mode:'markers',
              marker:{
                size:6,
                symbol:Array(tempBioMatVal['Female']['MeanProtein'].length).fill("square-open-dot"),
              },
              //text:tempBioMatVal['Female']['MeanProtein'].split('|') //name of Uniprot ID and Gene
            };
            finalData[tempBioMatKey].push(plotDataArrayFemaleTrace);
          } catch (e){

          }

        }
      }
      let finalLayout:any=[]
      //this.cdRef.detectChanges();
      for (let y in bioMatKey){
        let layout={
          title:{text:'Protein concentration ranges in '+bioMatKey[y],font:{size:14}},
          xaxis: {showticklabels:false,title:'Protein',font:{size:14}},
          yaxis: {title:this.unitDic[bioMatKey[y]]+'<br>in Log10 Scale',font:{size:14}},
        };
        finalLayout.push(layout);
      }

      this.finalPlotData={
          'plotData':finalData,
          'plotLayout':finalLayout,
          'config':this.defaultPlotlyConfiguration
      };


      this.barplot(this.plotlyData);
      this.preparerawData(this.autoPlotStatus);
    });
    this.advReq=this.http.get('/fileapi/resultFile/jsonData/preLoadData/advanceSearchOptions.json')
      .subscribe((resp:any) => {
        this._qmpkb.dropDownStorage=resp.data;
    });
  }


  preparerawData(plotStatus:any){
    let tempTissueList=[
       'Brain',
       'Brown Adipose',
       'Epididymis',
       'Eye',
       'Heart',
       'Kidney',
       'Liver Caudate and Right Lobe',
       'Liver Left Lobe',
       'Lung',
       'Ovary',
       'Pancreas',
       'Plasma',
       'RBCs',
       'Salivary Gland',
       'Seminal Vesicles',
       'Skeletal Muscle',
       'Skin',
       'Spleen',
       'Testes',
       'White Adipose'

  ];
    let tempPlotDataInitial=this.finalPlotData['plotData'];
    let tempPlotLayoutInitial=this.finalPlotData['plotLayout'];
    let tempConfigInitial=this.finalPlotData['config'];

    if(document.getElementById('myDivHome')){
      Plotly.newPlot('myDivHome',tempPlotDataInitial['Brain'],tempPlotLayoutInitial[0],tempConfigInitial);
    }
    
    const self =this;
    let timeleft=3;
    if ( !plotStatus){
      this.interval = setInterval(() => {
        if(this.progress>= 3){
          this.plotIndex++;
          if(this.plotIndex==20){
             this.plotIndex=0;
          }
          this.selected=this.plotDataOptions[this.plotIndex];
          if(document.getElementById('myDivHome')){
            Plotly.newPlot('myDivHome',tempPlotDataInitial[tempTissueList[this.plotIndex]],tempPlotLayoutInitial[this.plotIndex],tempConfigInitial);
          }
          
          this.progress=0;
        } else{
           this.progress++;
        }
      }, 1000);
    }
     $('#myDivHome').hover(function(ev){
         $("#progressBar").hide();
         self.progress=0;
         clearInterval(self.interval);
      }, function(ev){
        self.interval = setInterval(() => {
          $("#progressBar").show();
          if(self.progress>= 3){
            self.plotIndex++;
            if(self.plotIndex==20){
               self.plotIndex=0;
            }
            self.selected=self.plotDataOptions[self.plotIndex];
            if(document.getElementById('myDivHome')){
              Plotly.newPlot('myDivHome',tempPlotDataInitial[tempTissueList[self.plotIndex]],tempPlotLayoutInitial[self.plotIndex],tempConfigInitial);
            }
            self.progress=0;
          } else{
             self.progress++;
          }
          },1000);
      });

    this.spinner.hide();
  }


  barplot(rawData:any):void {
    let layout:any={};
    layout = {
      xaxis: {domain: [0, 0.25]},
      xaxis2: {domain: [0.35, .60]},
      xaxis3: {domain: [.70, 1.0]},
      yaxis: {domain: [0, .9]},
      yaxis2: {anchor: 'x2',domain: [0, .9]},
      yaxis3: {anchor: 'x3',domain: [0, .9]},
      annotations: [
        {
          text: "Biological Matrix",
          font: {
            size: 16
          },
          showarrow: false,
          align: 'center',
          x: 0.13,
          y: 1,
          xref: 'paper',
          yref: 'paper',
        },
        {
          text: "Sex",
          font: {
            size: 16
          },
          showarrow: false,
          align: 'center',
          x: 0.48,
          y: 1,
          xref: 'paper',
          yref: 'paper',
         },
        {
          text: "Strain",
          font: {
            size: 16
          },
          showarrow: false,
          align: 'center',
          x: 0.85,
          y: 1,
          xref: 'paper',
          yref: 'paper',
         }
      ],
      showlegend: false
    };

    const d3colors = Plotly.d3.scale.category10();
    let defaultPlotlyConfiguration={};
    defaultPlotlyConfiguration ={
      responsive: true,
      scrollZoom: true,
      showTips:true,
      modeBarButtonsToRemove: ['sendDataToCloud', 'autoScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'lasso2d', 'select2d','toImage','pan', 'pan2d','zoom2d','toggleSpikelines'],
      displayLogo: false
    };

    let plotDataArrayMatTrace1:any={};
    let plotDataArrayMatTrace2:any={};
    plotDataArrayMatTrace1={
      y:rawData[0]["BioMat"].split('|'),
      x:rawData[0]["PeptideSeq"].split('|'),
      name:'Assays',
      type:'bar',
      orientation:'h'
    };
    plotDataArrayMatTrace2={
      y:rawData[0]["BioMat"].split('|'),
      x:rawData[0]["Protein"].split('|'),
      name:'Protein',
      type:'bar',
      orientation:'h'
    };

    let plotDataArraySexTrace1:any={};
    let plotDataArraySexTrace2:any={};
    plotDataArraySexTrace1={
      y:rawData[1]["Sex"].split('|'),
      x:rawData[1]["PeptideSeq"].split('|'),
      xaxis:'x2',
      yaxis:'y2',
      name:'Assays',
      type:'bar',
      orientation:'h'
    };
    plotDataArraySexTrace2={
      y:rawData[1]["Sex"].split('|'),
      x:rawData[1]["Protein"].split('|'),
      xaxis:'x2',
      yaxis:'y2',
      name:'Protein',
      type:'bar',
      orientation:'h'
    };

    let plotDataArrayStrainTrace1:any={};
    let plotDataArrayStrainTrace2:any={};
    plotDataArrayStrainTrace1={
      y:rawData[2]["Strain"].split('|'),
      x:rawData[2]["PeptideSeq"].split('|'),
      xaxis:'x3',
      yaxis:'y3',
      name:'Assays',
      type:'bar',
      orientation:'h'
    };
    plotDataArrayStrainTrace2={
      y:rawData[2]["Strain"].split('|'),
      x:rawData[2]["Protein"].split('|'),
      xaxis:'x3',
      yaxis:'y3',
      name:'Protein',
      type:'bar',
      orientation:'h'
    };

    const finalData=[plotDataArrayMatTrace1,plotDataArrayMatTrace2,plotDataArraySexTrace1,plotDataArraySexTrace2,plotDataArrayStrainTrace1,plotDataArrayStrainTrace2];


    //Plotly.newPlot('myDiv',finalData,layout,defaultPlotlyConfiguration);      
  }


  onOptionsSelected(event){
      if(event.target){
        $("#progressBar").hide();
        let tempPlotData=this.finalPlotData['plotData'];
        let tempPlotLayout=this.finalPlotData['plotLayout'];
        let tempConfig=this.finalPlotData['config'];
        this.autoPlotStatus = true;
        this.preparerawData(this.autoPlotStatus);
        clearInterval(this.interval);
        if(document.getElementById('myDivHome')){
          Plotly.purge('myDivHome');
          Plotly.newPlot('myDivHome',tempPlotData[this.selected.name],tempPlotLayout[this.selected.num],tempConfig);
        }
      }
    }


  toggle() {
    this.show = !this.show;

    // CHANGE THE NAME OF THE BUTTON.
    if(this.show)  
      this.buttonName = "Basic search";
    else
      this.buttonName = "Advanced search";
  }

  ngOnDestroy(){
    this.queryRes.unsubscribe();
    this.advReq.unsubscribe();
  }

}

<file_sep>/client/qmpkb-app/src/app/protvista-view/protvista-view.component.ts
import { Component, OnInit, OnDestroy, HostListener, ViewChild,Input} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { NgxSpinnerService } from 'ngx-spinner';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import * as $ from "jquery";

declare var require: any
declare var jquery: any;

@Component({
  selector: 'app-protvista-view',
  templateUrl: './protvista-view.component.html',
  styleUrls: ['./protvista-view.component.css']
})
export class ProtvistaViewComponent implements OnInit,OnDestroy  {
  private routeSub:any;
  dtOptionsProtVista: any = {};
  mousePepStart:number;
  humanPepStart:number;
  mousePepEnd:number;
  humanPepEnd:number;
  mouseUniprotKB:any;
  humanUniprotKB:any;
  pepseq:any;
  protname:any;
  errorStr:Boolean;
  queryData:any;
  queryProtVistaUniProtKB:any;
  pepSeqMatchList:any;
  humanProtvistaQueryData:any;
  protVistaDataStatus=false;
  @Input() public href: string | undefined;
  @HostListener('click', ['$event']) public onClick(event: Event): void{
    if (!this.href || this.href === '#' || (this.href && this.href.length ===0)){
      event.preventDefault();
    }
  }
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;
  constructor(
    private route: ActivatedRoute,
    private location: Location,
    private http: HttpClient,
    private router: Router,
    private spinner: NgxSpinnerService,
    private _qmpkb:QmpkbService
    ) { }

    @Input()
    set protVistatermQuery(protVistaUniProtKB:any){
      this.queryProtVistaUniProtKB=protVistaUniProtKB;

    }

  async  getProtVistaData(){

    await this._qmpkb.receiveDataFromBackendSearch('/seqfeaturesapi/?uniProtKb='+ this.queryProtVistaUniProtKB).subscribe((response: any)=>{
        
        this.queryData=response;
        this.pepseq=this.queryData.pepseq;
        this.mouseUniprotKB=this.queryProtVistaUniProtKB;
        this.humanUniprotKB=this.queryData.humanUniprotKB;
        this.mousePepStart=this.queryData.seqStart;
        this.humanPepStart=this.queryData.humanPepStart;
        this.mousePepEnd=this.queryData.seqEnd;
        this.humanPepEnd=this.queryData.humanPepEnd;
        this.protname= this.queryData.protname;
        this.pepSeqMatchList=this.queryData.pepSeqMatchList;
        this.humanProtvistaQueryData={
          humanUniprotKB:this.humanUniprotKB,
          humanPepStart:this.humanPepStart,
          humanPepEnd:this.humanPepEnd

        }
        this.dtOptionsProtVista = {
              searching: false,
              info: false,
              ordering: false,
              paging: false,
              autoWidth:true  
        };
        if (this.mousePepEnd > 0){
           setTimeout(() => {this.plotProtVistaMouseFunc(this.mouseUniprotKB,this.mousePepStart,this.mousePepEnd)}, 100); 
       };
       this.protVistaDataStatus=true;
      }, error=>{
        this.errorStr = error;
      })
  }

  ngOnInit() {
    this.getProtVistaData();
  }


  plotProtVistaMouseFunc(protvistaMouseUni:string,mousePreSelectStart:number,mousePreSelectEnd:number): void {
      if (mousePreSelectStart >0){
        var mouseDiv = document.getElementById('mouseDiv');
        var ProtVistaMouse = require('ProtVista');

        var mouseinstance = new ProtVistaMouse({
          el: mouseDiv,
          uniprotacc: protvistaMouseUni,
          defaultSources: true,
          //These categories will **not** be rendered at all
          exclusions: ['SEQUENCE_INFORMATION', 'STRUCTURAL', 'TOPOLOGY', 'MOLECULE_PROCESSING', 'ANTIGEN'],
          //Your data sources are defined here
          customDataSource: {
            url: 'fileapi/resultFile/jsonData/protvistadataJson/mouse/externalLabeledFeatures_',
            source: 'MouseQuaPro',
            useExtension: true
          },
          categoryOrder: ['TARGETED_PROTEOMICS_ASSAY_MOUSE', 'PROTEOMICS', 'DOMAINS_AND_SITES', 'PTM', 'MUTAGENESIS'],
          //This feature will be preselected
          selectedFeature: {
          begin: mousePreSelectStart,
          end: mousePreSelectEnd,
          type: 'MRM'
          }
        });
      }
  }
  ngOnDestroy(){
      this.routeSub.unsubscribe()
  }
}

<file_sep>/backend/src/qmpkbapp/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.db import models

# Create your models here.

class IpAddressInformation(models.Model):
	ip_address=models.CharField(max_length=1200,blank=False)
	access_date=models.DateTimeField(auto_now_add=True,auto_now=False)
	def __unicode__(self):
		return self.ip_address<file_sep>/client/qmpkb-app/src/app/help/help.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import * as $ from "jquery";
declare var jquery: any;


@Component({
  selector: 'app-help',
  templateUrl: './help.component.html',
  styleUrls: ['./help.component.css']
})
export class HelpComponent implements OnInit {
  baseUrl;
  constructor(
  	  private router: Router
  ) { }

  ngOnInit() {
  	this.baseUrl = window.location.origin;
    if (this.router.url.includes('#')){
      const link=this.router.url.split('#')[1];
      this.preCSS(link);
    }
  }

 preCSS(hashLink:any):void {
    var self= this;
/*    $('#'+hashLink).trigger('click');*/
    $('#'+hashLink).css({'padding-top':'51px'});

 }
  gethref(evt, linkName) {
      const hrefIDArray=['searching','update','cite','result','submission','implementation'];
      $('#'+linkName).css({'padding-top':'51px'});
      for(let i=0; i<hrefIDArray.length;i++){
        if(hrefIDArray[i] !==linkName){
          $('#'+hrefIDArray[i]).css({'padding-top':''});
        }
      }
  }
}<file_sep>/client/qmpkb-app/src/app/basic-search/basic-search.component.ts
import { Component, OnInit, Input, Renderer } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, FormControl, Validators, FormArray } from '@angular/forms';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';
import { NgxSpinnerService } from 'ngx-spinner';
import * as $ from "jquery";

declare var jquery: any;

@Component({
  selector: 'app-basic-search',
  templateUrl: './basic-search.component.html',
  styleUrls: ['./basic-search.component.css']
})
export class BasicSearchComponent implements OnInit {
	searchQuery: string;
  baseUrl;
  @Input()
  passedQuery: string;
  selectedExampleValue: string;
  selectedExampleName: string;
  errorStr:Boolean;
  public alertIsVisible:boolean= false;
  submitButtonClickStatus:boolean = false;

  public fields: any[] = [
      [
        {
          name:'Protein name',
          value:'Vinculin'
        },
        {
          name:'Gene',
          value:'Vcl'
        },
        {
          name:'UniProtKB accession',
          value:'Q64727'
        }
      ],[
        {
          name:'Peptide sequence',
          value:'ALASQLQDSLK'
        },
        {
          name:'Strain',
          value:'NODSCID'
        },
        {
          name:'Mutant',
          value:'Wild'
        }
      ],[
        {
          name:'Sex',
          value:'Male'
        },
        {
          name:'Biological matrix',
          value:'Plasma'
        },
        {
          name:'Subcellular localization',
          value:'Secreted'
        }
      ],[
        {
          name:'Molecular pathway(s)',
          value:'Complement and coagulation cascades'
        },
        {
          name:'Involvement in disease',
          value:'Adiponectin deficiency(ADPND)'
        },
        {
          name:'GO ID',
          value:'GO:0008015'
        }
      ],[
        {
          name:'GO Term',
          value:'blood circulation'
        },
        {
          name:'GO Aspects',
          value:'Biological Process'
        },
        {
          name:'Drug associations ID',
          value:'DB05202'
        }
      ]
    ];

  constructor(
    private router: Router,
    private http: HttpClient,
    private renderer: Renderer,
    private _qmpkb:QmpkbService,
    private spinner: NgxSpinnerService
  ) { }


  ngOnInit() {
    this.spinner.show();
    this.fields;
    this.selectedExampleName='';
    this.selectedExampleValue='';
    this.spinner.hide();
  }

  ngAfterViewInit(): void {


/*    window.onclick = function(event) {
      if (!event.target.matches('#bt')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
          }
        }
      }
    }*/
  }
  getValue(item : any) {
    this.selectedExampleName=item.name;
    this.selectedExampleValue=item.value;
  }

   exampleFunction() {
      document.getElementById("myDropdown").classList.toggle("show");
  }
  exampleDisplay(){
    document.getElementById("myDropdown").classList.toggle("show");
  }
  submitFunction(){
    this.submitButtonClickStatus=true;
  }
  submitSearch(event,formData){

  	let searchedQuery = formData.value['searchterm']
    if (searchedQuery){
      if (this.submitButtonClickStatus){
        this.spinner.show();
        this.router.navigate(['/results'],{queryParams:{searchterm:searchedQuery}});
      }
    }

  }

}<file_sep>/backend/src/qmpkbapp/modifiedJsondata.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import Counter
from itertools import combinations
import ast
from operator import itemgetter
import operator
import json
import re,sys
import itertools
from collections import OrderedDict
import datetime
from statistics import mean
from appTissueInfo import *
from django.contrib.admin.utils import flatten
# function to generate peptidebased info into nested json format
def pepbasedInfo(jfinaldata,uniprotpepinfo,matchingpepseqquery,proteininfoColname,querybiomatrix):
	pepetidebasedinfoCol=['UniProtKB Accession','Peptide ID','Peptide Sequence','Summary Concentration Range Data',\
	'All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based','Special Residues','Molecular Weight',\
	'GRAVY Score','Transitions','Retention Time','Percent Organic Solution','Gradients','AAA Concentration','CZE Purity',\
	'Unique in protein','Present in isoforms','PeptideTracker TransView',"Peptide unique in user's database",\
	"Peptide in user's database","Peptide ID","Concentration View"]
	updatedUniInfo=[]
	biomatrixContainUniId=[]
	finalupdatedUniInfo={}
	tempdiffcol=proteininfoColname
	updatedpepinfocol=['UniProtKB Accession','Peptide Sequence',"Unique in protein",'Present in isoforms',\
	'Present in human ortholog','Unique in human protein','Present in human isoforms',\
	"Peptide unique in user's database", "Peptide in user's database","Panel",'LLOQ','ULOQ','Sample LLOQ']
	assaydinfocol=['Special Residues','Molecular Weight','GRAVY Score','AAA Concentration','CZE Purity']
	tempdiffcol.append('Organism ID')
	foldchangeData={}
	sexData=[]
	strainData=[]
	biomatrixData=[]
	for uniprotid in uniprotpepinfo:
		tempupdatedUniDic={}
		peptidebasedinfo=[]
		tempmatchingpepseq=''
		tempepepseqlist=[]
		biologicalmatrix=[]
		biologicalmatrixdetails=[]
		sexdetails=[]
		straindetails=[]
		knockoutdetails=[]
		meanconcdic={}
		concendataAll=[]
		concendataALLSampleLLOQ=[]
		pepSeqPresence=[]
		for pepseq in list(set(uniprotpepinfo[uniprotid])):
			tempassaydic={}
			tempconcenlist=[]
			tempassaydinfo=[]
			tempgradients=[]
			temptransition=[]
			tempconcendata=[]
			geneExpData='NA'
			concenQuery='NA'
			concenView={}
			for jd in jfinaldata:
				if uniprotid in jd['UniProtKB Accession'] and pepseq in jd['Peptide Sequence']:
					if jd['Gene Expression Data'] != 'NA':
						geneExpData=jd['Gene Expression Data'].split(';')[1:]
						geneExpData.sort(key=lambda g: g.upper())
					concendataAll.append([jd['Peptide Sequence'],jd['All Concentration Range Data']])
					concendataALLSampleLLOQ.append([jd['Peptide Sequence'],jd['All Concentration Range Data-Sample LLOQ Based']])
					biologicalmatrix.append(jd["Biological Matrix"])
					tempepepseqlist.append(jd['Peptide Sequence'])
					tempjfinalkeys=jd.keys()
					subpepinfodic={}

					for i in pepetidebasedinfoCol:
						try:
							subpepinfodic[i]=jd[i]
						except KeyError:
							subpepinfodic[i]='NA'
					for j in updatedpepinfocol:
						try:
							tempassaydic[j]=jd[j]
						except KeyError:
							tempassaydic[j]='NA'
					try:
						tempassaydinfo.append({a:jd[a] for a in assaydinfocol})
					except KeyError:
						pass

					try:
						tempgradients.append(jd['Gradients'])
					except KeyError:
						tempgradients.append('NA')

					try:
						temptransition.append(jd['Transitions'])
					except KeyError:
						temptransition.append('NA')

					pepSeqPresence.append(jd['Present in human ortholog'])

					try:
						if 'NA' != jd["Biological Matrix"].upper():
							tempPlotSampleLLOQ=str(jd['Sample LLOQ'].encode('ascii','ignore').strip())
							tempPlotSampleLLOQ=tempPlotSampleLLOQ.replace(' (fmol target protein/g extracted protein)','')
							tempPlotSampleLLOQ=dict([tempval.split('|') for tempval in tempPlotSampleLLOQ.split(';')])

							tempPlotULOQ=str(jd['ULOQ'].encode('ascii','ignore').strip())
							tempPlotULOQ=tempPlotULOQ.replace(' (fmol target protein/g extracted protein)','')
							tempPlotULOQ=dict([tempval.split('|') for tempval in tempPlotULOQ.split(';')])

							tempSampleLLOQInfo=str(jd['Sample LLOQ'].encode('ascii','ignore').strip()).split(';')
							tempSampleLLOQInfo=dict([tempval.split('|') for tempval in tempSampleLLOQInfo])

							tempULOQInfo=str(jd['ULOQ'].encode('ascii','ignore').strip()).split(';')
							tempULOQInfo=dict([tempval.split('|') for tempval in tempULOQInfo])

							tempSampleAllLLOQ=jd['All Concentration Range Data-Sample LLOQ Based']
							tempSampleAllData=jd['All Concentration Range Data']
							tempMinMaxConDic={}
							tempConVal=[[str(al.split('|')[2]),float(al.split('|')[6].encode('ascii','ignore').strip().replace(' (fmol target protein/g extracted protein)',''))] for al in tempSampleAllData.split(';')]
							for ali in tempConVal:
								if ali[0] in tempMinMaxConDic:
									tempMinMaxConDic[ali[0]].append(ali[1])
								else:
									tempMinMaxConDic[ali[0]]=[ali[1]]							

							if jd['All Concentration Range Data-Sample LLOQ Based'] != 'NA':

								for sal in tempSampleAllLLOQ.split(';'):
									tempSampleAllLLOQInfo=sal.split('|')
									if tempSampleAllLLOQInfo[-1].upper() !='NA' and len(tempSampleAllLLOQInfo)>1:
										if concenView.has_key(tempSampleAllLLOQInfo[2]):
											concenView[tempSampleAllLLOQInfo[2]].append(float(tempSampleAllLLOQInfo[-3].split('(')[0].strip()))
										else:
											concenView[tempSampleAllLLOQInfo[2]]=[float(tempSampleAllLLOQInfo[-3].split('(')[0].strip())]
							else:
								for sampL in tempSampleLLOQInfo:
									if (max(tempMinMaxConDic[str(sampL)]) < float(tempSampleLLOQInfo[str(sampL)].split('(')[0].strip())) and (min(tempMinMaxConDic[str(sampL)]) < float(tempSampleLLOQInfo[str(sampL)].split('(')[0].strip())):
										concenView[sampL]="<"+str(tempSampleLLOQInfo[sampL]).split('(')[0].strip()+"(Sample LLOQ-"+str(sampL)+")"
									elif (max(tempMinMaxConDic[str(sampL)]) > float(tempSampleLLOQInfo[str(sampL)].split('(')[0].strip())) and (min(tempMinMaxConDic[str(sampL)]) > float(tempSampleLLOQInfo[str(sampL)].split('(')[0].strip())):
										concenView[sampL]=">"+str(tempULOQInfo[sampL]).split('(')[0].strip()+"(ULOQ-"+str(sampL)+")"
									else:
										concenView[sampL]="<"+str(tempSampleLLOQInfo[sampL]).split('(')[0].strip()+"(Sample LLOQ-"+str(sampL)+")<br>"+">"+str(tempULOQInfo[sampL]).split('(')[0].strip()+"(ULOQ-"+str(sampL)+")"

							tempMatrix=str(jd["Biological Matrix"]).split('<br/>')
							if '<br>' in str(jd["Biological Matrix"]):
								tempMatrix=str(jd["Biological Matrix"]).split('<br>')
							conQSeq=str(jd["Sex"]).split('<br/>')
							if '<br>' in str(jd["Sex"]):
								conQSeq=str(jd["Sex"]).split('<br>')
							conQStrain=str(jd["Strain"]).split('<br/>')
							if '<br>' in str(jd["Strain"]):
								conQStrain=str(jd["Strain"]).split('<br>')
							concenQuery='|'.join(conQSeq)+'@'+'|'.join(conQStrain)+'@'+'|'.join(tempMatrix)+'@'+str(jd["Knockout"])+'@'+pepseq+'@'+uniprotid
							concenQuery=concenQuery.replace('/','!')
							coninfo=(jd['Summary Concentration Range Data'].strip()).split(';')
							addedType=[]
							tempdetailslist=[]
							typeOfbiomat=[]
							typeOfsex=[]
							typeOfstrain=[]
							typeOfknocout=[]
							if len(coninfo)>0:
								for c in coninfo:
									subconinfo=c.split('|')
									dataAdded=str(subconinfo[4])+'@'+str(subconinfo[3])+'@'+str(subconinfo[2])+'@'+str(subconinfo[0])+'@'+str(subconinfo[1])+'@'+pepseq+'@'+uniprotid
									if 'NA' in subconinfo[6] and str(subconinfo[2]) in tempSampleLLOQInfo:
										if (max(tempMinMaxConDic[str(subconinfo[2])]) < float(tempSampleLLOQInfo[subconinfo[2]].split('(')[0].strip())) and (min(tempMinMaxConDic[str(subconinfo[2])]) < float(tempSampleLLOQInfo[subconinfo[2]].split('(')[0].strip())):
											 subconinfo[6]="<"+str(tempSampleLLOQInfo[subconinfo[2]]).split('(')[0].strip()+"(Sample LLOQ-"+str(subconinfo[2])+")"
										elif (max(tempMinMaxConDic[str(subconinfo[2])]) > float(tempSampleLLOQInfo[subconinfo[2]].split('(')[0].strip())) and (min(tempMinMaxConDic[str(subconinfo[2])]) > float(tempSampleLLOQInfo[subconinfo[2]].split('(')[0].strip())):
											subconinfo[6]= ">"+str(tempULOQInfo[subconinfo[2]]).split('(')[0].strip()+"(ULOQ-"+str(subconinfo[2])+")"
										else:
											subconinfo[6]= "<"+str(tempSampleLLOQInfo[subconinfo[2]]).split('(')[0].strip()+"(Sample LLOQ-"+str(subconinfo[2])+")<br>" + ">"+str(tempULOQInfo[subconinfo[2]]).split('(')[0].strip()+"(ULOQ-"+str(subconinfo[2])+")"

									tempconlist=[subconinfo[6],subconinfo[4],pepseq,uniprotid,str(subconinfo[2]),str(subconinfo[3]),str(subconinfo[0]),str(subconinfo[1])]
									if dataAdded not in addedType:
										typeOfbiomat.append(tempconlist[4])
										typeOfsex.append(tempconlist[1])
										typeOfstrain.append(tempconlist[5])
										typeOfknocout.append(tempconlist[7])
										addedType.append(dataAdded)
										tempdetailslist.append(tempconlist)
							typeOfbiomat=list(set(typeOfbiomat))
							typeOfsex=list(set(typeOfsex))
							typeOfstrain=list(set(typeOfstrain))
							typeOfknocout=list(set(typeOfknocout))
							for b in typeOfbiomat:
								templist=[]
								tempsex=[]
								tempstrain=[]
								tempknockout=[]
								temppanel=[]
								concenVal={}
								ukb=''
								temppepseq=''
								tempUnit=''
								for i in tempdetailslist:
									if b == i[4]:
										tempsex.append(i[1])
										tempstrain.append(i[5])
										tempknockout.append(i[7])
										temppanel.append(i[6])
										if concenVal.has_key(i[4]):
											concenVal[i[4]].append(i[0].split('(')[0].strip())
										else:
											concenVal[i[4]]=[i[0].split('(')[0].strip()]
										if '<' in i[0] or '>' in i[0]:
											tempUnit=''.join(i[0].split('(')[1:-1]).strip()
										else:
											tempUnit=i[0].split('(')[-1].strip()
										ukb=i[3]
										temppepseq=i[2]
								tempQuery='|'.join(list(set(tempsex)))+'@'+'|'.join(list(set(tempstrain)))+'@'+b+'@'+'|'.join(list(set(tempknockout)))+'@'+temppepseq+'@'+ukb
								tempQuery=tempQuery.replace('/','!')
								tempconcenVal='NA'
								tempUnit=tempUnit.replace('fmol target protein/u','fmol target protein/µ')
								tempUnit=tempUnit.replace('fmol target protein/g','fmol target protein/µg')
								countSampleLLOQ=len([mc for mc in concenVal[b] if '<' in mc or '>' in mc])
								if len(concenVal[b]) ==countSampleLLOQ:
									if len(list(set(concenVal[b])))==1:
										if '<' in list(set(concenVal[b]))[0]:
											tempconcenVal=list(set(concenVal[b]))[0]+"(Sample LLOQ-"+str(b)+")"
										else:
											tempconcenVal=list(set(concenVal[b]))[0]+"(ULOQ-"+str(b)+")"
									else:
										tempconcenVal='<br>'.join([ul+"(Sample LLOQ-"+str(b)+")" if '<' in ul else ul+"(ULOQ-"+str(b)+")" for ul in concenVal[b]])
								else:
									tempVal=[float(j) for j in concenVal[b] if '<' not in str(j) and '>' not in str(j)]
									if len(tempVal)>0:
										tempconcenVal=str(mean(tempVal))
								templist=[tempconcenVal,'<br>'.join(list(set(tempsex))),temppepseq,ukb,b,'<br>'.join(list(set(tempstrain))),'<br>'.join(list(set(tempknockout))),tempQuery,tempPlotSampleLLOQ[b],tempPlotULOQ[b]]
								biologicalmatrixdetails.append(templist)
							for s in typeOfsex:
								templist=[]
								tempbiomat=[]
								tempstrain=[]
								tempknockout=[]
								temppanel=[]
								concenVal={}
								ukb=''
								temppepseq=''
								tempUnit=''
								for i in tempdetailslist:
									if s == i[1]:
										tempbiomat.append(i[4])
										tempstrain.append(i[5])
										tempknockout.append(i[7])
										temppanel.append(i[6])
										if concenVal.has_key(i[4]):
											concenVal[i[4]].append(i[0].split('(')[0].strip())
										else:
											concenVal[i[4]]=[i[0].split('(')[0].strip()]
										if '<' in i[0] or '>' in i[0]:
											tempUnit=''.join(i[0].split('(')[1:-1]).strip()
										else:
											tempUnit=i[0].split('(')[-1].strip()
										ukb=i[3]
										temppepseq=i[2]
								tempQuery=s+'@'+'|'.join(list(set(tempstrain)))+'@'+'|'.join(list(set(tempbiomat)))+'@'+'|'.join(list(set(tempknockout)))+'@'+temppepseq+'@'+ukb
								tempQuery=tempQuery.replace('/','!')
								for tbm in list(set(tempbiomat)):
									tempconcenVal='NA'
									tempUnit=tempUnit.replace('fmol target protein/u','fmol target protein/µ')
									tempUnit=tempUnit.replace('fmol target protein/g','fmol target protein/µg')
									countSampleLLOQ=len([mc for mc in concenVal[tbm] if '<' in mc or '>' in mc])

									if len(concenVal[tbm]) ==countSampleLLOQ:
										if len(list(set(concenVal[tbm])))==1:
											if '<' in list(set(concenVal[tbm]))[0]:
												tempconcenVal=list(set(concenVal[tbm]))[0]+"(Sample LLOQ-"+str(tbm)+")"
											else:
												tempconcenVal=list(set(concenVal[tbm]))[0]+"(ULOQ-"+str(tbm)+")"
										else:
											tempconcenVal='<br>'.join([ul+"(Sample LLOQ-"+str(tbm)+")" if '<' in ul else ul+"(ULOQ-"+str(tbm)+")" for ul in concenVal[tbm]])
									else:
										tempVal=[float(j) for j in concenVal[tbm] if '<' not in str(j) and '>' not in str(j)]
										if len(tempVal)>0:
											tempconcenVal=str(mean(tempVal))

									templist=[tempconcenVal,s,temppepseq,ukb,tbm,'<br>'.join(list(set(tempstrain))),'<br>'.join(list(set(tempknockout))),tempQuery,tempPlotSampleLLOQ[tbm],tempPlotULOQ[tbm]]
									sexdetails.append(templist)
							for st in typeOfstrain:
								templist=[]
								tempbiomat=[]
								tempsex=[]
								tempknockout=[]
								temppanel=[]
								concenVal={}
								ukb=''
								temppepseq=''
								tempUnit=''
								for i in tempdetailslist:
									if st == i[5]:
										tempbiomat.append(i[4])
										tempsex.append(i[1])
										tempknockout.append(i[7])
										temppanel.append(i[6])
										if concenVal.has_key(i[4]):
											concenVal[i[4]].append(i[0].split('(')[0].strip())
										else:
											concenVal[i[4]]=[i[0].split('(')[0].strip()]
										if '<' in i[0] or '>' in i[0]:
											tempUnit=''.join(i[0].split('(')[1:-1]).strip()
										else:
											tempUnit=i[0].split('(')[-1].strip()
										ukb=i[3]
										temppepseq=i[2]
								tempQuery='|'.join(list(set(tempsex)))+'@'+st+'@'+'|'.join(list(set(tempbiomat)))+'@'+'|'.join(list(set(tempknockout)))+'@'+temppepseq+'@'+ukb
								tempQuery=tempQuery.replace('/','!')
								for tbm in list(set(tempbiomat)):
									tempconcenVal='NA'
									tempUnit=tempUnit.replace('fmol target protein/u','fmol target protein/µ')
									tempUnit=tempUnit.replace('fmol target protein/g','fmol target protein/µg')
									countSampleLLOQ=len([mc for mc in concenVal[tbm] if '<' in mc or '>' in mc])
									if len(concenVal[tbm]) ==countSampleLLOQ:
										if len(list(set(concenVal[tbm])))==1:
											if '<' in list(set(concenVal[tbm]))[0]:
												tempconcenVal=list(set(concenVal[tbm]))[0]+"(Sample LLOQ-"+str(tbm)+")"
											else:
												tempconcenVal=list(set(concenVal[tbm]))[0]+"(ULOQ-"+str(tbm)+")"
										else:
											tempconcenVal='<br>'.join([ul+"(Sample LLOQ-"+str(tbm)+")" if '<' in ul else ul+"(ULOQ-"+str(tbm)+")" for ul in concenVal[tbm]])
									else:
										tempVal=[float(j) for j in concenVal[tbm] if '<' not in str(j) and '>' not in str(j)]
										if len(tempVal)>0:
											tempconcenVal=str(mean(tempVal))
									templist=[tempconcenVal,'<br>'.join(list(set(tempsex))),temppepseq,ukb,tbm,st,'<br>'.join(list(set(tempknockout))),tempQuery,tempPlotSampleLLOQ[tbm],tempPlotULOQ[tbm]]
									straindetails.append(templist)
							for k in typeOfknocout:
								templist=[]
								tempbiomat=[]
								tempsex=[]
								tempstrain=[]
								temppanel=[]
								concenVal={}
								ukb=''
								temppepseq=''
								tempUnit=''
								for i in tempdetailslist:
									if k == i[7]:
										tempbiomat.append(i[4])
										tempsex.append(i[1])
										tempstrain.append(i[5])
										temppanel.append(i[6])
										if concenVal.has_key(i[4]):
											concenVal[i[4]].append(i[0].split('(')[0].strip())
										else:
											concenVal[i[4]]=[i[0].split('(')[0].strip()]
										if '<' in i[0] or '>' in i[0]:
											tempUnit=''.join(i[0].split('(')[1:-1]).strip()
										else:
											tempUnit=i[0].split('(')[-1].strip()
										ukb=i[3]
										temppepseq=i[2]
								tempQuery='|'.join(list(set(tempsex)))+'@'+'|'.join(list(set(tempstrain)))+'@'+'|'.join(list(set(tempbiomat)))+'@'+k+'@'+temppepseq+'@'+ukb
								tempQuery=tempQuery.replace('/','!')
								for tbm in list(set(tempbiomat)):
									tempconcenVal='NA'
									tempUnit=tempUnit.replace('fmol target protein/u','fmol target protein/µ')
									tempUnit=tempUnit.replace('fmol target protein/g','fmol target protein/µg')
									countSampleLLOQ=len([mc for mc in concenVal[tbm] if '<' in mc or '>' in mc])
									if len(concenVal[tbm]) ==countSampleLLOQ:
										if len(list(set(concenVal[tbm])))==1:
											if '<' in list(set(concenVal[tbm]))[0]:
												tempconcenVal=list(set(concenVal[tbm]))[0]+"(Sample LLOQ-"+str(tbm)+")"
											else:
												tempconcenVal=list(set(concenVal[tbm]))[0]+"(ULOQ-"+str(tbm)+")"
										else:
											tempconcenVal='<br>'.join([ul+"(Sample LLOQ-"+str(tbm)+")" if '<' in ul else ul+"(ULOQ-"+str(tbm)+")" for ul in concenVal[tbm]])
									else:
										tempVal=[float(j) for j in concenVal[tbm] if '<' not in str(j) and '>' not in str(j)]
										if len(tempVal)>0:
											tempconcenVal=str(mean(tempVal))
									templist=[tempconcenVal,'<br>'.join(list(set(tempsex))),temppepseq,ukb,tbm,'<br>'.join(list(set(tempstrain))),k,tempQuery,tempPlotSampleLLOQ[tbm],tempPlotULOQ[tbm]]
									knockoutdetails.append(templist)

						tempconcendata.append(jd['Summary Concentration Range Data'])
					except KeyError:
						tempconcendata.append('NA')
					subpepinfodic.pop('Peptide ID', None)
					try:
						tempmean=[]
						tempMin=[]
						tempMax=[]
						if len(concenView)>0:
							for c in concenView:
								if "<" not in concenView[c]:
									tmean=c+':'+str(round(mean(concenView[c]),2))+unitDic[c]
									tmean=tmean.encode('ascii','ignore')
									tempmean.append(tmean)
									
									tmin=c+':'+str(round(min(concenView[c]),2))+unitDic[c]
									tmin=tmin.encode('ascii','ignore')
									tempMin.append(tmin)

									tmax=c+':'+str(round(max(concenView[c]),2))+unitDic[c]
									tmax=tmax.encode('ascii','ignore')
									tempMax.append(tmax)
								else:
									concenView[c]=concenView[c].replace('fmol target protein/u','fmol target protein/µ')
									concenView[c]=concenView[c].replace('fmol target protein/g','fmol target protein/µg')
									tempmean.append(concenView[c])
									tempMin.append(concenView[c])
									tempMax.append(concenView[c])
						subpepinfodic["Concentration View"]='<br/>'.join(tempmean)+'|'+'<br/>'.join(tempMin)+'|'+'<br/>'.join(tempMax)
						subpepinfodic["Concentration View"]=subpepinfodic["Concentration View"].replace('(fmol target protein/µg extracted protein)','')
						tempconcenlist.append(subpepinfodic["Concentration View"])
					except KeyError:
						tempconcenlist.append('NA')
					if len(tempdiffcol) >0:
						tempupdatedUniDic={key: jd[key] for key in tempdiffcol}
			tempassaydic['concenQuery']=concenQuery
			tempassaydic['Assay Information']=tempassaydinfo
			tempgradients=list(set(tempgradients))
			tempassaydic['Gradients']=tempgradients
			temptransition=list(set(temptransition))
			tempassaydic['Transitions']=temptransition
			tempassaydic['Transitions']=temptransition
			tempconcendata=list(set(tempconcendata))
			tempassaydic['Summary Concentration Range Data']=tempconcendata
			tempconcenlist=list(set(tempconcenlist))
			if len(tempconcenlist)>1:
				tempconcenlist.remove('NA')
			try:
				tempassaydic['Concentration View']=tempconcenlist[0]
				tempassaydic['Concentration View']=tempassaydic['Concentration View'].replace('(fmol target protein/µg extracted protein)','')
				tempassaydic['Concentration View']=tempassaydic['Concentration View'].replace('(fmol target protein/ug extracted protein)','')
			except IndexError:
				tempassaydic['Concentration View']='NA'
			peptidebasedinfo.append(tempassaydic)
		biologicalmatrix=[x for i in biologicalmatrix for x in i.split('<br/>')]
		biologicalmatrix=list(set(biologicalmatrix))
		if len(biologicalmatrix) >0:
			if 'NA' in biologicalmatrix:
				biologicalmatrix.remove('NA')

		biologicalmatrix='<br/>'.join(biologicalmatrix)
		try:
			tempupdatedUniDic["Biological Matrix"]=biologicalmatrix
		except IndexError:
			tempupdatedUniDic["Biological Matrix"]='NA'

		pepSeqPresence=list(set(pepSeqPresence))
		if len(pepSeqPresence) >1:
			if 'No' in pepSeqPresence:
				pepSeqPresence.remove('No')
		tempmatchingpepseq=list(set(tempepepseqlist))

		tempupdatedUniDic['Concentration Range']=tempupdatedUniDic['Concentration Range'].replace('(fmol target protein/µg extracted protein)','')
		tempupdatedUniDic['Concentration Range']=tempupdatedUniDic['Concentration Range'].replace('Mean Conc.:','')
		if ':' in tempupdatedUniDic['Concentration Range']:
			tempConcRange=tempupdatedUniDic['Concentration Range'].split('<br/>')
			tempConcRange=[str(fI).strip() for fI in tempConcRange if len(str(fI).strip())>0]
			tempConcRangeDic={}
			for cR in tempConcRange:
				crInfo=cR.split(':')
				tempConcRangeDic[crInfo[0]]=crInfo[1]
			newtempConcRange=[]
			for fK in tempConcRangeDic:
				newtempConcRange.append(fK+':'+tempConcRangeDic[fK])
			tempupdatedUniDic['Concentration Range']='<br/>'.join(newtempConcRange)

		tempupdatedUniDic['Peptide Sequence']='<br>'.join(map(str,tempmatchingpepseq))
		tempupdatedUniDic['Peptide Based Info']=peptidebasedinfo
		tempupdatedUniDic['Gene Expression Data']=geneExpData
		tempupdatedUniDic['All Concentration Range Data']=concendataAll
		tempupdatedUniDic['All Concentration Range Data-Sample LLOQ Based']=concendataALLSampleLLOQ
		tempupdatedUniDic['Assay Info']=','.join(map(str, peptidebasedinfo))
		tempupdatedUniDic['Assay Info']=tempupdatedUniDic['Assay Info'].replace('Peptide ID','Assay ID')
		biologicalmatrixdetails=[list(tupl) for tupl in {tuple(item) for item in biologicalmatrixdetails}]
		tempupdatedUniDic['Biological Matrix Details']=biologicalmatrixdetails

		sexdetails=[list(tupl) for tupl in {tuple(item) for item in sexdetails}]
		tempupdatedUniDic['Sex Details']=sexdetails

		straindetails=[list(tupl) for tupl in {tuple(item) for item in straindetails}]
		tempupdatedUniDic['Strain Details']=straindetails
		knockoutdetails=[list(tupl) for tupl in {tuple(item) for item in knockoutdetails}]
		tempupdatedUniDic['Knockout Details']=knockoutdetails
		tempupdatedUniDic['Present in human ortholog']=pepSeqPresence


		tempupdatedUniDic['Sex']=tempupdatedUniDic['Sex'].replace('|','<br>')
		tempupdatedUniDic['Sex']=tempupdatedUniDic['Sex'].replace('<br/>','<br>')
		tempupdatedUniDic['Strain']=tempupdatedUniDic['Strain'].replace('|','<br>')
		tempupdatedUniDic['Strain']=tempupdatedUniDic['Strain'].replace('<br/>','<br>')
		tempupdatedUniDic['Biological Matrix']=tempupdatedUniDic['Biological Matrix'].replace('|','<br>')
		tempupdatedUniDic['Biological Matrix']=tempupdatedUniDic['Biological Matrix'].replace('<br/>','<br>')

		if '<br>' in tempupdatedUniDic['Sex']:
			sexData.append(tempupdatedUniDic['Sex'].split('<br>'))
		else:
			sexData.append(tempupdatedUniDic['Sex'])

		if '<br>' in tempupdatedUniDic['Strain']:
			strainData.append(tempupdatedUniDic['Strain'].split('<br>'))
		else:
			strainData.append(tempupdatedUniDic['Strain'])

		if '<br>' in tempupdatedUniDic['Biological Matrix']:
			biomatrixData.append(tempupdatedUniDic['Biological Matrix'].split('<br>'))
		else:
			biomatrixData.append(tempupdatedUniDic['Biological Matrix'])

		updatedUniInfo.append(tempupdatedUniDic)

		if len(querybiomatrix) >0:
			if querybiomatrix in str(tempupdatedUniDic["Biological Matrix"]).lower():
				biomatrixContainUniId.append(tempupdatedUniDic["UniProtKB Accession"])
	foldChangeQueryData={
		'Biological Matrix':sorted(list(set(flatten(biomatrixData)))),
		'Sex':sorted(list(set(flatten(sexData)))),
		'Strain':sorted(list(set(flatten(strainData))))
	}
	if len(sorted(list(set(flatten(biomatrixData)))))>1:
		foldchangeData['Biological Matrix']=sorted(list(set(flatten(biomatrixData))))
	if len(sorted(list(set(flatten(sexData)))))>1:
		foldchangeData['Sex']=sorted(list(set(flatten(sexData))))
	if len(sorted(list(set(flatten(strainData)))))>1:
		foldchangeData['Strain']=sorted(list(set(flatten(strainData))))

	foldchangeData['foldChangeQueryData']=foldChangeQueryData
		
	finalupdatedUniInfo["data"]=updatedUniInfo[:10000]
	return finalupdatedUniInfo,biomatrixContainUniId,foldchangeData


# function to generate peptidebased info into nested json format
def pepbasedInfoRESTAPI(updatedresult,uniprotpepinfo):
	restApiColname=['Mouse UniProtKB accession','Mouse Protein name','Mouse Gene','Organism','Subcellular localization',\
	'Strain','Mutant','Biological Matrix','UniProtKB accession of human ortholog','Human ortholog','Human Gene',\
	'Available assays in human ortholog','Molecular pathway(s) Mouse','Molecular pathway(s) Human',\
	'Involvement in disease-Human(UniProt)','Involvement in disease-Human(DisGeNET)',\
	'GO Mouse','GO Human','Drug associations-Human','Gene Expression Data']

	pepetidebasedinfoCol=['Assay ID','Peptide sequence','Summary Concentration Range Data',\
	'All Concentration Range Data-Sample LLOQ Based','Labeled Residues','Molecular Weight',\
	'GRAVY Score','Transitions','Retention Time','Percent Organic Solution',\
	'Gradients','LLOQ','ULOQ','Sample LLOQ','Unique in protein','Present in isoforms']
	updatedpepinfocol=['Peptide sequence',"Unique in protein",'Present in isoforms',\
	'Present in human ortholog','Unique in human protein','Present in human isoforms',\
	"Peptide unique in user's database", "Peptide in user's database","Panel"]
	assaydinfocol=['Molecular Weight','GRAVY Score','LLOQ','ULOQ','Sample LLOQ']
	updatedUniInfo=[]

	for uniprotid in uniprotpepinfo:
		tempupdatedUniDic={}
		peptidebasedinfo=[]
		tempmatchingpepseq=''
		tempepepseqlist=[]
		biologicalmatrix=[]
		for pepseq in list(set(uniprotpepinfo[uniprotid])):
			tempassaydic={}
			tempconcenlist=[]
			tempassaydinfo=[]
			tempgradients=[]
			tempAnalytInfo=[]
			tempRetTimeInfo=[]
			temptransition=[]
			sumtempconcendata=[]
			alltempconcendata=[]
			alltempconcendataSampleLLOQ=[]

			for jd in updatedresult:
				if uniprotid in jd['Mouse UniProtKB accession'] and pepseq in jd['Peptide sequence']:
					biologicalmatrix.append(jd["Biological Matrix"])
					tempepepseqlist.append(jd['Peptide sequence'])
					tempjfinalkeys=jd.keys()
					subpepinfodic={}
					for i in pepetidebasedinfoCol:
						try:
							subpepinfodic[i]=jd[i]
						except KeyError:
							subpepinfodic[i]='NA'
					for j in updatedpepinfocol:
						try:
							tempassaydic[j]=jd[j]
						except KeyError:
							tempassaydic[j]='NA'
					try:
						tempassaydinfo.append({a:jd[a] for a in assaydinfocol})
					except KeyError:
						pass

					try:
						tempgradients.append(jd['Gradients'])
					except KeyError:
						tempgradients.append('NA')

					try:
						tempAnalytInfo.append(jd['Analytical inofrmation'])
					except KeyError:
						tempAnalytInfo.append('NA')

					try:
						tempRetTimeInfo.append(jd['Retention Time'])
					except KeyError:
						tempRetTimeInfo.append('NA')

					try:
						temptransition.append(jd['Transitions'])
					except KeyError:
						temptransition.append('NA')

					try:
						sumtempconcendata.append(jd['Summary Concentration Range Data'])
					except KeyError:
						sumtempconcendata.append('NA')
					try:
						alltempconcendata.append(jd['All Concentration Range Data'])
					except KeyError:
						alltempconcendata.append('NA')
					try:
						alltempconcendataSampleLLOQ.append(jd['All Concentration Range Data-Sample LLOQ Based'])
					except KeyError:
						alltempconcendataSampleLLOQ.append('NA')
					subpepinfodic.pop('Peptide ID', None)

					if len(restApiColname) >0:
						tempupdatedUniDic={key: jd[key] for key in restApiColname}

			tempassaydic['Assay Information']=tempassaydinfo
			tempgradients=list(set(tempgradients))
			tempAnalytInfo=list(set(tempAnalytInfo))
			tempassaydic['Gradients']=tempgradients
			tempassaydic['Analytical inofrmation']=tempAnalytInfo
			tempRetTimeInfo=list(set(tempRetTimeInfo))
			tempassaydic['Retention Time']=tempRetTimeInfo
			temptransition=list(set(temptransition))
			temptransition=[x for item in temptransition for x in item.split(';')]
			tempassaydic['Transitions']=temptransition
			sumtempconcendata=list(set(sumtempconcendata))
			sumtempconcendata=['|'.join(x.split('|')[1:]) for item in sumtempconcendata for x in item.split(';')]
			alltempconcendata=list(set(alltempconcendata))
			alltempconcendata=['|'.join(x.split('|')[1:]) for item in alltempconcendata for x in item.split(';')]
			alltempconcendataSampleLLOQ=list(set(alltempconcendataSampleLLOQ))
			alltempconcendataSampleLLOQ=['|'.join(x.split('|')[1:]) for item in alltempconcendataSampleLLOQ for x in item.split(';')]
			tempassaydic['Summary Concentration Range Data']=sumtempconcendata
			#tempassaydic['All Concentration Range Data']=alltempconcendata
			tempassaydic['All Concentration Range Data-Sample LLOQ Based']=alltempconcendataSampleLLOQ
			tempconcenlist=list(set(tempconcenlist))
			peptidebasedinfo.append(tempassaydic)

		biologicalmatrix=[x for i in biologicalmatrix for x in i.split('<br/>')]
		biologicalmatrix=list(set(biologicalmatrix))
		if len(biologicalmatrix) >0:
			if 'NA' in biologicalmatrix:
				biologicalmatrix.remove('NA')
		try:
			tempupdatedUniDic["Biological Matrix"]=biologicalmatrix[0]
		except IndexError:
			tempupdatedUniDic["Biological Matrix"]='NA'

		tempupdatedUniDic['Peptide Assay']=peptidebasedinfo
		updatedUniInfo.append(tempupdatedUniDic)
	return updatedUniInfo<file_sep>/backend/updatefile/addModCol.py
import urllib,urllib2
from bioservices.kegg import KEGG
import os,subprocess,psutil,re,shutil,datetime,sys,glob
from operator import itemgetter
import numpy as np
import random, time
from itertools import count, groupby
import pandas as pd
import csv
import json
import ctypes

def addModCol():
	print ("Adding or updating data, job starts",str(datetime.datetime.now()))
	mousepeptrackfilename='mouse_report_peptrack_data.csv'
	#increase the field size of CSV
	csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2))
	mousePeptrackData=[]
	with open(mousepeptrackfilename) as csvfile:
		reader = csv.DictReader(csvfile, delimiter='\t')
		for row in reader:
			mousePeptrackData.append(row)

	homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
	filename='ReportBook_mother_file.csv'
	filepath = os.path.join(homedir, 'src/qmpkbmotherfile', filename)

	columns=['UniProtKB Accession','Protein','Gene','Organism','Organism ID','SubCellular','Peptide Sequence',\
	'Summary Concentration Range Data','All Concentration Range Data','All Concentration Range Data-Sample LLOQ Based',\
	'Peptide ID','Special Residues','Molecular Weight','GRAVY Score','Transitions','Retention Time',\
	'Analytical inofrmation','Gradients','AAA Concentration','CZE Purity','Panel','Knockout','LLOQ','ULOQ','Sample LLOQ',\
	'Protocol','Trypsin','QC. Conc. Data','Unique in protein','Present in isoforms',\
	'Mouse Kegg Pathway Name','Mouse Kegg Pathway','Human Disease Name','Human UniProt DiseaseData','Human UniProt DiseaseData URL',\
	'Human DisGen DiseaseData','Human DisGen DiseaseData URL','Mouse Go ID','Mouse Go Name','Mouse Go Term','Mouse Go','Human Drug Bank',\
	'Human UniProtKB Accession','Human ProteinName','Human Gene','Human Kegg Pathway Name','Human Kegg Pathway',\
	'Human Go ID','Human Go Name','Human Go Term','Human Go','UniprotKb entry status','Concentration View','Strain','Sex',\
	'Biological Matrix','Concentration Range']
	finalSexData=[]
	finalStrainData=[]
	finalknockoutData=[]
	finalBioMatData=[]
	finalPanelData=[]
	finalResultData=[]
	finalResultData.append(columns)
	modrepfile="modreprot.csv"
	with open(filepath,'r') as f:
		repreader = csv.DictReader(f,delimiter="\t")
		for row in repreader:
			if len(row['UniProtKB Accession'].strip())>0:
				if len(row['Summary Concentration Range Data'].strip())>0  and (str(row['Summary Concentration Range Data']).strip()).lower() !='na':
					coninfo=(row['Summary Concentration Range Data'].strip()).split(';')
					if len(coninfo)>0:
						subconinfo=coninfo[0].split('|')
						condata="Mean Conc.:"+str(subconinfo[6])+"<br/>Matix:"+str(subconinfo[2])
						tempSampleLLOQInfo=str(row['Sample LLOQ'].strip()).split(';')
						if str(subconinfo[6]) =='NA':
							for samLLOQ in tempSampleLLOQInfo:
								if str(subconinfo[2]) in samLLOQ.split('|'):
									condata="<"+str(samLLOQ.split('|')[1].strip())+"(Sample LLOQ-"+str(subconinfo[2])+")"
						row['Concentration View']=condata
						strainlist=[]
						sexlist=[]
						matrixlist=[]
						meanConclist=[]
						unitlist=[]
						for i in coninfo:
							l=i.split('|')
							finalSexData.append(l[4])
							finalStrainData.append(l[3])
							finalBioMatData.append(l[2])
							strainlist.append(l[3])
							sexlist.append(l[4])
							matrixlist.append(l[2])
							meanConcData=l[6]
							unitlist.append(l[6].split(' (')[-1])
							if meanConcData.upper() !='NA':
								meanConclist.append(l[2]+':'+str(meanConcData))
							else:
								for samXLLOQ in tempSampleLLOQInfo:
									if str(l[2]) in samXLLOQ.split('|'):
										meanConclist.append("<"+str(samXLLOQ.split('|')[1].strip())+"(Sample LLOQ-"+str(l[2])+")")
						if len(strainlist)>0:
							strainlist =list(set(strainlist))
							if len(strainlist)>1:
								strainlist=[x for x in strainlist if 'na' != x.lower()]
							sexlist =list(set(sexlist))
							if len(sexlist)>1:
								sexlist=[x for x in sexlist if 'na' != x.lower()]
							matrixlist =list(set(matrixlist))
							if len(matrixlist)>1:
								matrixlist=[x for x in matrixlist if 'na' != x.lower()]
							row['Strain']='|'.join(list(set(strainlist)))
							row['Sex']='|'.join(list(set(sexlist)))
							row['Biological Matrix']='|'.join(list(set(matrixlist)))
							countSampleLLOQ=len([mc for mc in meanConclist if 'Sample LLOQ' in mc])
							if len(meanConclist) ==countSampleLLOQ:
								meanConclist=list(set(meanConclist))
								row['Concentration Range']='<br/>'.join(meanConclist[:2])
							else:
								meanConclist=[m for m in meanConclist if 'Sample LLOQ' not in m]
								meanConclist=list(set(meanConclist))
								row['Concentration Range']= 'Mean Conc.:'+'<br/>'+'<br/>'.join(meanConclist[:2])
								#row['Concentration Range']="Max. Mean Conc.:"+str(max(meanConclist))+' ('+str(unitlist[meanConclist.index(max(meanConclist))])+"<br/>Min. Mean Conc.:"+str(min(meanConclist))+' ('+str(unitlist[meanConclist.index(min(meanConclist))])
						else:
							row['Strain']='NA'
							row['Sex']='NA'
							row['Biological Matrix']='NA'
							row['Concentration Range']='NA'
					if len(row['Panel'].strip())>0  and (str(row['Panel']).strip()).lower() !='na':
						panelinfo=(row['Panel'].strip()).split(';')
						for i in panelinfo:
							finalPanelData.append(i)

					if len(row['Knockout'].strip())>0  and (str(row['Knockout']).strip()).lower() !='na':
						knockoutinfo=(row['Knockout'].strip()).split(';')
						for i in knockoutinfo:
							finalknockoutData.append(i)
				templist=[]
				for c in columns:
					templist.append(row[c])
				finalResultData.append(templist)
	#finalknockoutData.append('Mutant type')
	finalSexData=list(set(finalSexData))
	if len(finalSexData)>1:
		finalSexData=[x for x in finalSexData if 'na' != x.lower()]
	finalknockoutData=list(set(finalknockoutData))
	if len(finalknockoutData)>1:
		finalknockoutData=[x for x in finalknockoutData if 'na' != x.lower()]
	finalStrainData=list(set(finalStrainData))
	if len(finalStrainData)>1:
		finalStrainData=[x for x in finalStrainData if 'na' != x.lower()]
	finalBioMatData=list(set(finalBioMatData))
	if len(finalBioMatData)>1:
		finalBioMatData=[x for x in finalBioMatData if 'na' != x.lower()]
	finalPanelData=list(set(finalPanelData))
	if len(finalPanelData)>1:
		finalPanelData=[x for x in finalPanelData if 'na' != x.lower()]

	finalresultlist=[]
	finalSexData.sort()
	finalStrainData.sort()
	finalBioMatData.sort()
	finalknockoutData.sort()
	finalPanelData=sorted(finalPanelData, key=lambda p: int(p.split('-')[1]))
	for s in finalSexData:
		finalresultdic={}
		finalresultdic["id"]=s
		finalresultdic["selectid"]="sex"
		finalresultdic["name"]=s
		finalresultlist.append(finalresultdic)

	for k in finalknockoutData:
		finalresultdic={}
		finalresultdic["id"]=k
		finalresultdic["selectid"]="mutant"
		finalresultdic["name"]=k
		finalresultlist.append(finalresultdic)

	for st in finalStrainData:
		finalresultdic={}
		finalresultdic["id"]=st
		finalresultdic["selectid"]="strain"
		finalresultdic["name"]=st
		finalresultlist.append(finalresultdic)

	for bm in finalBioMatData:
		finalresultdic={}
		finalresultdic["id"]=bm
		finalresultdic["selectid"]="biologicalMatrix"
		finalresultdic["name"]=bm
		finalresultlist.append(finalresultdic)

	for p in finalPanelData:
		finalresultdic={}
		finalresultdic["id"]=p
		finalresultdic["selectid"]="panel"
		finalresultdic["name"]=p
		finalresultlist.append(finalresultdic)

	finalresultJson={"data":finalresultlist}
	adsearchopfilename='advanceSearchOptions.json'
	adsearchopmovefilepath=os.path.join(homedir, 'updatefile', adsearchopfilename)
	adsearchopfilepath = os.path.join(homedir, 'src/resultFile/jsonData/preLoadData', adsearchopfilename)
	adsearchopfileoutput=open(adsearchopfilename,'w')
	adsearchopfileoutput.write(json.dumps(finalresultJson))
	adsearchopfileoutput.close()


	with open(modrepfile,'wb') as mf:
		mwriter =csv.writer(mf,delimiter='\t')
		mwriter.writerows(finalResultData)


	movefilepath=os.path.join(homedir, 'updatefile', filename)
	os.rename(modrepfile,filename)
	shutil.move(movefilepath,filepath)
	shutil.move(adsearchopmovefilepath,adsearchopfilepath)
	print ("Adding or updating data, job done",str(datetime.datetime.now()))
<file_sep>/backend/src/qmpkbapp/summaryKeggCoverage.py
import os,sys
from operator import itemgetter
import numpy as np
from itertools import count, groupby
import pandas as pd
import ast
from operator import itemgetter

def summarykeggcal(top10keggdict,prodataseries):
	keggpathwaycoverage=[]

	for kskey in top10keggdict:
		keggpathwayname=(kskey.strip()).split('|')[0]
		tempUniqKeggUniIDList=list(set(top10keggdict[kskey]))
		peptrack=[]
		for ckey in prodataseries:
			if "peptidetracker" in ckey.lower():
				peptrack=list(set(prodataseries[ckey]).intersection(tempUniqKeggUniIDList))

		temppeptrack=len(list(set(peptrack)))
		tempTotal=len(list(set(tempUniqKeggUniIDList)))
		templist=[keggpathwayname,tempTotal,temppeptrack]
		keggpathwaycoverage.append(templist)

	unqkeggpathwaycoverage=[list(tupl) for tupl in {tuple(item) for item in keggpathwaycoverage }]
	keggchart=[]
	if len(unqkeggpathwaycoverage)>0:
		sortedkeggpathwaycoverage=sorted(unqkeggpathwaycoverage, key= itemgetter(1), reverse=True)
		keggchart=[['Pathway Name', 'Total unique proteins', 'PeptideTracker']]
		keggchart=keggchart+sortedkeggpathwaycoverage
	return keggchart<file_sep>/backend/src/qmpkbapp/views.py
#!/usr/bin/env.python
# -*- coding: utf-8 -*-
# encoding: utf-8
from __future__ import unicode_literals
from django.utils.encoding import force_text

from django.shortcuts import render

from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework.permissions import IsAdminUser

from qmpkbapp.models import IpAddressInformation

from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.schemas import SchemaGenerator
from rest_framework.permissions import AllowAny
import coreapi,coreschema
from rest_framework.schemas import ManualSchema
from rest_framework_swagger import renderers
import sys,re,os,glob,shutil,subprocess,socket
import urllib,urllib3
import fileinput
from ipware.ip import get_ip
from time import gmtime, strftime,sleep
import csv
import hashlib, random
import datetime
from django.conf import settings
from django.core.mail import send_mail
from django.contrib import messages
from django.core.mail import EmailMultiAlternatives
from django.template import RequestContext
import json,demjson
import uuid
import json as simplejson
import calendar
from django.contrib import auth
from bioservices.kegg import KEGG
from xml.etree import cElementTree as ET
import xmltodict
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from Bio.PDB.Polypeptide import *
from Bio import SeqIO
from requests.exceptions import ConnectionError
import requests
from django.utils.datastructures import MultiValueDictKeyError
from Bio.SeqUtils import seq1
from goatools import obo_parser
from elasticsearch import Elasticsearch,helpers,RequestsHttpConnection
import pandas as pd
from .colName import *
from summaryStat import summaryStatcal
from .calculationprog import *
from .totalpepassay import *
from .modifiedJsondata import *
from .filterSearch import *
from .downLoadData import *
import random
import names
from operator import itemgetter
import ast
from collections import OrderedDict
from itertools import combinations
import pandas as pd
import numpy as np
import operator
from .appTissueInfo import *
#delete after publication
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login,logout
import math
from .adjustP import p_adjust_bh
from scipy.stats import mannwhitneyu
# Import Biopython modules to interact with KEGG
from Bio.KEGG import REST
from Bio.KEGG.KGML import KGML_parser

# from rpy2.robjects.packages import importr
# from rpy2.robjects.vectors import FloatVector
# statsR= importr('stats')

searchFields=["UniProtKB Accession.ngram","Protein.ngram","Gene.ngram","Organism.ngram",\
				"Organism ID.ngram","SubCellular.ngram","Peptide Sequence.ngram",\
				"Mouse Kegg Pathway Name.ngram","Human Disease Name.ngram","Mouse Go ID.ngram",\
				"Mouse Go Name.ngram","Mouse Go Term.ngram","Human Drug Bank.ngram","Strain.ngram","Knockout.ngram","Panel.ngram","Sex.ngram","Biological Matrix.ngram"]

es = Elasticsearch(
	['http://xxxxx:9200/'],
	connection_class=RequestsHttpConnection
)
# Create your views here.


def basicSearch(request):
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)

	if request.method=='GET':
		searchterm=request.GET.get("searchterm")# user input for searching result
		searchterm= str(searchterm).strip()
		querybiomatrix=''
		if '_' in searchterm:
			tempsearchterm=searchterm.split('_')
			querybiomatrix=tempsearchterm[0]
			searchterm=str(tempsearchterm[1]).strip()
		response_data = {'filename_proteincentric': None,'downloadResultFilePath': None}
		countUnqprot=[]
		if searchterm.lower() !='none':
			#build elasticsearch query to search data
			query={
				"query":{
					"bool":{
						"should":[{
								"multi_match":{
									"query":searchterm,
									"type":"best_fields",
									"fields":searchFields,
									"minimum_should_match":"100%"
								}
						}]
					}
				}
			}
			#generate random file name to store search result in json format
			currdate=str(datetime.datetime.now())
			currdate=currdate.replace('-','_')
			currdate=currdate.replace(' ','_')
			currdate=currdate.replace(':','_')
			currdate=currdate.replace('.','_')
			nameFIle=str(uuid.uuid4())
			jsonfilename_proteincentric=nameFIle+'_search_proteincentric.json'
			jsonfilepath_proteincentric=os.path.join(settings.BASE_DIR, 'resultFile', 'jsonData','resultJson', 'search', 'results', jsonfilename_proteincentric)
			jsonfilepath_proteincentric_download=os.path.join(settings.BASE_DIR, 'resultFile', 'jsonData','resultJson', 'search', 'downloadversion', jsonfilename_proteincentric)
			jsonfileoutput_proteincentric= open(jsonfilepath_proteincentric,'w')
			jfinaldata=[]
			es.indices.refresh(index="xxxxxxxxx-index")
			#elasticsearch will search data
			res=helpers.scan(client=es,scroll='2m',index="xxxxxxxxx-index", doc_type="xxxxxxxx-type",query=query,request_timeout=30)
			jfinaldata=[]
			uniprotpepinfo={}
			#if data is valid based on uniprotkb release then it will display
			for i in res:
				jdic=i['_source']
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				panelFilter=True
				if 'panel' in searchterm.lower():
					if searchterm.lower() in (jdic['Panel'].lower()).split(';') and 'panel' in searchterm.lower():
						panelFilter=True
					else:
						panelFilter=False

				if jdic["UniprotKb entry status"] =="Yes" and panelFilter:
					countUnqprot.append(jdic["UniProtKB Accession"].split('-')[0].upper())
					if uniprotpepinfo.has_key(jdic["UniProtKB Accession"]):
						uniprotpepinfo[jdic["UniProtKB Accession"]].append(jdic["Peptide Sequence"])
					else:
						uniprotpepinfo[jdic["UniProtKB Accession"]]=[jdic["Peptide Sequence"]]
					#if jdic["Retention Time"].lower() =='na' or jdic["Gradients"].lower() =='na':
					if jdic["Retention Time"].lower() =='na':
						jdic["Summary Concentration Range Data"]='NA'
						jdic["Concentration View"]='NA'

					if jdic["Human UniProtKB Accession"].lower() !='na' and jdic["Present in human ortholog"].lower() =='no':
						jdic["Available assays in human ortholog"]='http://mrmassaydb.proteincentre.com/search/hyperlink/?UniProtKB Accession='+jdic["Human UniProtKB Accession"]
					else:
						jdic["Available assays in human ortholog"]='NA'

					if len(str(jdic["Summary Concentration Range Data"]).strip()) >0 and str(jdic["Summary Concentration Range Data"]).strip().upper() !="NA":
						try:
							jdic["Biological Matrix"]=jdic["Biological Matrix"].replace('|','<br/>')
						except KeyError:
							pass
						# try:
						# 	if '<br/>' in jdic["Concentration View"]:
						# 		tempmatrix=jdic["Concentration View"].split()[-1]
						# 		jdic["Concentration View"]=jdic["Concentration View"].replace('tissue',tempmatrix)
						# except KeyError:
						# 	pass
					jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/u','µg protein/µ')
					jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

					jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/u','µg protein/µ')
					jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

					jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/u','µg protein/µ')
					jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/mg','µg protein/mg')

					jdic["Concentration View"]=jdic["Concentration View"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["Concentration Range"]=jdic["Concentration Range"].replace('fmol target protein/u','fmol target protein/µ')

					jdic["LLOQ"]=jdic["LLOQ"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["ULOQ"]=jdic["ULOQ"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["Sample LLOQ"]=jdic["Sample LLOQ"].replace('fmol target protein/u','fmol target protein/µ')

					if jdic["Unique in protein"].upper() =='NA':
						jdic["Unique in protein"]=jdic["Unique in protein"].replace('NA','No')
					if jdic["Present in isoforms"].upper() =='NA':
						jdic["Present in isoforms"]=jdic["Present in isoforms"].replace('NA','No')

					
					jfinaldata.append(jdic)
			es.indices.refresh(index="xxxxxxxxx-index")
			#checking any result generated by database
			foundHits=len(jfinaldata)
			#storing only 10000 rows in json format
			matchingpepseqquery=[searchterm]
			finalupdatedUniInfo,biomatrixContainUniId,foldchangeData=pepbasedInfo(jfinaldata,uniprotpepinfo,matchingpepseqquery,proteinInfoColname,querybiomatrix)

			biomatrixContainUniId=list(set(biomatrixContainUniId))
			if len(querybiomatrix) >0:
				jfinaldata = [x for x in jfinaldata if x["UniProtKB Accession"] in biomatrixContainUniId]
				finalupdatedUniInfo["data"]=[k for k in finalupdatedUniInfo["data"] if k["UniProtKB Accession"] in biomatrixContainUniId]

			json.dump(finalupdatedUniInfo,jsonfileoutput_proteincentric)
			jsonfileoutput_proteincentric.close()
			# if result found then do other job
			if foundHits >0:
				statsummary=summaryStatcal(jfinaldata) # sent data to this funcation for generating stat
				
				keggchart=statsummary['keggchart']
				keggchart=[i[:2] for i in keggchart]
				specieslist=statsummary['specieslist']
				totallist=statsummary['total']
				subcell=statsummary['subcell']
				sortedgodic=statsummary['godic']
				querybioMatData=statsummary['BioMat']
				querystrainData=statsummary['Strain']
				querynoOfHumanortholog=statsummary['noOfHumanortholog']
				querynoOfDiseaseAssProt=statsummary['noOfDiseaseAssProt']
				humandisease=statsummary['disdic']
				pepseqdataseries=ast.literal_eval(json.dumps(statsummary['pepseqdataseries'])) #dumping data into json format
				prodataseries=statsummary['prodataseries']
				unqisostat=statsummary['unqisostat']
				urlname_proteincentric="search/results/"+jsonfilename_proteincentric
				foldchangeLength=len(foldchangeData)
				with open(jsonfilepath_proteincentric_download,'w') as downloadJsonFile:
					json.dump(jfinaldata,downloadJsonFile)
				response_data={
					"filename_proteincentric":urlname_proteincentric,'query': searchterm,'foundHits':foundHits,
					'keggchart':keggchart[:11],'specieslist':specieslist,
					'totallist':totallist,'subcell':subcell,'querybioMatData':querybioMatData,'querystrainData':querystrainData,'querynoOfHumanOrtholog':querynoOfHumanortholog,'querynoOfDiseaseAssProt':querynoOfDiseaseAssProt,
					'updatedgo':sortedgodic,'pepseqdataseries':pepseqdataseries,'humandisease':humandisease,
					'prodataseries':prodataseries,'unqisostat':unqisostat
					}
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def advancedSearch(request):
	"""
	This is advance search function, based on given search parameters it will generate result datatable along with stat
	from database.
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		advancesearchFields={
		 'protein':'Protein',
		 'gene':'Gene',
		 'uniProtKBAccession':'UniProtKB Accession', 
		 'pepSeq':'Peptide Sequence',
		 'panel':'Panel',
		 'strain':'Strain',
		 'mutant':'Knockout',
		 'sex':'Sex',
		 'biologicalMatrix': 'Biological Matrix',
		 'subCellLoc':'SubCellular',
		 'keggPathway':'Mouse Kegg Pathway Name',
		 'disCausMut':'Human Disease Name',
		 'goId':'Mouse Go ID',
		 'goTerm':'Mouse Go Name',
		 'goAspects':'Mouse Go Term',
		 'drugId':'Human Drug Bank',
		 'fastaFileName':'Own protein sequences in FASTA format'
		}
		multiOptions=['panel','strain','mutant','sex','biologicalMatrix']
		filtersearchStatus=0
		response_data={'filename_proteincentric': None,'downloadResultFilePath': None}
		searchterm=[]  # list of search term value associated with searchtype
		searchtype =[]  # list of search parameter
		searchtermlist=[]
		panelQuery=''
		advanceFormDetails=json.loads(request.GET.get('advancedFormData'))
		queryformData=advanceFormDetails["queryformData"]
		optionGroups=queryformData["optionGroups"]
		for opItem in optionGroups:
			searchterm.append(str(opItem["whereInput"]).strip())
			searchtype.append(str(opItem["selectInput"]).strip())
		userInputFastaFileName=''
		userInputFastaFileContext=''
		if "fastaFileName" in searchtype:
			userInputFastaFileName=str(searchterm[searchtype.index("fastaFileName")]).strip()
		nameFIle=str(uuid.uuid4()) # generate random file name to store user search result
		fastaseq=[]
		finalsearhdata=''
		if len(userInputFastaFileName)>0:
			try:
				finalsearhdata+='File'+':'+'Fasta Sequence'+' '
				#storing user provided fasta file
				fastafilepath=os.path.join(settings.BASE_DIR, 'resultFile', 'fastaFile', userInputFastaFileName+'.fasta')

				#reading fasta file
				for useq_record in SeqIO.parse(fastafilepath, 'fasta'):
					seqheader = useq_record.id
					sequniID = seqheader.split(' ')[0]
					sequniID=sequniID.replace('>','')
					tempseqs = str(useq_record.seq).strip()
					fastaseq.append(str(sequniID)+'_'+tempseqs.upper())
			except MultiValueDictKeyError:
				pass

			try:
				fastafileindex=searchtype.index("fastaFileName")
				#delete data based on index from list
				del searchtype[fastafileindex]
				del searchterm[fastafileindex]
			except ValueError:
				pass

		matchingpepseqquery=[]
		for i in range(0,len(searchtype)):
			subsearchtype=searchtype[i]
			subsearchterm=searchterm[i]
			if subsearchtype in multiOptions:
				subsearchterm=map(str,ast.literal_eval(subsearchterm))
				subsearchterm='|'.join(subsearchterm)
				searchterm[i]=subsearchterm
			#build elasticsearch query for all except organism to search data
			if '|' in subsearchterm:
				if 'Peptide Sequence' == subsearchtype:
					for p in (subsearchterm.strip()).split('|'):
						matchingpepseqquery.append(str(p).strip())
				subsearchterm=(subsearchterm.strip()).split('|')
			else:
				if 'Peptide Sequence' == subsearchtype:
					for p in (subsearchterm.strip()).split('\n'):
						matchingpepseqquery.append(str(p).strip())
				subsearchterm=(subsearchterm.strip()).split('\n')
			subsearchterm=map(str, subsearchterm)
			subsearchterm=map(lambda j: j.strip(), subsearchterm)
			subsearchterm=filter(None, subsearchterm)
			if  subsearchtype=='mutant':
				finalsearhdata+=''.join('Mutant')+':'+';'.join(subsearchterm)+' '
			elif subsearchtype=='goTerm':
				finalsearhdata+=''.join('Mouse GO Term')+':'+';'.join(subsearchterm)+' '
			elif subsearchtype=='goAspects':
				finalsearhdata+=''.join('Mouse GO Aspects')+':'+';'.join(subsearchterm)+' '
			else:
				finalsearhdata+=''.join(advancesearchFields[str(subsearchtype)])+':'+';'.join(subsearchterm)+' '
			
			if len(subsearchterm)>0:
				subsearchterm=[(item.strip()).lower() for item in subsearchterm] #converting into lower case
				shouldlist=[]
				for x in subsearchterm:
					tempquery={
								"multi_match":{
									"query":x.strip(),
									"type":"best_fields",
									"fields":[advancesearchFields[str(subsearchtype)]+".ngram"],
									"minimum_should_match":"100%"
								}
							}
					shouldlist.append(tempquery)
				booldic={}
				booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
				searchtermlist.append(booldic)
		unqfastaseq=list(set(fastaseq))

		if len(searchtermlist)>0 or len(unqfastaseq)>0:
			es.indices.refresh(index="xxxxxxxxx-index")

			query=""
			if len(searchtermlist)>0:
				query={
					"query": {
						"bool": {
							"must":searchtermlist
						}
					}
				}
			if len(searchtermlist)==0:
				query={
					"query": {
						"match_all": {}
					}
				}
			try:
				if searchtype.index('sex') >=0:
					filtersearchStatus=1
			except ValueError:
				pass
			try:
				if searchtype.index('strain') >=0:
					filtersearchStatus=1
			except ValueError:
				pass
			try:
				if searchtype.index('biologicalMatrix') >=0:
					filtersearchStatus=1
			except ValueError:
				pass
			try:
				if searchtype.index('panel') >=0:
					panelQuery=searchterm[searchtype.index('panel')].strip()
					filtersearchStatus=1
			except ValueError:
				pass
			try:
				if searchtype.index('mutant') >=0:
					filtersearchStatus=1
			except ValueError:
				pass
			#storing user search result into json format
			currdate=str(datetime.datetime.now())
			currdate=currdate.replace('-','_')
			currdate=currdate.replace(' ','_')
			currdate=currdate.replace(':','_')
			currdate=currdate.replace('.','_')
			jsonfilename_proteincentric=nameFIle+'_search_proteincentric.json'
			jsonfilepath_proteincentric=os.path.join(settings.BASE_DIR, 'resultFile', 'jsonData','resultJson', 'search', 'results', jsonfilename_proteincentric)
			jsonfilepath_proteincentric_download=os.path.join(settings.BASE_DIR, 'resultFile', 'jsonData','resultJson', 'search', 'downloadversion', jsonfilename_proteincentric)
			jsonfileoutput_proteincentric= open(jsonfilepath_proteincentric,'w')

			jfinaldata=[]
			res=helpers.scan(client=es,scroll='2m',index="xxxxxxxxx-index", doc_type="xxxxxxxx-type",query=query,request_timeout=30)
			jfinaldata=[]
			uniprotpepinfo={}
			usersequnq=[]
			for i in res:
				jdic=i['_source']
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				panelFilter=True
				if len(panelQuery) >0:
					for q in  panelQuery.lower().split('|'):
						if q in (jdic['Panel'].lower()).split(';'):
							panelFilter=True
							break
					else:
						panelFilter=False
				#if jdic["Retention Time"].lower() =='na' or jdic["Gradients"].lower() =='na':
				if panelFilter:
					if jdic["Retention Time"].lower() =='na':
						jdic["Summary Concentration Range Data"]='NA'
						jdic["Concentration View"]='NA'

					if jdic["Human UniProtKB Accession"].lower() !='na' and jdic["Present in human ortholog"].lower() =='no':
						jdic["Available assays in human ortholog"]='http://mrmassaydb.proteincentre.com/search/hyperlink/?UniProtKB Accession='+jdic["Human UniProtKB Accession"]
					else:
						jdic["Available assays in human ortholog"]='NA'

					jdic["PPI"] ="View"
					if len(str(jdic["Summary Concentration Range Data"]).strip()) >0 and str(jdic["Summary Concentration Range Data"]).strip().upper() !="NA":
						try:
							jdic["Biological Matrix"]=jdic["Biological Matrix"].replace('|','<br/>')
						except KeyError:
							pass

						# try:
						# 	if '<br/>' in jdic["Concentration View"]:
						# 		tempmatrix=jdic["Concentration View"].split()[-1]
						# 		jdic["Concentration View"]=jdic["Concentration View"].replace('tissue',tempmatrix)
						# except KeyError:
						# 	pass
					if filtersearchStatus==0:
						jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
						jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/u','µg protein/µ')
						jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

						jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
						jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/u','µg protein/µ')
						jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

						jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('fmol target protein/u','fmol target protein/µ')
						jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/u','µg protein/µ')
						jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/mg','µg protein/mg')

						jdic["Concentration View"]=jdic["Concentration View"].replace('fmol target protein/u','fmol target protein/µ')
						jdic["Concentration Range"]=jdic["Concentration Range"].replace('fmol target protein/u','fmol target protein/µ')

						jdic["LLOQ"]=jdic["LLOQ"].replace('fmol target protein/u','fmol target protein/µ')
						jdic["ULOQ"]=jdic["ULOQ"].replace('fmol target protein/u','fmol target protein/µ')
						jdic["Sample LLOQ"]=jdic["Sample LLOQ"].replace('fmol target protein/u','fmol target protein/µ')

						if jdic["Unique in protein"].upper() =='NA':
							jdic["Unique in protein"]=jdic["Unique in protein"].replace('NA','No')
						if jdic["Present in isoforms"].upper() =='NA':
							jdic["Present in isoforms"]=jdic["Present in isoforms"].replace('NA','No')
					seqhit=0
					# checking any peptide present in user provided fasta sequence
					# classified into 3 catagories
					if len(unqfastaseq)>0:
						pepseq=str(jdic['Peptide Sequence']).strip()
						indices = [i for i, s in enumerate(fastaseq) if pepseq.upper() in s]
						seqhit=len(indices)
						tempuserseqheadermatch='NA'
						tempmatchlist=[]
						if len(indices)>0:
							for i in indices:
								tempmatchlist.append('_'.join(fastaseq[i].split('_')[:-1]))
						if len(tempmatchlist)>0:
							tempuserseqheadermatch='<br/>'.join(tempmatchlist)
						jdic["Peptide in user's database"] =str(tempuserseqheadermatch)
						if len(indices)==0:
							jdic["Peptide unique in user's database"] ="Not present"
						elif len(indices) > 1:
							jdic["Peptide unique in user's database"] ="Present but not unique"
						else:
							jdic["Peptide unique in user's database"] ="Present and unique"
							usersequnq.append("Present and unique")

					if len(searchtermlist)==0:
						if seqhit >0:
							if uniprotpepinfo.has_key(jdic["UniProtKB Accession"]):
								uniprotpepinfo[jdic["UniProtKB Accession"]].append(jdic["Peptide Sequence"])
							else:
								uniprotpepinfo[jdic["UniProtKB Accession"]]=[jdic["Peptide Sequence"]]
							jfinaldata.append(jdic)
					else:
						if jdic["UniprotKb entry status"] =="Yes":
							if uniprotpepinfo.has_key(jdic["UniProtKB Accession"]):
								uniprotpepinfo[jdic["UniProtKB Accession"]].append(jdic["Peptide Sequence"])
							else:
								uniprotpepinfo[jdic["UniProtKB Accession"]]=[jdic["Peptide Sequence"]]
							jfinaldata.append(jdic)

			es.indices.refresh(index="xxxxxxxxx-index")
			#jfinaldata=jfinaldata[0]
			#storing only 10000 rows in json format
			if filtersearchStatus >0:
				jfinaldata,filteredUniProtIDs=filterSearch(jfinaldata,searchterm,searchtype)

			#checking any result generated by database
			foundHits=len(jfinaldata)

			# if result found then do other job
			if foundHits >0:
				querybiomatrix=''
				try:
					if len(filteredUniProtIDs) >0:
						for delKey in filteredUniProtIDs:
							del uniprotpepinfo[delKey]
				except UnboundLocalError:
					pass
				finalupdatedUniInfo,biomatrixContainUniId,foldchangeData=pepbasedInfo(jfinaldata,uniprotpepinfo,matchingpepseqquery,proteinInfoColname,querybiomatrix)

				json.dump(finalupdatedUniInfo,jsonfileoutput_proteincentric)
				jsonfileoutput_proteincentric.close()

				statsummary=summaryStatcal(jfinaldata) # sent data to this funcation for generating stat
				keggchart=statsummary['keggchart']
				keggchart=[i[:2] for i in keggchart]
				specieslist=statsummary['specieslist']
				totallist=statsummary['total']
				subcell=statsummary['subcell']
				sortedgodic=statsummary['godic']
				querybioMatData=statsummary['BioMat']
				querystrainData=statsummary['Strain']
				querynoOfHumanortholog=statsummary['noOfHumanortholog']
				querynoOfDiseaseAssProt=statsummary['noOfDiseaseAssProt']
				humandisease=statsummary['disdic']
				pepseqdataseries=ast.literal_eval(json.dumps(statsummary['pepseqdataseries'])) #dumping data into json format
				prodataseries=statsummary['prodataseries']
				unqisostat=statsummary['unqisostat']
				urlname_proteincentric="search/results/"+jsonfilename_proteincentric
				with open(jsonfilepath_proteincentric_download,'w') as downloadJsonFile:
					json.dump(jfinaldata,downloadJsonFile)
				unqfastaseqlen=0
				unqfastaseqlen=len(unqfastaseq)
				if len(unqfastaseq)>0:
					tempcalunq=str(round(((float(usersequnq.count('Present and unique'))/float(len(jfinaldata)))*100),2))+'%'
					unqisostat.append(["User data",tempcalunq,"NA"])
					#df.to_csv(downloadResultFilePath,index=False, encoding='utf-8', columns=downloadColName)

					response_data={
						"filename_proteincentric":urlname_proteincentric,
						'query': finalsearhdata,'foundHits':foundHits,
						'keggchart':keggchart[:11],'humandisease':humandisease,
						'totallist':totallist,'subcell':subcell,'querybioMatData':querybioMatData,'querystrainData':querystrainData,'querynoOfHumanOrtholog':querynoOfHumanortholog,'querynoOfDiseaseAssProt':querynoOfDiseaseAssProt,
						'updatedgo':sortedgodic,'unqfastaseqlen':unqfastaseqlen,
						'unqisostat':unqisostat,'fastafilename':userInputFastaFileName
						}
				elif len(unqfastaseq)==0:
					#df.to_csv(downloadResultFilePath,index=False, encoding='utf-8',columns=downloadColNameUserSeq)
					response_data={
						"filename_proteincentric":urlname_proteincentric,
						'query': finalsearhdata,'foundHits':foundHits,
						'keggchart':keggchart[:11],'humandisease':humandisease,
						'totallist':totallist,'subcell':subcell,'querybioMatData':querybioMatData,'querystrainData':querystrainData,'querynoOfHumanOrtholog':querynoOfHumanortholog,'querynoOfDiseaseAssProt':querynoOfDiseaseAssProt,
						'updatedgo':sortedgodic,'unqfastaseqlen':unqfastaseqlen,
						'unqisostat':unqisostat
						}
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def protVista(request):
	'''
	This function will display result for Mutation,PTM & Domain.
	'''
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		response_data = {'seqStart':None,'seqEnd':None}
		pepSeqMatchList=[]
		pepSeqMatchDic={}
		domainplotscript=[]
		valid=False
		humanValid=False
		contextpep={}
		humanContextPep={}
		proseq=''
		humanProSeq=''
		match_info=[]
		human_match_info=[]
		fasthead=''
		humanFastHead=''
		fastasq=''
		humanFastaSq=''
		fastalen=0
		humanFastaLen=0
		reachable=True
		humanReachable=True
		pepfilepath = os.path.join(settings.BASE_DIR, 'qmpkbmotherfile', 'ReportBook_mother_file.csv')
		presentunidpepseqstat=False
		listOfPeptide=[]
		listOfHumanPeptide=[]
		pepstart=0
		humanPepStart=0
		pepend=0
		humanPepEnd=0
		jsonprotvistastatus=False
		humanJsonProtvistaStatus=False
		protname=None
		humanUniprotKB='NA'
		es.indices.refresh(index="xxxxxxxxx-index")
		query={"query": {
			"bool": {
				"must": [
					{"match": {"UniProtKB Accession": uniprotkb}},
					{"match": {"UniprotKb entry status": "Yes"}}
				]
			}
		}
		}

		res=helpers.scan(client=es,scroll='2m',index="xxxxxxxxx-index", doc_type="xxxxxxxx-type",query=query,request_timeout=30)

		for hit in res:
			jdic=hit["_source"]
			jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
			if str(jdic["Present in human ortholog"]).strip() == 'Yes':
				humanUniprotKB=str(jdic["Human UniProtKB Accession"]).strip()
				listOfHumanPeptide.append(str(jdic["Peptide Sequence"]).strip())
			listOfPeptide.append(str(jdic["Peptide Sequence"]).strip())
		es.indices.refresh(index="xxxxxxxxx-index")
		foundHits=len(listOfPeptide)
		if '-' not in uniprotkb:
			code=(str(uniprotkb).strip()).upper()
			try:
				sleep(random.randint(5,10))
				requests.get("https://www.uniprot.org/", timeout=1)
				unidatafasta = urllib.urlopen("https://www.uniprot.org/uniprot/" + code + ".fasta")
				for mseq in SeqIO.parse(unidatafasta, "fasta"):
					fasthead=str((mseq.id).strip())
					proseq=str((mseq.seq).strip())
					fastasq=str((mseq.seq).strip())

				unidatafasta.close()
			except ConnectionError as e:
				reachable=False

			if reachable:
				jsonfilestatus=False
				jsonfilename='externalLabeledFeatures_'+uniprotkb+'.json'
				jsonfilepath=os.path.join(settings.BASE_DIR, 'resultFile','jsonData', 'protvistadataJson', 'mouse',jsonfilename)
				if os.path.exists(jsonfilepath):
					if datetime.datetime.fromtimestamp(os.path.getmtime(pepfilepath))< datetime.datetime.fromtimestamp(os.path.getmtime(jsonfilepath)):
						jsonfilestatus=True
						jsonprotvistastatus=True
					else:
						os.remove(jsonfilepath)
						jsonfilestatus=False
				else:
					jsonfilestatus=False
				jsonpepdata={}
				for pepseqitem in listOfPeptide:
					peptide_pattern = re.compile(pepseqitem,re.IGNORECASE)
					for match in re.finditer(peptide_pattern,proseq):
						jsonpepdata[pepseqitem.upper()] =[(int(match.start())+1),match.end()]
						pepstart=int(match.start())+1
						pepend=int(match.end())
						if pepseqitem in pepSeqMatchDic:
							pepSeqMatchDic[pepseqitem].append([pepstart,pepend,'Mouse'])
						else:
							pepSeqMatchDic[pepseqitem]=[[pepstart,pepend,'Mouse']]

						match_info.append([(int(match.start())+1),match.group(),match.end()])
				contextpep[uniprotkb]=[list(x) for x in set(tuple(x) for x in match_info)]
				fastalen=len(fastasq)

				if not jsonfilestatus:
					jsonfileoutput= open(jsonfilepath,'w')
					jsonformatdataprotvista={}
					jsonformatdataprotvista["sequence"]=str(proseq)
					tempfearures=[]
					for jsonkey in jsonpepdata.keys():
						tempdicjsondic={}
						tempdicjsondic["type"]="MRM"
						tempdicjsondic["category"]="Targeted_Proteomics_Assay_Mouse"
						tempdicjsondic["description"]="Suitable MRM Assay for Mouse"
						tempdicjsondic["begin"]=str(jsonpepdata[jsonkey][0])
						tempdicjsondic["end"]=str(jsonpepdata[jsonkey][1])
						tempdicjsondic["color"]="#00B88A"
						tempdicjsondic["accession"]=uniprotkb
						tempfearures.append(tempdicjsondic)
					jsonformatdataprotvista["features"]=tempfearures
					json.dump(jsonformatdataprotvista,jsonfileoutput)
					jsonfileoutput.close()
					jsonprotvistastatus=True

		if ('-' not in humanUniprotKB and humanUniprotKB !='NA'):
			try:
				sleep(random.randint(5,10))
				requests.get("https://www.uniprot.org/", timeout=1)
				humanUniDataFasta = urllib.urlopen("https://www.uniprot.org/uniprot/" + humanUniprotKB + ".fasta")
				for hseq in SeqIO.parse(humanUniDataFasta, "fasta"):
					humanFastHead=str((hseq.id).strip())
					humanProSeq=str((hseq.seq).strip())
					humanFastaSq=str((hseq.seq).strip())
				humanUniDataFasta.close()
			except ConnectionError as e:
				humanReachable=False

			if humanReachable:
				humanJsonFileStatus=False
				humanJsonFileName='externalLabeledFeatures_'+humanUniprotKB+'.json'
				humanJsonFilePath=os.path.join(settings.BASE_DIR, 'resultFile','jsonData', 'protvistadataJson','human', humanJsonFileName)
				if os.path.exists(humanJsonFilePath):
					if datetime.datetime.fromtimestamp(os.path.getmtime(pepfilepath))< datetime.datetime.fromtimestamp(os.path.getmtime(humanJsonFilePath)):
						humanJsonFileStatus=True
						humanJsonProtvistaStatus=True
					else:
						os.remove(jsonfilepath)
						humanJsonFileStatus=False
				else:
					humanJsonFileStatus=False
				humanJsonPepData={}
				for hPepSeqItem in listOfHumanPeptide:
					human_peptide_pattern = re.compile(hPepSeqItem,re.IGNORECASE)
					for hmatch in re.finditer(human_peptide_pattern,humanProSeq):
						humanJsonPepData[hPepSeqItem.upper()] =[(int(hmatch.start())+1),hmatch.end()]
						humanPepStart=int(hmatch.start())+1
						humanPepEnd=int(hmatch.end())
						if hPepSeqItem in pepSeqMatchDic:
							pepSeqMatchDic[hPepSeqItem].append([humanPepStart,humanPepEnd,'Human'])
						else:
							pepSeqMatchDic[hPepSeqItem]=[[humanPepStart,humanPepEnd,'Human']]
						human_match_info.append([(int(hmatch.start())+1),hmatch.group(),hmatch.end()])
				humanContextPep[humanUniprotKB]=[list(x) for x in set(tuple(x) for x in human_match_info)]
				humanFastaLen=len(humanFastaSq)
				if not humanJsonFileStatus:
					humanJsonFileOutput= open(humanJsonFilePath,'w')
					humanJsonFormatDataProtvista={}
					humanJsonFormatDataProtvista["sequence"]=str(humanProSeq)
					htempfearures=[]
					for jsonkey in humanJsonPepData.keys():
						htempdicjsondic={}
						htempdicjsondic["type"]="MRM"
						htempdicjsondic["category"]="Targeted_Proteomics_Assay_Human"
						htempdicjsondic["description"]="Suitable MRM Assay for Human"
						htempdicjsondic["begin"]=str(humanJsonPepData[jsonkey][0])
						htempdicjsondic["end"]=str(humanJsonPepData[jsonkey][1])
						htempdicjsondic["color"]="#00B88A"
						htempdicjsondic["accession"]=humanUniprotKB
						htempfearures.append(htempdicjsondic)
					humanJsonFormatDataProtvista["features"]=htempfearures
					json.dump(humanJsonFormatDataProtvista,humanJsonFileOutput)
					humanJsonFileOutput.close()
					humanJsonProtvistaStatus=True
		for pepMKey in pepSeqMatchDic:
			tempMatchList=[pepMKey,'NA','NA','NA','NA']
			for pepMItem in pepSeqMatchDic[pepMKey]:
				if pepMItem[-1]=='Mouse':
					tempMatchList[1]=pepMItem[0]
					tempMatchList[2]=pepMItem[1]
				else:
					tempMatchList[3]=pepMItem[0]
					tempMatchList[4]=pepMItem[1]
			pepSeqMatchList.append(tempMatchList)

		response_data={'contextpep':contextpep,'humanContextPep':humanContextPep,'fastalen':fastalen,'humanFastaLen':humanFastaLen,'uniprotkb':uniprotkb,'humanUniprotKB':humanUniprotKB,\
		'seqStart':pepstart,'humanPepStart':humanPepStart,'seqEnd':pepend,'humanPepEnd':humanPepEnd,'jsonprotvistastatus':jsonprotvistastatus,'humanJsonProtvistaStatus':humanJsonProtvistaStatus,\
		'pepSeqMatchList':pepSeqMatchList,'reachable':reachable}
		
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def assaydetails(request):
	"""
	This function is searching information for tranisition, based on intrument type
	in database.
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		resultFilePath= request.GET['resultFilePath']
		resultFilePath= str(request.GET.get("resultFilePath")).strip()
		fastafilename=request.GET.get("fastafilename")
		fastafilename= str(fastafilename).strip()
		es.indices.refresh(index="xxxxxxxxx-index")
		#build elasticsearch query based on peptide seq and uniprotkb acc
		query={"query": {
			"bool": {
				"must": [
					{"match": {"UniProtKB Accession": uniprotkb}},
					{"match": {"UniprotKb entry status": "Yes"}}
				]
			}
		}
		}
		res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)

		bioMatProtInfo={}
		transdic={}
		temptransdic={}
		gradientlist=[]
		gradinfoheader=[]
		loquantinfo=[]
		foundHits=res["hits"]["total"]
		userFastaStatus=0
		if fastafilename !='NA':
			userFastaStatus=1
		protinfo={}

		with open(resultFilePath) as rjf:
			for resitem in json.load(rjf)['data']:
				if resitem["UniProtKB Accession"]==uniprotkb:
					pepinfo =resitem["Peptide Based Info"]
					for pepItem in pepinfo:
						tempPepSeq=pepItem["Peptide Sequence"].strip()
						panData="NA"
						pepiso="NA"
						huPepiso="NA"
						pepUnq=pepItem["Unique in protein"].strip()
						pepHumanortholog=pepItem["Present in human ortholog"].strip()
						unqInHumanortholog=pepItem["Unique in human protein"].strip()

						if len(pepItem["Concentration View"].strip()) > 0 and pepItem["Concentration View"].strip().upper() !="NA":
							conqueryArray=pepItem["concenQuery"].strip().split('@')
							bioMatProtInfo[tempPepSeq]=conqueryArray[2]

						if len(pepItem["Present in isoforms"].strip()) > 0 and  pepItem["Present in isoforms"].strip().upper() != "NA" and pepItem["Present in isoforms"].strip().upper() != "NO":
							tempLst =pepItem["Present in isoforms"].strip().split(',')
							for idx, val in enumerate(tempLst):
								tempLst[idx] = '<a target="_blank"  routerLinkActive="active" href="https://www.uniprot.org/uniprot/' + val+'.fasta">'+val+ '</a>'
							pepiso="<br>".join(tempLst)

						if len(pepItem["Present in human isoforms"].strip()) > 0 and  pepItem["Present in human isoforms"].strip() != "NA" and pepItem["Present in human isoforms"].strip().upper() != "NO":
							tempLst =pepItem["Present in human isoforms"].strip().split(',')
							for idx, val in enumerate(tempLst):
								tempLst[idx] = '<a target="_blank"  routerLinkActive="active" href="https://www.uniprot.org/uniprot/' + val+'.fasta">'+val+ '</a>'
							huPepiso="<br>".join(tempLst)

						if len(pepItem["Panel"].strip()) > 0 and pepItem["Panel"].strip().upper() != "NA" :
							panview=pepItem["Panel"].strip().split(';')
							panData="<br>".join(panview)
						if userFastaStatus==0:
							protinfo[tempPepSeq]=[pepUnq,pepiso,pepHumanortholog,unqInHumanortholog,huPepiso,panData]
						if userFastaStatus==1:
							pepuserfo=None
							pepInUserDB=pepItem["Peptide in user's database"]
							if  pepItem["Peptide unique in user's database"].strip() == "Not present":
								pepuserfo= pepItem["Peptide unique in user's database"].strip()
							else:
								pepuserfo= '<a target="_blank"  routerLinkActive="active" routerLinkActive="active" href="/dataload/userpepseq_'  + pepItem["UniProtKB Accession"].strip() +'_'+pepItem["Peptide Sequence"].strip() +'_'+fastafilename + '">' + pepItem["Peptide unique in user's database"].strip() + '</a>'

							protinfo[tempPepSeq]=[pepUnq,pepiso,pepHumanortholog,unqInHumanortholog,huPepiso,pepuserfo,pepInUserDB,panData]
					break

		
		for hit in res['hits']['hits']:
			jdic=hit["_source"]
			jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
			jdic["Concentration Range"]=jdic["Concentration Range"].replace('fmol target protein/u','fmol target protein/µ')
			if str(jdic["UniProtKB Accession"]).strip() == uniprotkb and str(jdic["Peptide Sequence"]).strip() in protinfo:
				meanRetentime=0.0
				fragIon=[]
				temploquantinfo={}
				jdic["LLOQ"]=str(jdic["LLOQ"]).strip().replace('fmol target protein/u','fmol target protein/µ')
				jdic["ULOQ"]=str(jdic["ULOQ"]).strip().replace('fmol target protein/u','fmol target protein/µ')
				jdic["Sample LLOQ"]=str(jdic["Sample LLOQ"]).strip().replace('fmol target protein/u','fmol target protein/µ')
				templistOfMatrix=bioMatProtInfo[str(jdic["Peptide Sequence"]).strip()]
				for i in listOfMatrix:
					if i.lower() in templistOfMatrix.lower():
						tmepKey=i+str(jdic["Peptide Sequence"]).strip()
						for l in jdic["LLOQ"].split(';'):
							if i.lower() in l.lower():
								if i in temploquantinfo:
									temploquantinfo[i].append(l.split('|')[1].split('(')[0].strip())
								else:
									temploquantinfo[i]=[l.split('|')[1].split('(')[0].strip()]
						for u in jdic["ULOQ"].split(';'):
							if i.lower() in u.lower():
								if i in temploquantinfo:
									temploquantinfo[i].append(u.split('|')[1].split('(')[0].strip())
								else:
									temploquantinfo[i]=[u.split('|')[1].split('(')[0].strip()]
						for s in jdic["Sample LLOQ"].split(';'):
							if i.lower() in s.lower():
								if i in temploquantinfo:
									temploquantinfo[i].append(s.split('|')[1].split('(')[0].strip())
								else:
									temploquantinfo[i]=[s.split('|')[1].split('(')[0].strip()]
				for bk in temploquantinfo:
					tempList=[str(jdic["Peptide Sequence"]).strip(),bk]+temploquantinfo[bk]
					loquantinfo.append(tempList)

				if (str(jdic["Transitions"]).strip()) >0 and (str(jdic["Transitions"]).strip()).lower() !='na':
					transdata=str(jdic["Transitions"]).strip()
					transinfo=transdata.split(';')
					for titem in transinfo[1:]:
						subtransinfo=titem.split('|')
						if 'instrument' not in titem.lower():
							subtransinfo=[str(x) for x in subtransinfo]
							subtransinfo=[str(jdic["Peptide Sequence"]).strip()]+subtransinfo
							fragIon.append(subtransinfo[5])
							if temptransdic.has_key(subtransinfo[1].strip()):
								temptransdic[subtransinfo[1].strip()].append(subtransinfo)
							else:
								temptransdic[subtransinfo[1].strip()]=[subtransinfo]

				if (str(jdic["Gradients"]).strip()) >0 and (str(jdic["Gradients"]).strip()).lower() !='na':
					graddata=str(jdic["Gradients"]).strip()
					#graddata='Time[min]|A[%]|B[%];0.00|98.00|2.00;2.00|93.00|7.00;50.00|70.00|30.00;53.00|55.00|45.00;53.00|20.00|80.00;55.00|20.00|80.00;56.00|98.00|2.00'
					gradinfo=graddata.split(';')
					retentioninfo=str(jdic["Retention Time"]).strip().split(';')
					for i,j in enumerate(retentioninfo):
						try:
							float(j)
						except ValueError:
							del retentioninfo[i]
					analytdata=str(jdic["Analytical inofrmation"]).strip()
					#analytdata='Agilent Zorbax Eclipse Plus C18 RRHD 2.1 x 150mm 1.8um'
					gradinfoheader=[x for x in (gradinfo[0].strip()).split('|')]
					templist=[x.split('|') for x in gradinfo[1:]]
					tempRetentionTime=[]
					for ritem in range(0,len(retentioninfo)):
						if ritem != 0:
							if (float(ritem)%5.0)==0.0:
								tempRetentionTime.append(' '+retentioninfo[ritem])
							else:
								tempRetentionTime.append(retentioninfo[ritem])
						else:
							tempRetentionTime.append(retentioninfo[ritem])
					gradientlist.append([str(jdic["Peptide Sequence"]).strip(),','.join(tempRetentionTime),analytdata,'Gradient 1',templist])
					# for ritem in range(0,len(retentioninfo)):
					# 	gradientlist.append([retentioninfo[ritem],analytdata,'Gradient '+str(ritem+1),templist])
					retentioninfo=map(float,retentioninfo)
					meanRetentime=round(np.mean(retentioninfo),2)
					protinfo[str(jdic["Peptide Sequence"]).strip()]=[str(jdic["Molecular Weight"]).strip(),str(jdic["GRAVY Score"]).strip()]+protinfo[str(jdic["Peptide Sequence"]).strip()]+['<br>'.join(list(set(fragIon))),meanRetentime]
		
		if len(temptransdic)>0:
			transdic["Transitions"]=temptransdic
		es.indices.refresh(index="xxxxxxxxx-index")
		response_data ={'transdic':transdic,'foundHits':foundHits,'protinfo':protinfo,\
		'gradientlist': gradientlist, 'gradinfoheader':gradinfoheader,'loquantinfo':loquantinfo,\
		'userFastaStatus':userFastaStatus,'fastafilename':fastafilename
		}
		
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def concentration(request):
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		tempQuery=str(request.GET.get("query")).strip()
		tempQuery=tempQuery.replace('!','/')
		queryInfo=tempQuery.split('@')
		uniprotkb=queryInfo[-1]
		pepseq= queryInfo[-2]
		filterSearchTerm=[str(queryInfo[0]),str(queryInfo[1]),str(queryInfo[2]),str(queryInfo[3])]
		filterSearchType=[str('sex'),str('strain'),str('biologicalMatrix'),str('knockout')]
		concUnit=[]
		summaryConcData=[]
		es.indices.refresh(index="xxxxxxxxx-index")
		query={"query": {
			"bool": {
				"must": [
					{"match": {"UniProtKB Accession": uniprotkb}},
					{"match": {"Peptide Sequence": pepseq}},
					{"match": {"UniprotKb entry status": "Yes"}}
				]
			}
		}
		}
		res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)
		sumconclist=[]
		foundHits=res["hits"]["total"]
		protList=[]
		jfinaldata=[]
		sampleLLOQ=''
		ULOQ=''
		for hit in res['hits']['hits']:
			jdic=hit["_source"]
			jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
			if (str(jdic["Summary Concentration Range Data"]).strip()) >0 and (str(jdic["Summary Concentration Range Data"]).strip()).lower() !='na':
				sampleLLOQ=str(jdic["Sample LLOQ"]).strip()
				ULOQ=str(jdic["ULOQ"]).strip()
				jfinaldata.append(jdic)

		es.indices.refresh(index="xxxxxxxxx-index")
		jfinaldata=filterConcentration(jfinaldata,filterSearchTerm,filterSearchType)
		sampleLLOQ=sampleLLOQ.replace(' (fmol target protein/ug extracted protein)','')
		sampleLLOQ=dict([samval.split('|') for samval in sampleLLOQ.split(';')])
		ULOQ=ULOQ.replace(' (fmol target protein/ug extracted protein)','')
		ULOQ=dict([uval.split('|') for uval in ULOQ.split(';')])
		sumconcdata=str(jfinaldata[0]["Summary Concentration Range Data"]).strip()
		allconcdata=str(jfinaldata[0]["All Concentration Range Data"]).strip()
		allconcdataSampleLLOQ=str(jfinaldata[0]["All Concentration Range Data-Sample LLOQ Based"]).strip()
		sumconcdata=sumconcdata.replace('fmol target protein/u','fmol target protein/µ')
		sumconcdata=sumconcdata.replace('ug extracted protein/uL','µg extracted protein/µL')
		sumconcdata=sumconcdata.replace('ug extracted protein/mg','µg extracted protein/mg')

		allconcdata=allconcdata.replace('fmol target protein/u','fmol target protein/µ')
		allconcdata=allconcdata.replace('ug extracted protein/u','µg protein/µ')
		allconcdata=allconcdata.replace('ug extracted protein/mg','µg extracted protein/mg')

		allconcdataSampleLLOQ=allconcdataSampleLLOQ.replace('fmol target protein/u','fmol target protein/µ')
		allconcdataSampleLLOQ=allconcdataSampleLLOQ.replace('ug extracted protein/u','µg extracted protein/µ')

		sumconcinfo=sumconcdata.split(';')
		allconinfo=allconcdata.split(';')

		allconinfoSampleLLOQ=allconcdataSampleLLOQ.split(';')
		for scitem in sumconcinfo:
			scinfo =scitem.split('|')
			tempSampleLLOQ=sampleLLOQ[scinfo[2]]
			tempULOQ=ULOQ[scinfo[2]]
			stempid='|'.join(map(str,scinfo[2:5]))
			tempMatchConcList=[]
			for acitem in allconinfo:
				acinfo =acitem.split('|')
				del acinfo[3]
				atempid='|'.join(map(str,acinfo[2:5]))
				if stempid.lower() ==atempid.lower():
					concUnit.append('(' + acinfo[-2].strip().split(' (')[-1].strip())
					if float(acinfo[-3].strip().split(' ')[0].strip()) >0:
						tempMatchConcList.append(acinfo[-3].strip().split(' ')[0].strip())
			tempMatchConcData='|'.join(map(str,tempMatchConcList))

			tempMatchConcDataSampleLLOQ='NA'
			templen=1
			try:
				templen=len(filter(None,map(str,list(set(allconinfoSampleLLOQ)))))
			except UnicodeEncodeError:
				pass
			if 'NA' != ''.join(list(set(allconinfoSampleLLOQ))) and templen>0:
				tempMatchConcListSampleLLOQ=[]
				for slacitem in allconinfoSampleLLOQ:
					if slacitem.upper().strip() !='NA':
						slacinfo =slacitem.split('|')
						del slacinfo[3]
						slatempid='|'.join(map(str,slacinfo[2:5]))

						if stempid.lower() ==slatempid.lower():
							tempMatchConcListSampleLLOQ.append(slacinfo[-3].strip().split(' ')[0].strip())
				tempMatchConcDataSampleLLOQ='|'.join(map(str,tempMatchConcListSampleLLOQ))

			scinfo.append(str(jfinaldata[0]["UniProtKB Accession"]).strip())
			scinfo.append(str(jfinaldata[0]["Protein"]).strip())
			scinfo.append(str(jfinaldata[0]["Peptide Sequence"]).strip())
			scinfo.append(stempid)
			scinfo.append(tempMatchConcData)
			scinfo.append(tempMatchConcDataSampleLLOQ)
			scinfo.append(tempSampleLLOQ)
			scinfo.append(tempULOQ)
			scinfo=[scI.split('(')[0].strip()  if '(' in scI else scI for scI in scinfo]			
			sumconclist.append(scinfo)
		summaryConcData.insert(0,str(jfinaldata[0]["Peptide Sequence"]).strip())
		summaryConcData.insert(0,str(jfinaldata[0]["Protein"]).strip())
		summaryConcData.insert(0,str(jfinaldata[0]["UniProtKB Accession"]).strip())
		protList=summaryConcData
		concUnit=list(set(concUnit))
		lenOfConcData=len(sumconclist)
		concUnit='&'.join(concUnit)
		sumconclist=sorted(sumconclist,key=lambda l:l[4])
		sumconclist=sorted(sumconclist,key=lambda l:l[3])
		sumconclist=sorted(sumconclist,key=lambda l:l[2])
		response_data ={'conclist':sumconclist,'foundHits':foundHits,'protList':protList,'concUnit':concUnit,'lenOfConcData':lenOfConcData}

		return HttpResponse(json.dumps(response_data), content_type="application/json")


def pathway(request):
	'''
	This function will display result for KEGG pathways and STRING PPI.
	'''
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		if len(uniprotkb)>0:
			pathwayDic={}
			pathWayList=[]
			es.indices.refresh(index="xxxxxxxxx-index")
			query={"query": {
				"bool": {
					"must": [
						{"match": {"UniProtKB Accession": uniprotkb}},
						{"match": {"UniprotKb entry status": "Yes"}}
					]
				}
			}
			}
			res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)
			foundHits=res["hits"]["total"]
			for hit in res['hits']['hits']:
				jdic=hit["_source"]
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				mousePathway=str(jdic["Mouse Kegg Pathway"]).strip()
				humanPathway=str(jdic["Human Kegg Pathway"]).strip()
				if str(mousePathway).strip().lower() != 'na' and len(str(mousePathway).strip()) >0:
					mousePathwayInfo=mousePathway.split('|')
					for i in mousePathwayInfo:
						submousePathwayInfo=i.split(';')
						if submousePathwayInfo[1] in pathwayDic:
							pathwayDic[submousePathwayInfo[1]].append(submousePathwayInfo[0])
						else:
							pathwayDic[submousePathwayInfo[1]]=[submousePathwayInfo[0]]
				if str(humanPathway).strip().lower() != 'na' and len(str(humanPathway).strip()) >0:
					humanPathwayInfo=humanPathway.split('|')
					for i in humanPathwayInfo:
						subhumanPathwayInfo=i.split(';')
						if subhumanPathwayInfo[1] in pathwayDic:
							pathwayDic[subhumanPathwayInfo[1]].append(subhumanPathwayInfo[0])
						else:
							pathwayDic[subhumanPathwayInfo[1]]=[subhumanPathwayInfo[0]]
			es.indices.refresh(index="xxxxxxxxx-index")
			if foundHits >0 :
				if len(pathwayDic)>0:
					for pathKey in pathwayDic:
						tempList=['NA']*4
						tempList[0]=pathKey
						tempPathList=[]
						for j in pathwayDic[pathKey]:
							if 'hsa' in j:
								tempList[2]=j
								tempURL='<a target="_blank" href="https://www.kegg.jp/kegg-bin/show_pathway?'+j+'">'+j+'&nbsp;<i class="fa fa-external-link" aria-hidden="true"></i></a>'
								tempPathList.append(tempURL)
							if 'mmu' in j:
								tempList[1]=j
								tempURL='<a target="_blank" href="https://www.kegg.jp/kegg-bin/show_pathway?'+j+'">'+j+'&nbsp;<i class="fa fa-external-link" aria-hidden="true"></i></a>'
								tempPathList.append(tempURL)
						tempList[3]='<br>'.join(list(set(tempPathList)))
						pathWayList.append(tempList)
		response_data ={'pathWayList':pathWayList}

		return HttpResponse(json.dumps(response_data), content_type="application/json")

def pathwayview(request):
	'''
	This function will display result for KEGG pathways.
	'''
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("Uniprotkb")).strip()
		uniprotid=''
		uniprotname=''
		unikeggid=''
		nodesscript=[]
		edgesscript=[]
		keggurl=''
		reachable=True
		presentunidstat=False
		OSid=str(request.GET.get("organismid")).strip()
		pathwayid=str(request.GET.get("pathwayid")).strip()
		pathwayname=str(request.GET.get("pathwayname")).strip()
		homeURL=str((request.build_absolute_uri()).split('pathwayview')[0]).strip()
		uniProtGeneDic={}
		if len(uniprotkb)>0:
			pepfilegenidlistOther=[]

			es.indices.refresh(index="xxxxxxxxx-index")
			query={"query": {
				"bool": {
					"must": [
						{"match": {"UniProtKB Accession": uniprotkb}},
						{"match": {"Organism ID": OSid}},
						{"match": {"UniprotKb entry status": "Yes"}}
					]
				}
			}
			}
			res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)

			foundHits=res["hits"]["total"]
			es.indices.refresh(index="xxxxxxxxx-index")
			if foundHits >0 :
				presentunidstat=True
			if presentunidstat:
				viewquery={"query": {
					"bool": {
						"must": [
							{"match": {"Mouse Kegg Pathway Name": pathwayname}},
							{"match": {"Organism ID": OSid}},
							{"match": {"UniprotKb entry status": "Yes"}}
						]
					}
				}
				}
				resOrg = helpers.scan(client=es,scroll='2m',index="xxxxxxxxx-index", doc_type="xxxxxxxx-type",query=viewquery)
				
				jfinaldata=[]
				for i in resOrg:
					jdic=i['_source']
					jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
					pepfilegenidlistOther.append(jdic['Gene'])
					uniProtGeneDic[str(jdic['Gene']).strip().lower()]=str(jdic['UniProtKB Accession']).strip()
					jfinaldata.append(jdic)
				es.indices.refresh(index="xxxxxxxxx-index")
				pepfilegenidlistOther=list(set(pepfilegenidlistOther))

				pepfilegenidlistOther=[x.lower() for x in pepfilegenidlistOther]
				code=None
				if '-' in uniprotkb:
					code=(str(uniprotkb).split('-'))[0]
				else:
					code=str(uniprotkb.strip())

				try:
					sleep(random.randint(5,10))
					requests.get("https://www.uniprot.org/", timeout=5)
					unitxtdata = urllib.urlopen("https://www.uniprot.org/uniprot/" + code + ".txt")
					for uline in unitxtdata:
						udata=uline.strip()

						if udata.startswith('ID') and '_' in udata:
							idinfo = udata.split()
							uniprotid=idinfo[1].strip()

						if udata.startswith('GN   Name='):
							uniprotname= (((udata.split()[1]).split('='))[-1]).strip()
							if ';' in uniprotname:
								uniprotname= uniprotname.replace(';','')

						if udata.startswith('DR   KEGG'):
							unikeggid =(udata.split(';'))[1].strip()
					unitxtdata.close()

				except ConnectionError as e:
					reachable=False

		keggimagedict={}
		if len(unikeggid) >0 and reachable:
			k = KEGG()
			kegg=k.get(unikeggid)
			dict_data = k.parse(kegg)
			try:
				keggpathwayid= (dict_data['PATHWAY'].keys())
				for kegpathidietm in keggpathwayid:
					keggentryid = (unikeggid.split(':'))[1].strip()
					subkeggmapid=str(kegpathidietm)+'+'+str(keggentryid)
					if len(subkeggmapid) >0 and str(kegpathidietm).lower() == pathwayid.lower():
						keggpresentgeneIdlist=[]=[]
						notpresentkegggeneid=[]
						updatedcorddatalist=[]
						keggimagepath=''
						pathway = KGML_parser.read(REST.kegg_get(kegpathidietm, "kgml"))
						pathwayName=(str(pathway)).split('\n')[0].split(':')[1].strip()
						listUnqGene=[]
						keggOrgInitial=''
						getGeneList=[]
						pathwayGeneCoord={}
						for g in pathway.genes:
							tempGInfo=(g.name).split( )
							for tg in tempGInfo:
								geneID=tg.split(':')[1].strip()
								keggOrgInitial=tg.split(':')[0].strip()
								getGeneList.append(tg.strip())
								listUnqGene.append(geneID)
							for kgraphic in g.graphics:
								if kgraphic.type=='rectangle':
									kcoord=str(kgraphic.x)+','+str(kgraphic.y)+','+str(kgraphic.width)+','+str(kgraphic.height)
									tempGId=[x.split(':')[1].strip() for x in g.name.split(' ')]
									pathwayGeneCoord[kcoord]=tempGId
						listUnqGene=list(set(listUnqGene))
						getGeneList=list(set(getGeneList))
						geneKeggIdDics={}
						for gI in range(0,len(getGeneList),100):
							keggRESTURL='http://rest.kegg.jp/list/'+'+'.join(getGeneList[gI:gI+100])
							keggResponseREST = requests.get(keggRESTURL,verify=False)
							if not keggResponseREST.ok:
								keggResponseREST.raise_for_status()
								sys.exit()
							keggResponseBodyREST = keggResponseREST.text
							for gN in keggResponseBodyREST.split('\n')[:-1]:
								gnInfo=gN.split('\t')
								tempGeneList=[i.strip().lower() for i in gnInfo[1].split(';')[0].split(',')]
								tempKeggGeneID=gnInfo[0].split(':')[1]
								geneKeggIdDics[tempKeggGeneID]=[i.strip() for i in gnInfo[1].split(';')[0].split(',')]
								if gnInfo[0] != unikeggid:
									for tg in tempGeneList:
										if tg in pepfilegenidlistOther:
											keggpresentgeneIdlist.append(tempKeggGeneID)
						keggpresentgeneIdlist=list(set(keggpresentgeneIdlist))
						notpresentkegggeneid=set(geneKeggIdDics.keys())-set(keggpresentgeneIdlist+[unikeggid.split(':')[1]])
						notpresentkegggeneid=list(notpresentkegggeneid)
												
						presentKeggGeneIDList=set(keggpresentgeneIdlist+[unikeggid.split(':')[1]])
						presentKeggGeneIDList=list(presentKeggGeneIDList)
						presentGeneList=list(set(pepfilegenidlistOther+[uniprotname.lower()]))

						keggurl = "https://www.kegg.jp/kegg-bin/show_pathway?" + str(kegpathidietm)
						keggurl += "/%s%%20%s/" % (unikeggid.split(':')[1],'violet')
						if len(keggpresentgeneIdlist)>0:
							for pgc in keggpresentgeneIdlist:
								keggurl += "/%s%%20%s/" % (pgc,'maroon')
						if len(notpresentkegggeneid)>0:
							for ngc in notpresentkegggeneid:
								keggurl += "/%s%%20%s/" % (ngc,'#ffffff')

						try:
							sleep(random.randint(5,10))
							requests.get("https://www.kegg.jp/", timeout=1)
							kegghttp=urllib3.PoolManager()
							urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
							keggurlreq = kegghttp.request('GET',keggurl)
							keggurldata =keggurlreq.data
							keggurldata=keggurldata.decode('utf-8')
							keggurldata=keggurldata.replace('\t','')
							for kline in keggurldata.split('\n'):
								kline=kline.lstrip()
								try:
									if '<area' in kline.lower() and 'href='.lower() in kline.lower() and 'title=' in kline.lower() and 'shape=' in kline.lower():
										kline=kline.replace('"','')
										kshape=kline.split('shape=')[1].split(' ')[0]
										kcoords=kline.split('coords=')[1].split(' ')[0]
										khref=''
										ktitle=kline.split('title=')[1].replace('/>','').replace('class=module','')
										ktitleData=ktitle.lstrip()
										if kshape=='rect':
											ktitleInfo=ktitleData.split(',')
											ktitleInfoID=[k.strip().split(' ')[0] for k in ktitleInfo]
											commonKeggGeneIDList=list(set(ktitleInfoID)&set(presentKeggGeneIDList))
											if len(commonKeggGeneIDList)>0:
												tempTitle=[]
												commonKeggGeneList=[]
												for ki in ktitleInfoID:
													if ki in geneKeggIdDics:
														keggGeneList=geneKeggIdDics[ki]
														tempcommonKeggGeneList=[str(cg) for cg in keggGeneList if cg.lower() in presentGeneList]
														tempTitle.extend([ki+' ('+str(x)+')' for x in tempcommonKeggGeneList])
														commonKeggGeneList.extend(tempcommonKeggGeneList)
													
												ktitleData=','.join(tempTitle)
												khref='/results/?gene='+str('|'.join(commonKeggGeneList))+'&Organismid='+OSid
												updatedcorddatalist.append([kshape,kcoords,str(khref),ktitleData])
									if kline.startswith('<img src="/tmp/mark_pathway'):
										kinfo=kline.split('name=')
										keggimagepath=(kinfo[0].split('"'))[1].strip()
								except UnicodeDecodeError:
									pass
						except ConnectionError as e:
							reachable=False
						except urllib3.exceptions.MaxRetryError:
							reachable=False
						keggimagedict[subkeggmapid]=[keggimagepath,pathwayName,updatedcorddatalist]

			except KeyError:
				pass
		response_data ={
					'uniprotid':uniprotid,'uniprotname':uniprotname,
					'keggimagedict':keggimagedict,'keggurl':keggurl,
					'reachable':reachable
				}

		return HttpResponse(json.dumps(response_data), content_type="application/json")

def goterm(request):
	'''
	This function will display result for Go term.
	'''
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		contextgoterm =[]
		reachable=True
		jvenndataseries=[]
		response_data = {}
		if len(uniprotkb)>0:
			uniprotkblist=[]
			code=None
			gene=None
			protname=None
			goDic={}
			mouseUniData=[]
			humanUniData=[]
			goStatBioP=[]
			goStatMolF=[]
			goStatCellC=[]
			es.indices.refresh(index="xxxxxxxxx-index")
			#build elasticsearch query based provided uniprotkb acc
			query={"query": {
				"bool": {
					"must": [
						{"match": {"UniProtKB Accession": uniprotkb}},
						{"match": {"UniprotKb entry status": "Yes"}}
					]
				}
			}
			}
			res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)

			foundHits=res["hits"]["total"]
			for hit in res['hits']['hits']:
				jdic=hit["_source"]
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				mouseGo=str(jdic["Mouse Go"]).strip()
				humanGo=str(jdic["Human Go"]).strip()
				if str(mouseGo).strip().lower() != 'na' and len(str(mouseGo).strip()) >0:
					mouseGoInfo=mouseGo.split('|')
					for i in mouseGoInfo:
						submouseGoInfo=i.split(';')
						if submouseGoInfo[1] in goDic:
							goDic[submouseGoInfo[1]].append([submouseGoInfo[0],submouseGoInfo[2],'Mouse'])
						else:
							goDic[submouseGoInfo[1]]=[[submouseGoInfo[0],submouseGoInfo[2],'Mouse']]
				if str(humanGo).strip().lower() != 'na' and len(str(humanGo).strip()) >0:
					humanGoInfo=mouseGo.split('|')
					for i in humanGoInfo:
						subhumanGoInfo=i.split(';')
						if subhumanGoInfo[1] in goDic:
							goDic[subhumanGoInfo[1]].append([subhumanGoInfo[0],subhumanGoInfo[2],'Human'])
						else:
							goDic[subhumanGoInfo[1]]=[[subhumanGoInfo[0],subhumanGoInfo[2],'Human']]
			es.indices.refresh(index="xxxxxxxxx-index")

			if foundHits >0:
				if len(goDic)>0:
					for goKey in goDic:
						tempList=['NA']*4
						tempList[0]=goKey
						tempList[1]=goDic[goKey][0][0]
						tempList[2]=goDic[goKey][0][1]
						orgList=[]
						for j in goDic[goKey]:
							orgList.append(j[2])
						tempList[3]='<br>'.join(list(set(orgList)))
						if tempList[2].lower()=='biological process':
							goStatBioP.append(tempList[0])
						if tempList[2].lower()=='molecular function':
							goStatMolF.append(tempList[0])
						if tempList[2].lower()=='cellular component':
							goStatCellC.append(tempList[0])
						contextgoterm.append(tempList)
		goStat=[]
		if len(goStatBioP)>0:
			goStat.append('Number of Biological Process GO Aspects:'+str(len(set(goStatBioP))))
		if len(goStatMolF)>0:
			goStat.append('Number of Molecular Function GO Aspects:'+str(len(set(goStatMolF))))
		if len(goStatCellC)>0:
			goStat.append('Number of Cellular Component GO Aspects:'+str(len(set(goStatCellC))))

		response_data ={'foundHits': foundHits,'contextgoterminfo': contextgoterm,'goStat':'<br>'.join(goStat)}

		return HttpResponse(json.dumps(response_data), content_type="application/json")

def geneExp(request):
	'''
	This function will display result for Gene Expression.
	'''
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		gene=None
		protname=None
		geneExpData=None
		geneExplist=[]
		if len(uniprotkb)>0:
			es.indices.refresh(index="xxxxxxxxx-index")
			#build elasticsearch query based provided uniprotkb acc
			query={"query": {
				"bool": {
					"must": [
						{"match": {"UniProtKB Accession": uniprotkb}},
						{"match": {"UniprotKb entry status": "Yes"}}
					]
				}
			}
			}
			res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)

			foundHits=res["hits"]["total"]
			for hit in res['hits']['hits']:
				jdic=hit["_source"]
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				gene=str(jdic["Gene"]).strip()
				protname=str(jdic["Protein"]).strip()
				geneExpData=str(jdic["Gene Expression Data"]).strip()
			es.indices.refresh(index="xxxxxxxxx-index")

			if foundHits >0:
				tempgeneExplist=geneExpData.split(';')[1:]
				tempgeneExplist.sort(key=lambda g: g.upper())
				for i in tempgeneExplist:
					tempListExp=[uniprotkb,protname,i.split('|')[0],i.split('|')[1]]
					geneExplist.append(tempListExp)
		protList=[uniprotkb,protname]
		response_data ={'geneExplist':geneExplist,'foundHits':foundHits,'protList':protList,'lenOfGeneExpData':len(geneExplist)}

		return HttpResponse(json.dumps(response_data), content_type="application/json")


class SwaggerRestAPIView(APIView):
	'''
	Creation of Manual schema for REST API
	'''
	schema=ManualSchema(fields=[
		coreapi.Field(
			name="UniProtKB accession",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:O89020'
			),
		coreapi.Field(
			name="Protein",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Afamin'
			),
		coreapi.Field(
			name="Gene",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Afm'
			),
		coreapi.Field(
			name="Peptide sequence",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:AAPITQYLK'
			),
		coreapi.Field(
			name="Panel",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Panel-1'
			),
		coreapi.Field(
			name="Strain",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:NODSCID'
			),
		coreapi.Field(
			name="Mutant",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Wild'
			),
		coreapi.Field(
			name="Sex",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Male'
			),
		coreapi.Field(
			name="Biological matrix",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Plasma'
			),
		coreapi.Field(
			name="Subcellular localization",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Secreted'
			),
		coreapi.Field(
			name="Molecular pathway(s)",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Complement and coagulation cascades'
			),
		coreapi.Field(
			name="Involvement in disease",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Adiponectin deficiency(ADPND)'
			),
		coreapi.Field(
			name="GO ID",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:GO:0008015'
			),
		coreapi.Field(
			name="GO Term",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:blood circulation'
			),
		coreapi.Field(
			name="GO Aspects",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:Biological Process'
			),
		coreapi.Field(
			name="Drug associations ID",
			required=False,
			location="query",
			schema=coreschema.String(),
			description='Example:DB05202'
			)
		])
	def get(self, request):
		"""
		This function is searching results, based on given multi search parameters
		in database.
		"""
		ip = get_ip(request, right_most_proxy=True)
		IpAddressInformation.objects.create(ip_address=ip)

		useruniprotkb =""
		userprotein =""
		usergeneid =""
		userorg=""
		userorgid=""
		usersubcell =""
		userpepseq =""
		userkegg =""
		userdis =""
		usergoid =""
		usergotn =""
		usergot=""
		userdrug=""
		userstrain=""
		userknockout=""
		userpanel=""
		usersex=""
		userbioMatrix=""
		filterSearchTerm=[]
		filterSearchType=[]
		filtersearchStatus=0
		try:
			useruniprotkb = request.GET["UniProtKB accession"]
		except MultiValueDictKeyError:
			pass
		if '|' in useruniprotkb:
			useruniprotkb=(useruniprotkb.strip()).split('|')
		else:
			useruniprotkb=(useruniprotkb.strip()).split('\n')
		useruniprotkb=[(item.strip()).lower() for item in useruniprotkb]
		useruniprotkb=map(str, useruniprotkb)
		useruniprotkb=filter(None, useruniprotkb)

		try:
			userprotein = request.GET["Protein"]
		except MultiValueDictKeyError:
			pass
		if '|' in userprotein:
			userprotein=(userprotein.strip()).split('|')
		else:
			userprotein=(userprotein.strip()).split('\\n')
		userprotein=[(item.strip()).lower() for item in userprotein]
		userprotein=map(str, userprotein)
		userprotein=filter(None, userprotein)

		try:
			usergeneid = request.GET["Gene"]
		except MultiValueDictKeyError:
			pass
		if '|' in usergeneid:
			usergeneid=(usergeneid.strip()).split('|')
		else:
			usergeneid=(usergeneid.strip()).split('\\n')
		usergeneid=[(item.strip()).lower() for item in usergeneid]
		usergeneid=map(str, usergeneid)
		usergeneid=filter(None, usergeneid)

		try:
			userorg = request.GET["Organism"]
		except MultiValueDictKeyError:
			pass
		if '|' in userorg:
			userorg=(userorg.strip()).split('|')
		else:
			userorg=(userorg.strip()).split('\\n')
		userorg=[(item.strip()).lower() for item in userorg]
		userorg=map(str, userorg)
		userorg=filter(None, userorg)

		try:
			userorgid = request.GET["Organism ID"]
		except MultiValueDictKeyError:
			pass
		if '|' in userorgid:
			userorgid=(userorgid.strip()).split('|')
		else:
			userorgid=(userorgid.strip()).split('\\n')
		userorgid=[(item.strip()).lower() for item in userorgid]
		userorgid=map(str, userorgid)
		userorgid=filter(None, userorgid)

		try:
			usersubcell = request.GET["Subcellular localization"]
		except MultiValueDictKeyError:
			pass
		if '|' in usersubcell:
			usersubcell=(usersubcell.strip()).split('|')
		else:
			usersubcell=(usersubcell.strip()).split('\\n')
		usersubcell=[(item.strip()).lower() for item in usersubcell]
		usersubcell=map(str, usersubcell)
		usersubcell=filter(None, usersubcell)

		try:
			userpepseq = request.GET["Peptide sequence"]
		except MultiValueDictKeyError:
			pass
		if '|' in userpepseq:
			userpepseq=(userpepseq.strip()).split('|')
		else:
			userpepseq=(userpepseq.strip()).split('\\n')
		userpepseq=[(item.strip()).lower() for item in userpepseq]
		userpepseq=map(str, userpepseq)
		userpepseq=filter(None, userpepseq)

		try:
			userkegg = request.GET["Molecular pathway(s)"]
		except MultiValueDictKeyError:
			pass
		if '|' in userkegg:
			userkegg=(userkegg.strip()).split('|')
		else:
			userkegg=(userkegg.strip()).split('\\n')
		userkegg=[(item.strip()).lower() for item in userkegg]
		userkegg=map(str, userkegg)
		userkegg=filter(None, userkegg)

		try:
			userdis = request.GET["Involvement in disease"]
		except MultiValueDictKeyError:
			pass
		if '|' in userdis:
			userdis=(userdis.strip()).split('|')
		else:
			userdis=(userdis.strip()).split('\\n')
		userdis=[(item.strip()).lower() for item in userdis]
		userdis=map(str, userdis)
		userdis=filter(None, userdis)

		try:
			usergoid = request.GET["GO ID"]
		except MultiValueDictKeyError:
			pass
		if '|' in usergoid:
			usergoid=(usergoid.strip()).split('|')
		else:
			usergoid=(usergoid.strip()).split('\\n')
		usergoid=[(item.strip()).lower() for item in usergoid]
		usergoid=map(str, usergoid)
		usergoid=filter(None, usergoid)

		try:
			usergotn = request.GET["GO Term"]
		except MultiValueDictKeyError:
			pass
		if '|' in usergotn:
			usergotn=(usergotn.strip()).split('|')
		else:
			usergotn=(usergotn.strip()).split('\\n')
		usergotn=[(item.strip()).lower() for item in usergotn]
		usergotn=map(str, usergotn)
		usergotn=filter(None, usergotn)

		try:
			usergot = request.GET["GO Aspects"]
		except MultiValueDictKeyError:
			pass
		if '|' in usergot:
			usergot=(usergot.strip()).split('|')
		else:
			usergot=(usergot.strip()).split('\\n')
		usergot=[(item.strip()).lower() for item in usergot]
		usergot=map(str, usergot)
		usergot=filter(None, usergot)

		try:
			userdrug = request.GET["Drug associations ID"]
		except MultiValueDictKeyError:
			pass
		if '|' in userdrug:
			userdrug=(userdrug.strip()).split('|')
		else:
			userdrug=(userdrug.strip()).split('\\n')
		userdrug=[(item.strip()).lower() for item in userdrug]
		userdrug=map(str, userdrug)
		userdrug=filter(None, userdrug)

		try:
			userstrain = request.GET["Strain"]
		except MultiValueDictKeyError:
			pass
		if '|' in userstrain:
			userstrain=(userstrain.strip()).split('|')
		else:
			userstrain=(userstrain.strip()).split('\\n')
		userstrain=[(item.strip()).lower() for item in userstrain]
		userstrain=map(str, userstrain)
		userstrain=filter(None, userstrain)

		try:
			userknockout = request.GET["Mutant"]
		except MultiValueDictKeyError:
			pass
		if '|' in userknockout:
			userknockout=(userknockout.strip()).split('|')
		else:
			userknockout=(userknockout.strip()).split('\\n')
		userknockout=[(item.strip()).lower() for item in userknockout]
		userknockout=map(str, userknockout)
		userknockout=filter(None, userknockout)

		try:
			userpanel = request.GET["Panel"]
		except MultiValueDictKeyError:
			pass
		if '|' in userpanel:
			userpanel=(userpanel.strip()).split('|')
		else:
			userpanel=(userpanel.strip()).split('\\n')
		userpanel=[(item.strip()).lower() for item in userpanel]
		userpanel=map(str, userpanel)
		userpanel=filter(None, userpanel)

		try:
			usersex = request.GET["Sex"]
		except MultiValueDictKeyError:
			pass
		if '|' in usersex:
			usersex=(usersex.strip()).split('|')
		else:
			usersex=(usersex.strip()).split('\\n')
		usersex=[(item.strip()).lower() for item in usersex]
		usersex=map(str, usersex)
		usersex=filter(None, usersex)

		try:
			userbioMatrix = request.GET["Biological matrix"]
		except MultiValueDictKeyError:
			pass
		if '|' in userbioMatrix:
			userbioMatrix=(userbioMatrix.strip()).split('|')
		else:
			userbioMatrix=(userbioMatrix.strip()).split('\\n')
		userbioMatrix=[(item.strip()).lower() for item in userbioMatrix]
		userbioMatrix=map(str, userbioMatrix)
		userbioMatrix=filter(None, userbioMatrix)

		spquerylist =[]
		searchtermlist=[]
		if len(useruniprotkb) >0:
			shouldlist=[]
			for x in useruniprotkb:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["UniProtKB Accession.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userprotein)> 0:
			shouldlist=[]
			for x in userprotein:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Protein.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(usergeneid) >0:
			shouldlist=[]
			for x in usergeneid:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Gene.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userorg) > 0:
			shouldlist=[]
			for x in userorg:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Organism.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userorgid) > 0:
			shouldlist=[]
			for x in userorgid:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Organism ID.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(usersubcell) >0:
			shouldlist=[]
			for x in usersubcell:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["SubCellular.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userpepseq) >0:
			shouldlist=[]
			for x in userpepseq:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Peptide Sequence.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userkegg) >0:
			shouldlist=[]
			for x in userkegg:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Mouse Kegg Pathway Name.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userdis) >0:
			shouldlist=[]
			for x in userdis:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Human Disease Name.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(usergoid) >0:
			sdict={}
			sdict["Mouse Go ID.ngram"]=[i.split(' ')[0] for i in usergoid]
			tdict={}
			tdict["terms"]=sdict
			searchtermlist.append(tdict)
			shouldlist=[]
			for x in usergoid:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Mouse Go ID.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(usergotn) >0:
			shouldlist=[]
			for x in usergotn:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Mouse Go Name.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(usergot) > 0:
			shouldlist=[]
			for x in usergot:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Mouse Go Term.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if len(userdrug) > 0:
			shouldlist=[]
			for x in userdrug:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Human Drug Bank.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)

		if len(userstrain) > 0:
			filterSearchType.append('strain')
			filterSearchTerm.append('|'.join(userstrain))
			shouldlist=[]
			for x in userstrain:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Strain.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)

		if len(userknockout) > 0:
			shouldlist=[]
			for x in userknockout:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Knockout.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)

		if len(userpanel) > 0:
			shouldlist=[]
			for x in userpanel:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Panel.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)

		if len(usersex) > 0:
			filterSearchType.append('sex')
			filterSearchTerm.append('|'.join(usersex))
			shouldlist=[]
			for x in usersex:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Sex.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)

		if len(userbioMatrix) > 0:
			filterSearchType.append('biologicalMatrix')
			filterSearchTerm.append('|'.join(userbioMatrix))
			shouldlist=[]
			for x in userbioMatrix:
				tempquery={
							"multi_match":{
								"query":x.strip(),
								"type":"best_fields",
								"fields":["Biological Matrix.ngram"],
								"minimum_should_match":"100%"
							}
						}
				shouldlist.append(tempquery)
			booldic={}
			booldic["bool"]={"should":shouldlist,"minimum_should_match": 1}
			searchtermlist.append(booldic)
		if not searchtermlist or len(searchtermlist)==0:
			return Response({"error": "No information passed!"}, status=status.HTTP_400_BAD_REQUEST)

		es.indices.refresh(index="xxxxxxxxx-index")

		query={
			"query": {
				"bool": {
					"must":searchtermlist
				}
			}
		}

		try:
			if filterSearchType.index('sex') >=0:
				filtersearchStatus=1
		except ValueError:
			pass
		try:
			if filterSearchType.index('strain') >=0:
				filtersearchStatus=1
		except ValueError:
			pass
		try:
			if filterSearchType.index('biologicalMatrix') >=0:
				filtersearchStatus=1
		except ValueError:
			pass
		try:
			if filterSearchType.index('panel') >=0:
				filtersearchStatus=1
		except ValueError:
			pass
		try:
			if filterSearchType.index('knockout') >=0:
				filtersearchStatus=1
		except ValueError:
			pass
		jfinaldata=[]
		res=helpers.scan(client=es,scroll='2m',index="xxxxxxxxx-index", doc_type="xxxxxxxx-type",query=query,request_timeout=30)
		jfinaldata=[]
		uniprotpepinfo={}
		for i in res:
			jdic=i['_source']
			jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
			panelFilter=True
			if len(userpanel) >0:
				for q in userpanel:
					if q.lower() in (jdic['Panel'].lower()).split(';'):
						panelFilter=True
						break
				else:
					panelFilter=False
				#if jdic["Retention Time"].lower() =='na' or jdic["Gradients"].lower() =='na':
			if jdic["UniprotKb entry status"] =="Yes" and panelFilter:
				if uniprotpepinfo.has_key(jdic["UniProtKB Accession"]) and panelFilter:
					uniprotpepinfo[jdic["UniProtKB Accession"]].append(jdic["Peptide Sequence"])
				else:
					uniprotpepinfo[jdic["UniProtKB Accession"]]=[jdic["Peptide Sequence"]]

				if jdic["Human UniProtKB Accession"].lower() !='na' and jdic["Present in human ortholog"].lower() =='no':
					jdic["Available assays in human ortholog"]='http://mrmassaydb.proteincentre.com/search/hyperlink/?UniProtKB Accession='+jdic["Human UniProtKB Accession"]
				else:
					jdic["Available assays in human ortholog"]='NA'

				#if jdic["Retention Time"].lower() =='na' or jdic["Gradients"].lower() =='na':
				if jdic["Retention Time"].lower() =='na':
					jdic["Summary Concentration Range Data"]='NA'
					jdic["Concentration View"]='NA'
				if filtersearchStatus==0:

					jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/u','µg protein/µ')
					jdic["Summary Concentration Range Data"]=jdic["Summary Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

					jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/u','µg protein/µ')
					jdic["All Concentration Range Data"]=jdic["All Concentration Range Data"].replace('ug protein/mg','µg protein/mg')

					jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/u','µg protein/µ')
					jdic["All Concentration Range Data-Sample LLOQ Based"]=jdic["All Concentration Range Data-Sample LLOQ Based"].replace('ug protein/mg','µg protein/mg')

					jdic["Concentration View"]=jdic["Concentration View"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["Concentration Range"]=jdic["Concentration Range"].replace('fmol target protein/u','fmol target protein/µ')

					jdic["LLOQ"]=jdic["LLOQ"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["ULOQ"]=jdic["ULOQ"].replace('fmol target protein/u','fmol target protein/µ')
					jdic["Sample LLOQ"]=jdic["Sample LLOQ"].replace('fmol target protein/uL','fmol target protein/µ')

					if jdic["Unique in protein"].upper() =='NA':
						jdic["Unique in protein"]=jdic["Unique in protein"].replace('NA','No')
					if jdic["Present in isoforms"].upper() =='NA':
						jdic["Present in isoforms"]=jdic["Present in isoforms"].replace('NA','No')
				jfinaldata.append(jdic)

		foundHits=len(jfinaldata)
		if foundHits <= 0:
			return Response({"error": "No information found!"}, status=status.HTTP_400_BAD_REQUEST)
		es.indices.refresh(index="xxxxxxxxx-index")
		if filtersearchStatus>0:
		 jfinaldata,filteredUniProtIDs=filterSearch(jfinaldata,filterSearchTerm,filterSearchType)

		foundHits=len(jfinaldata)
		if foundHits <= 0:
			return Response({"error": "No information found!"}, status=status.HTTP_400_BAD_REQUEST)
		else:
			jfinaldata=updateDataToDownload(jfinaldata)
			jsonfilename=str(uuid.uuid4())+'_restapi_search.json'
			jsonfilepath=os.path.join(settings.BASE_DIR, 'resultFile', 'jsonData','resultJson', 'restapisearch', jsonfilename)
			jsonfileoutput= open(jsonfilepath,'w')
			json.dump(jfinaldata,jsonfileoutput)
			jsonfileoutput.close()

			df=pd.read_json(jsonfilepath)
			df.rename(columns ={'UniProtKB Accession':'Mouse UniProtKB accession','Protein':'Mouse Protein name',\
					'Gene':'Mouse Gene','Present in isoforms':'Peptide present in isoforms',\
					'Peptide Sequence':'Peptide sequence','Knockout':'Mutant',\
					'Unique in protein':'Peptide unique in proteome','Human UniProtKB Accession': \
					'UniProtKB accession of human ortholog','Human ProteinName': 'Human ortholog',\
					'Peptide ID':'Assay ID','Present in human isoforms':'Peptide present in human isoforms',\
					'Unique in human protein':'Peptide unique in human protein',\
					'SubCellular':'Subcellular localization','Mouse Kegg Pathway':'Molecular pathway(s) Mouse',\
					'Present in human ortholog':'Peptide present in human ortholog',\
					'Human Kegg Pathway':'Molecular pathway(s) Human','Human UniProt DiseaseData':'Involvement in disease-Human(UniProt)',\
					'Human DisGen DiseaseData':'Involvement in disease-Human(DisGeNET)','Human Drug Bank':\
					'Drug associations-Human','CZE Purity':'CZE','AAA Concentration':'AAA',\
					'Mouse Go':'GO Mouse','Human Go':'GO Human','LLOQ':'Assay LLOQ','ULOQ':'Assay ULOQ'}, inplace =True)
			#df=df.loc[:,restApiColname]
			updatedresult=df.to_json(orient='records')
			updatedresult=json.loads(updatedresult)
			updatedUniInfo=pepbasedInfoRESTAPI(updatedresult,uniprotpepinfo)

		return Response(updatedUniInfo)

def peptideUniqueness(request):
	"""
	This function is searching results, based on given multi search parameters
	in database.
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		response_data={}
		useruniprotkb=str(request.GET.get("Uniprotkb")).strip()
		userpepseq=str(request.GET.get("pepseq")).strip()
		userfastafilename=str(request.GET.get("fastafile")).strip()
		userpepseq=userpepseq.upper()
		reachable=True
		valid=False
		pepjsondatalist=[]
		es.indices.refresh(index="xxxxxxxxx-index")
		query={"query": {
			"bool": {
				"must": [
					{"match": {"UniProtKB Accession": useruniprotkb}},
					{"match": {"Peptide Sequence": userpepseq}}				]
			}
		}
		}
		res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)
		foundHits=res["hits"]["total"]
		originalpepunqstatus="Not unique"
		uniprotkbstatus="NA"
		for hit in res['hits']['hits']:
			jdic=hit["_source"]
			jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
			uniprotkbstatus=str(jdic["UniprotKb entry status"]).strip()
			if jdic["Unique in protein"].upper() =='NA':
				jdic["Unique in protein"]=jdic["Unique in protein"].replace('NA','No')
			if jdic["Present in isoforms"].upper() =='NA':
				jdic["Present in isoforms"]=jdic["Present in isoforms"].replace('NA','No')
			if len(str(jdic["Unique in protein"]).strip())>0:
				originalpepunqstatus=str(jdic["Unique in protein"]).strip()
		es.indices.refresh(index="xxxxxxxxx-index")
		fastafilepath=os.path.join(settings.BASE_DIR, 'resultFile', 'fastaFile', userfastafilename+'.fasta')
		if os.path.exists(fastafilepath) and foundHits>0:
			proseq=''
			try:
				sleep(random.randint(5,10))
				requests.get("https://www.uniprot.org/", timeout=1)
				unidatafasta = urllib.urlopen("https://www.uniprot.org/uniprot/" + useruniprotkb + ".fasta")
				for i in range(1):
					header=unidatafasta.next()
					if '>' in header[0]:
						valid=True
				if valid:
					for line in unidatafasta:
						proseq+=line.strip()
				unidatafasta.close()
			except ConnectionError as e:
				reachable=False

			if reachable:
				fastaseq=[]
				contextpepuser=[]
				peptide_pattern = re.compile(userpepseq,re.IGNORECASE)
				
				for match in re.finditer(peptide_pattern,proseq):
					matchpdbseqpos=range(int(match.start()),match.end())
					proseq=proseq.upper()
					tseq=proseq
					seqlen=len(proseq)
					proseqlist=list(proseq)
					for y in range(0,len(proseqlist)):
						if y in matchpdbseqpos:
							proseqlist[y]='<b><font color="red">'+proseqlist[y]+'</font></b>'
						if y%60 ==0 and y !=0:
							proseqlist[y]=proseqlist[y]+'<br/>'
					proseq="".join(proseqlist)
					contextpepuser.append(['<a target="_blank" href="https://www.uniprot.org/uniprot/'+useruniprotkb+'">'+useruniprotkb+'</a>',(int(match.start())+1),match.end(),matchpdbseqpos,tseq,seqlen,proseq,'MouseQuaPro'])

				for useq_record in SeqIO.parse(fastafilepath, 'fasta'):
					seqheader = useq_record.id
					sequniID = seqheader.split(' ')[0]
					sequniID=sequniID.replace('>','')
					tempseqs = str(useq_record.seq).strip()
					fastaseq.append(tempseqs.upper())
					for fmatch in re.finditer(peptide_pattern,tempseqs.upper()):
						fmatchpdbseqpos=range(int(fmatch.start()),fmatch.end())
						tempseqs=tempseqs.upper()
						tseq=tempseqs
						seqlen=len(tempseqs)
						tempseqslist=list(tempseqs)
						for y in range(0,len(tempseqslist)):
							if y in fmatchpdbseqpos:
								tempseqslist[y]='<b><font color="red">'+tempseqslist[y]+'</font></b>'
							if y%60 ==0 and y !=0:
								tempseqslist[y]=tempseqslist[y]+'<br/>'
						tempseqs="".join(tempseqslist)
						contextpepuser.append([sequniID,(int(fmatch.start())+1),fmatch.end(),fmatchpdbseqpos,tseq,seqlen,tempseqs,'User data'])

				useruniqstatus=''
				unqfastaseq=list(set(fastaseq))
				indices = [i for i, s in enumerate(fastaseq) if userpepseq.upper() in s]
				if len(indices)==0:
					useruniqstatus ="Not present"
				elif len(indices) > 1:
					useruniqstatus="Present but not unique"
				else:
					useruniqstatus="Present and unique"
				for x in contextpepuser:
					tempdatadic={}
					tempdatadic["proteinID"]=x[0]
					tempdatadic["peptideSequence"]=userpepseq
					tempdatadic["start"]=str(x[1])
					tempdatadic["end"]=str(x[2])
					tempdatadic["seqlen"]=str(x[-3])
					tempdatadic["seq"]=str(x[-4])
					if 'target' in x[0]:
						tempdatadic["peptideuniqueinprotein"]=originalpepunqstatus
					else:
						tempdatadic["peptideuniqueinprotein"]=useruniqstatus
					tempdatadic["datasource"]=str(x[-1])
					tempdatadic["highlightedpepseq"]=str(x[-2])
					pepjsondatalist.append(tempdatadic)
				pepunqdata={"data":pepjsondatalist}
				response_data={'pepunqdata':json.dumps(pepunqdata),'reachable':reachable}
			else:
				response_data={'reachable':reachable}
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def contact(request):
	"""
	This is contact form where 
	Admin will recieve email from contact page.
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		contactdetails=json.loads(request.GET.get('contactdetails').strip())
		form_email = contactdetails["contactFormEmail"].strip() # get email address
		form_full_name = contactdetails["contactFormName"].strip() # get name
		form_message = contactdetails["contactFormMessage"].strip() # get message
		form_userWantForward = contactdetails["contactFormCopy"] # user Want to Forward this email
		subject='Site contact form for QMPKB'
		from_email=settings.EMAIL_HOST_USER
		to_email=[from_email, '<EMAIL>','<EMAIL>','<EMAIL>']
		contact_message="%s: %s via %s"%(
			form_full_name,
			form_message,
			form_email)
		send_mail(subject,contact_message,from_email,to_email,fail_silently=True) # sent email

		#foward user the same email
		if form_userWantForward:
			contact_message_user="%s: %s via %s"%(
				form_full_name,
				form_message,
				form_email)
			send_mail(subject,contact_message_user,from_email,[form_email],fail_silently=True) # sent email

		return HttpResponse({}, content_type="application/json")


def foldChange(request):
	if request.method=='GET':
		dropDownTerm=request.GET.get("dropDownTerm")# user input for searching result
		dropDownTerm= str(dropDownTerm).strip()
		checkBoxTerm=request.GET.get("checkBoxTerm")# user input for searching result
		checkBoxTerm= str(checkBoxTerm).strip()
		resultfileName=request.GET.get("fileName")# user input for searching result
		resultfileName= str(resultfileName).strip()
		queryDataDic=json.loads(request.GET.get("queryData"))# user input for searching result
		
		homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
		matrixFilePath= os.path.join(homedir, 'src/qmpkbmotherfile', 'mouseQuaProMatrix.tsv')
		resultfilePath=os.path.join(homedir, 'src/','/'.join(resultfileName.split('/')[1:]))


		foldChangeStatus=True
		response_data={}
		log2foldChangeData=[]
		foldchangePvalue=[]
		flagData=[]
		foldPairLegend=[]
		defaultDropDownMenus=['Biological Matrix','Sex','Strain']
		dropdownQuery=dropDownTerm
		defaultDropDownMenus.remove(dropdownQuery)
		checkedQuery=checkBoxTerm.split(',')
		resultDF=pd.read_csv(resultfilePath)
		proteinData=list(resultDF['Peptide sequence'] + '_' + resultDF['Mouse UniProtKB accession'])
		df=pd.read_csv(matrixFilePath,delimiter='\t', na_filter=False)
		columns=list(df.columns)[:3]+proteinData
		del queryDataDic[dropdownQuery]
		querkeys=queryDataDic.keys()

		df=df.loc[(df[querkeys[0]].isin(queryDataDic[querkeys[0]])) & (df[querkeys[1]].isin(queryDataDic[querkeys[1]]))]
		df=df[columns]
		df.drop(defaultDropDownMenus, axis=1, inplace=True)
		df = df[(df[dropdownQuery] == checkedQuery[0]) | (df[dropdownQuery] == checkedQuery[1])]
		for protID in proteinData:
			subDF=df[[dropdownQuery,protID]]
			pair1=subDF[protID][(subDF[dropdownQuery]==checkedQuery[0]) & (subDF[protID].astype(str) !='nan')]
			pair1=list(pair1.astype(float))
			pair2=subDF[protID][(subDF[dropdownQuery]==checkedQuery[1]) & (subDF[protID].astype(str) !='nan')]
			pair2=list(pair2.astype(float))
			if len(pair1)>0 and len(pair2)>0:
				meanConcPair1=np.mean(pair1)
				meanConcPair2=np.mean(pair2)
				log2foldChangeData.append(math.log(abs(meanConcPair1/meanConcPair2),2))
				pair1=[math.log(v1) for v1 in pair1]
				pair2=[math.log(v2) for v2 in pair2]
				if len(pair1)==1 or len(pair2)==1:
					flagData.append('Yes')
					foldchangePvalue.append(1)
				else:
					try:
						stat, pval = mannwhitneyu(pair1, pair2)
						foldchangePvalue.append(pval)
						flagData.append('No')
					except ValueError:
						flagData.append('Yes')
						foldchangePvalue.append(1)
				foldPairLegend.append(protID)

		#foldchangePvalue_adjust =statsR.p_adjust(FloatVector(foldchangePvalue), method = 'BH')
		foldchangePvalue_adjust=(p_adjust_bh(foldchangePvalue)).tolist()
		foldchangePvalue_adjust=[-math.log10(p) for p in foldchangePvalue_adjust]
		indicesYes = [i for i, x in enumerate(flagData) if x == "Yes"]
		indicesNo = [i for i, x in enumerate(flagData) if x == "No"]
		try:
			maxAbsValLog2=max(list(map(abs,log2foldChangeData)))
			maxValPval=max(foldchangePvalue_adjust)
			hLine=abs(math.log10(0.05))
			if hLine > maxValPval:
				maxValPval=hLine
			flaggedData={
				'Yes':[list(np.array(log2foldChangeData)[indicesYes]),list(np.array(foldchangePvalue_adjust)[indicesYes]),list(np.array(foldPairLegend)[indicesYes])],
				'No':[list(np.array(log2foldChangeData)[indicesNo]),list(np.array(foldchangePvalue_adjust)[indicesNo]),list(np.array(foldPairLegend)[indicesNo])]
			}

			response_data ={
				'log2FoldData':flaggedData,
				'maxAbsValLog2':maxAbsValLog2,
				'hLine':hLine,
				'maxValPval':maxValPval,
				'foldChangeStatus':foldChangeStatus

			}

		except ValueError:
			foldChangeStatus=False
			response_data ={
				'log2FoldData':{},
				'maxAbsValLog2':0,
				'hLine':0,
				'maxValPval':0,
				'foldChangeStatus':foldChangeStatus

			}
		return HttpResponse(json.dumps(response_data), content_type="application/json")


def detailInformation(request):
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)

	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		resultfileName=request.GET.get("fileName")# user input for searching result
		resultfileName= str(resultfileName).strip()
		homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
		resultfilePath='NA'
		if resultfileName != 'NA':
			resultfilePath=os.path.join(homedir, 'src/resultFile/jsonData/resultJson/search/results/',resultfileName+'_search_proteincentric.json')
		else:
			resultfilePath=os.path.join(homedir, 'src/resultFile/preDownloadFile/json/all_data_proteincentric.json')

		fastafilename=request.GET.get("fastafilename")
		fastafilename= str(fastafilename).strip()
		if fastafilename != 'NA':
			fastafilename=fastafilename.replace('|','_')
		contextgoterm =[]
		reachable=True
		jvenndataseries=[]
		response_data = {}
		if len(uniprotkb)>0:
			uniprotkblist=[]
			code=None
			geneName=None
			protname=None
			humanProtName=None
			humanGeneName=None
			humanUniKb=None
			pepPresentInHumanOrtholog=None
			availableAssayInHumanOrtholog=None
			subcell=None
			humanDiseaseUniProt=['NA']
			humanDiseaseDisGeNet=['NA']
			drugBank=None
			orgID=None
			disStat=0
			drugStat=0
			assayStat=0
			bioMatStat=0
			strainStat=0
			es.indices.refresh(index="xxxxxxxxx-index")
			#build elasticsearch query based provided uniprotkb acc
			query={"query": {
				"bool": {
					"must": [
						{"match": {"UniProtKB Accession": uniprotkb}},
						{"match": {"UniprotKb entry status": "Yes"}}
					]
				}
			}
			}
			res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)

			foundHits=res["hits"]["total"]
			for hit in res['hits']['hits']:
				jdic=hit["_source"]
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				geneName=str(jdic["Gene"]).strip()
				protname=str(jdic["Protein"]).strip()
			es.indices.refresh(index="xxxxxxxxx-index")

			if foundHits >0:
				with open(resultfilePath) as rjf:
					for resitem in json.load(rjf)['data']:
						if resitem["UniProtKB Accession"]==uniprotkb:
							orgID=resitem["Organism ID"].strip()
							if len(resitem["Human ProteinName"].strip()) > 0 and resitem["Human ProteinName"].strip() != "NA":
								tempLst =resitem["Human ProteinName"].strip().split('|')
								humanProtName= "<br>".join(tempLst)
							else:
								humanProtName='NA'

							if len(resitem["Human Gene"].strip()) > 0 and resitem["Human Gene"].strip() != "NA":
								tempLst =(resitem["Human Gene"].strip()).split('|')
								humanGeneName= "<br>".join(tempLst)
							else:
								humanGeneName='NA'

							if len(resitem["Human UniProtKB Accession"].strip()) > 0 and resitem["Human UniProtKB Accession"].strip() != "NA":
								tempLst =(resitem["Human UniProtKB Accession"].strip()).split(',')
								for idx, val in enumerate(tempLst):
									tempLst[idx]='<a target="_blank" routerLinkActive="active" href="https://www.uniprot.org/uniprot/' + val+'">'+val+ '</a>'
								humanUniKb= "<br>".join(tempLst)
							else:
								humanUniKb='NA'
							pepPresentInHumanOrtholog=resitem["Present in human ortholog"][0].strip()

							if resitem["Available assays in human ortholog"].strip() != "NA":
								availableAssayInHumanOrtholog= '<a target="_blank" routerLinkActive="active" href="'+ resitem["Available assays in human ortholog"] + '">' + 'View' + '</a>'
							else:
								availableAssayInHumanOrtholog='NA'

							if len(resitem["SubCellular"].strip()) > 0:
								subcell =(resitem["SubCellular"].strip()).split('|')
							else:
								subcell=['NA']
							if len(resitem["Human UniProt DiseaseData"].strip()) > 0 and resitem["Human UniProt DiseaseData"].strip() != "NA":
								humanDiseaseUniProt=resitem["Human UniProt DiseaseData URL"].strip().split('|')
							else:
								humanDiseaseUniProt=['NA']

							if len(resitem["Human DisGen DiseaseData"].strip()) > 0 and resitem["Human DisGen DiseaseData"].strip() != "NA":
								humanDiseaseDisGeNet=resitem["Human DisGen DiseaseData URL"].strip().split('|')
							else:
								humanDiseaseDisGeNet=['NA']
							if len(resitem['Human Disease Name'].strip()) > 0 and resitem['Human Disease Name'].strip() != "NA":
								disStat=len(resitem['Human Disease Name'].strip().split('|'))
							if len(resitem['Peptide Sequence'].strip()) > 0 and resitem['Peptide Sequence'].strip() != "NA":
								assayStat=len(resitem['Peptide Sequence'].strip().split('<br>'))
							if len(resitem['Biological Matrix'].strip()) > 0 and resitem['Biological Matrix'].strip() != "NA":
								bioMatStat=len(resitem['Biological Matrix'].strip().split('<br>'))
							if len(resitem['Strain'].strip()) > 0 and resitem['Strain'].strip() != "NA":
								strainStat=len(resitem['Strain'].strip().split('<br>'))
							if len(resitem["Human Drug Bank"].strip()) > 0 and resitem["Human Drug Bank"].strip() != "NA":
								#tempLst =resitem["Human Drug Bank"].strip().split('|')
								drugBank=resitem["Human Drug Bank"].strip().split('|')
								drugStat=len(drugBank)
							else:
								drugBank=['NA']
							break
			orthologData=[
				{
					"humanProtName":humanProtName,
					"humanGeneName":humanGeneName,
					"humanUniKb":humanUniKb,
					"pepPresentInHumanortholog":pepPresentInHumanOrtholog,
					"availableAssayInHumanortholog":availableAssayInHumanOrtholog,
					"disStat":disStat,
					"drugStat":drugStat
				}
			]
			response_data ={
				"resultFilePath":resultfilePath,"proteinName":protname,"geneName":geneName,"uniprotkb":uniprotkb,"foundHits":foundHits,
				"orthologData":orthologData,"subcell":subcell,"humanDiseaseUniProt":humanDiseaseUniProt,"humanDiseaseDisGeNet":\
				humanDiseaseDisGeNet,"drugBankData":drugBank,"fastafilename":fastafilename,"orgID":orgID,
				"assayStat":assayStat,"bioMatStat":bioMatStat,"strainStat":strainStat
			}
			return HttpResponse(json.dumps(response_data), content_type="application/json")

def detailConcentration(request):
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		uniprotkb=str(request.GET.get("uniProtKb")).strip()
		resultFilePath= request.GET['resultFilePath']
		resultFilePath= str(request.GET.get("resultFilePath")).strip()

		filterSearchType=[str('sex'),str('strain'),str('biologicalMatrix'),str('knockout')]
		concUnit=[]
		strainData=None
		knockoutData=None
		bioMatData=None
		sexData=None
		allConcSamLLOQ=None
		allConc=None
		summaryConcData=[]
		es.indices.refresh(index="xxxxxxxxx-index")
		query={"query": {
			"bool": {
				"must": [
					{"match": {"UniProtKB Accession": uniprotkb}},
					{"match": {"UniprotKb entry status": "Yes"}}
				]
			}
		}
		}
		res = es.search(index="xxxxxxxxx-index", doc_type="xxxxxxxx-type", body=query)
		protinfo={}

		with open(resultFilePath) as rjf:
			for resitem in json.load(rjf)['data']:
				if resitem["UniProtKB Accession"]==uniprotkb:
					allConcSamLLOQ=resitem["All Concentration Range Data-Sample LLOQ Based"];
					allConc=resitem["All Concentration Range Data"];
					bioMatData=resitem["Biological Matrix Details"]
					strainData=resitem["Strain Details"]
					sexData=resitem["Sex Details"]
					knockoutData=resitem["Knockout Details"]
					pepinfo =resitem["Peptide Based Info"]
					for pepItem in pepinfo:
						tempPepSeq=pepItem["Peptide Sequence"].strip()

						if len(pepItem["concenQuery"].strip()) > 0 and pepItem["concenQuery"].strip().upper() !="NA":
							tempQuery=pepItem["concenQuery"].strip().replace('!','/')
							queryInfo=tempQuery.split('@')
							tempfilterSearchTerm=[str(queryInfo[0]),str(queryInfo[1]),str(queryInfo[2]),str(queryInfo[3])]
							protinfo[tempPepSeq]=tempfilterSearchTerm
					break
		finalconclist=[]
		for protKey in protinfo:
			sumconclist=[]
			foundHits=res["hits"]["total"]
			protList=[]
			jfinaldata=[]
			sampleLLOQ=''
			ULOQ=''
			filterSearchTerm=protinfo[protKey]
			for hit in res['hits']['hits']:
				jdic=hit["_source"]
				jdic={str(tkey):force_text(tvalue) for tkey,tvalue in jdic.items()}
				if str(jdic["Peptide Sequence"]).strip() ==protKey:
					if (str(jdic["Summary Concentration Range Data"]).strip()) >0 and (str(jdic["Summary Concentration Range Data"]).strip()).lower() !='na':
						sampleLLOQ=str(jdic["Sample LLOQ"]).strip()
						ULOQ=str(jdic["ULOQ"]).strip()
						jfinaldata.append(jdic)

			es.indices.refresh(index="xxxxxxxxx-index")
			jfinaldata=filterConcentration(jfinaldata,filterSearchTerm,filterSearchType)
			sampleLLOQ=sampleLLOQ.replace(' (fmol target protein/ug extracted protein)','')
			sampleLLOQ=dict([samval.split('|') for samval in sampleLLOQ.split(';')])
			ULOQ=ULOQ.replace(' (fmol target protein/ug extracted protein)','')
			ULOQ=dict([uval.split('|') for uval in ULOQ.split(';')])
			sumconcdata=str(jfinaldata[0]["Summary Concentration Range Data"]).strip()
			allconcdata=str(jfinaldata[0]["All Concentration Range Data"]).strip()
			allconcdataSampleLLOQ=str(jfinaldata[0]["All Concentration Range Data-Sample LLOQ Based"]).strip()
			sumconcdata=sumconcdata.replace('fmol target protein/u','fmol target protein/µ')
			sumconcdata=sumconcdata.replace('ug extracted protein/uL','µg extracted protein/µL')
			sumconcdata=sumconcdata.replace('ug extracted protein/mg','µg extracted protein/mg')

			allconcdata=allconcdata.replace('fmol target protein/u','fmol target protein/µ')
			allconcdata=allconcdata.replace('ug extracted protein/u','µg protein/µ')
			allconcdata=allconcdata.replace('ug extracted protein/mg','µg extracted protein/mg')

			allconcdataSampleLLOQ=allconcdataSampleLLOQ.replace('fmol target protein/u','fmol target protein/µ')
			allconcdataSampleLLOQ=allconcdataSampleLLOQ.replace('ug extracted protein/u','µg extracted protein/µ')

			sumconcinfo=sumconcdata.split(';')
			allconinfo=allconcdata.split(';')
			allconinfoSampleLLOQ=allconcdataSampleLLOQ.split(';')
			for scitem in sumconcinfo:
				scinfo =scitem.split('|')
				tempSampleLLOQ=sampleLLOQ[scinfo[2]]
				tempULOQ=ULOQ[scinfo[2]]
				stempid='|'.join(map(str,scinfo[2:5]))
				tempMatchConcList=[]
				for acitem in allconinfo:
					acinfo =acitem.split('|')
					del acinfo[3]
					atempid='|'.join(map(str,acinfo[2:5]))
					if stempid.lower() ==atempid.lower():
						concUnit.append('(' + acinfo[-2].strip().split(' (')[-1].strip())
						if float(acinfo[-3].strip().split(' ')[0].strip()) >0:
							tempMatchConcList.append(acinfo[-3].strip().split(' ')[0].strip())
				tempMatchConcData='|'.join(map(str,tempMatchConcList))

				tempMatchConcDataSampleLLOQ='NA'
				templen=1
				try:
					templen=len(filter(None,map(str,list(set(allconinfoSampleLLOQ)))))
				except UnicodeEncodeError:
					pass
				if 'NA' != ''.join(list(set(allconinfoSampleLLOQ))) and templen>0:
					tempMatchConcListSampleLLOQ=[]
					for slacitem in allconinfoSampleLLOQ:
						if slacitem.upper().strip() !='NA':
							slacinfo =slacitem.split('|')
							del slacinfo[3]
							slatempid='|'.join(map(str,slacinfo[2:5]))

							if stempid.lower() ==slatempid.lower():
								tempMatchConcListSampleLLOQ.append(slacinfo[-3].strip().split(' ')[0].strip())
					tempMatchConcDataSampleLLOQ='|'.join(map(str,tempMatchConcListSampleLLOQ))

				scinfo.append(str(jfinaldata[0]["UniProtKB Accession"]).strip())
				scinfo.append(str(jfinaldata[0]["Protein"]).strip())
				scinfo.append(str(jfinaldata[0]["Peptide Sequence"]).strip())
				stempid=stempid+'|'+protKey[0:3]+'..'
				scinfo.append(stempid)
				scinfo.append(tempMatchConcData)
				scinfo.append(tempMatchConcDataSampleLLOQ)
				scinfo.append(tempSampleLLOQ)
				scinfo.append(tempULOQ)
				scinfo=[scI.split('(')[0].strip()  if '(' in scI else scI for scI in scinfo]
				sumconclist.append(scinfo)
			summaryConcData.insert(0,str(jfinaldata[0]["Peptide Sequence"]).strip())
			summaryConcData.insert(0,str(jfinaldata[0]["Protein"]).strip())
			summaryConcData.insert(0,str(jfinaldata[0]["UniProtKB Accession"]).strip())
			sumconclist=sorted(sumconclist,key=lambda l:l[4])
			sumconclist=sorted(sumconclist,key=lambda l:l[3])
			sumconclist=sorted(sumconclist,key=lambda l:l[2])
			for conItem in sumconclist:
				finalconclist.append(conItem)
		concUnit=list(set(concUnit))
		concUnit='&'.join(concUnit)
		lenOfConcData=len(finalconclist)
		response_data ={'conclist':finalconclist,'foundHits':foundHits,'concUnit':concUnit,'lenOfConcData':lenOfConcData,
		"strainData":strainData,"knockoutData":knockoutData,"bioMatData":bioMatData,"sexData":sexData,
		"allConcSamLLOQ":allConcSamLLOQ,"allConc":allConc
		}
		
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def saveFastaFile(request):
	"""
	This is function save fasta file.
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		userInputFastaFileContext=''
		userInputFastaFileContext=str(request.GET.get('fastaFileContext')).strip()
		userInputFastaFileContext=userInputFastaFileContext.replace('\\n','\n')
		userInputFastaFileContext=userInputFastaFileContext.replace('"','')
		nameFile=str(uuid.uuid4()) # generate random file name to store user search result
		fastaseq=[]
		finalsearhdata=''
		currdate=str(datetime.datetime.now())
		currdate=currdate.replace('-','_')
		currdate=currdate.replace(' ','_')
		currdate=currdate.replace(':','_')
		currdate=currdate.replace('.','_')
		nameFIle=currdate+'_'+nameFile
		fastafilename=nameFile+'.fasta'
		#storing user provided fasta file
		fastafilepath=os.path.join(settings.BASE_DIR, 'resultFile', 'fastaFile', fastafilename)
		fastafilewrite=open(fastafilepath,"w")
		fastafilewrite.write(userInputFastaFileContext)
		fastafilewrite.close()
		response_data={'nameFile':nameFile}
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def submission(request):
	"""
	This is submission form where 
	Admin will recieve email from submission page.
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		submissiondetails=json.loads(request.GET.get('submissiondetails').strip())
		form_email = submissiondetails["submissionFormEmail"].strip() # get email address
		form_full_name = submissiondetails["submissionFormName"].strip() # get name
		form_laboratory = submissiondetails["submissionFormLaboratory"].strip() # get Laboratory
		form_experiment = submissiondetails["submissionFormExperiment"].strip() # get Experiment
		try:
			form_publication = submissiondetails["submissionFormPublication"].strip() # get Publication
		except AttributeError:
			form_publication = 'NA'
		form_data_repository = submissiondetails["submissionFormDataRepository"].strip() # get Data Repository
		form_data_acession_number = submissiondetails["submissionFormDataAcessionNumber"].strip() # get Data Acession Number
		try:
			form_repository_password = submissiondetails["submissionFormRepositoryPassword"].strip() # get Repository Password
		except AttributeError:
			form_repository_password = 'NA'
		form_message = submissiondetails["submissionFormMessage"].strip() # get message
		form_userWantForward = submissiondetails["submissionFormCopy"] # user Want to Forward this email
		subject='Site data submission form for MouseQuaPro'
		from_email=settings.EMAIL_HOST_USER
		to_email=['<EMAIL>','<EMAIL>','<EMAIL>']
		submission_message="Full Name:%s, Email:%s,Laboratory:%s, Description of experiment:%s, Publication(s) DOI:%s,Data repository:%s,Data acession number:%s,Repository password:%s,Message: %s"%(
			form_full_name,
			form_email,
			form_laboratory,
			form_experiment,
			form_publication,
			form_data_repository,
			form_data_acession_number,
			form_repository_password,
			form_message)
		send_mail(subject,submission_message,from_email,to_email,fail_silently=True) # sent email

		#foward user the same email
		if form_userWantForward:
			submission_message_user="Full Name:%s, Email:%s,Laboratory:%s, Description of experiment:%s, Publication(s) DOI:%s,Data repository:%s,Data acession number:%s,Repository password:%s,Message: %s"%(
			form_full_name,
			form_email,
			form_laboratory,
			form_experiment,
			form_publication,
			form_data_repository,
			form_data_acession_number,
			form_repository_password,
			form_message)
			send_mail(subject,submission_message_user,from_email,[form_email],fail_silently=True) # sent email

		return HttpResponse({}, content_type="application/json")

def generateDownload(request):
	"""
	This is generate download file
	"""
	ip = get_ip(request, right_most_proxy=True)
	IpAddressInformation.objects.create(ip_address=ip)
	if request.method=='GET':
		resultJsonfilepath=request.GET.get('jsonfile').strip()
		fastaFileStatus=resultJsonfilepath.split('|')[1]
		resultJsonfileName=resultJsonfilepath.split('/')[-1].split('_')[0]
		downloadFilename='Results_'+resultJsonfileName+'_search.csv'
		downloadResultFilePath=os.path.join(settings.BASE_DIR, 'resultFile', 'downloadResult', 'search',  downloadFilename)
		homedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)
		fullresultfilePath=os.path.join(homedir, 'src/resultFile/jsonData/resultJson/search/downloadversion/',resultJsonfilepath.split('/')[-1].split('|')[0])
		with open(fullresultfilePath) as rjf:
			resultsJsonData=json.load(rjf)
			resultsJsonData=updateDataToDownload(resultsJsonData)
			df=pd.read_json(json.dumps(resultsJsonData))
			df.rename(columns ={'UniProtKB Accession':'Mouse UniProtKB accession','Protein':'Mouse Protein name',\
				'Gene':'Mouse Gene','Present in isoforms':'Peptide present in isoforms',\
				'Peptide Sequence':'Peptide sequence','Knockout':'Mutant',\
				'Unique in protein':'Peptide unique in proteome','Human UniProtKB Accession': \
				'UniProtKB accession of human ortholog','Human ProteinName': 'Human ortholog',\
				'Peptide ID':'Assay ID','Present in human isoforms':'Peptide present in human isoforms',\
				'Unique in human protein':'Peptide unique in human protein',\
				'SubCellular':'Subcellular localization','Mouse Kegg Pathway':'Molecular pathway(s) Mouse',\
				'Present in human ortholog':'Peptide present in human ortholog',\
				'Human Kegg Pathway':'Molecular pathway(s) Human','Human UniProt DiseaseData':'Involvement in disease-Human(UniProt)',\
				'Human DisGen DiseaseData':'Involvement in disease-Human(DisGeNET)','Human Drug Bank':\
				'Drug associations-Human','CZE Purity':'CZE','AAA Concentration':'AAA',\
				'Mouse Go':'GO Mouse','Human Go':'GO Human','LLOQ':'Assay LLOQ','ULOQ':'Assay ULOQ'}, inplace =True)
			if fastaFileStatus == 'NA':
				df.to_csv(downloadResultFilePath,index=False, encoding='utf-8',columns=downloadColName)
			if fastaFileStatus == 'Fasta':
				df.to_csv(downloadResultFilePath,index=False, encoding='utf-8',columns=downloadColNameUserSeq)
		
			response_data ={'downloadFileName':downloadFilename}

			return HttpResponse(json.dumps(response_data), content_type="application/json")<file_sep>/client/qmpkb-app/src/app/dropdown-service/dropdown.service.ts
import { Injectable } from '@angular/core';
import {Select} from '../dropdown-service/select';
import {Where} from '../dropdown-service/where';
import {QmpkbService} from '../qmpkb-service/qmpkb.service';



@Injectable({
  providedIn: 'root'
})
export class DropdownService {

  constructor(private _qmpkb:QmpkbService) {
  }

  getSelect(){
    return [
     new Select('Protein', 'protein' ),
     new Select('Gene', 'gene' ),
     new Select('UniProtKB accession', 'uniProtKBAccession'),
     new Select('Peptide sequence', 'pepSeq' ),
     new Select('Panel', 'panel' ),
     new Select('Strain', 'strain' ),
     new Select('Mutant', 'mutant'  ),
     new Select('Sex', 'sex'  ),
     new Select('Biological matrix', 'biologicalMatrix'  ),
     new Select('Subcellular localization', 'subCellLoc' ),
     new Select('Molecular pathway(s)', 'keggPathway' ),
     new Select('Involvement in disease', 'disCausMut' ),
     new Select('GO ID', 'goId' ),
     new Select('GO term', 'goTerm' ),
     new Select('GO aspects', 'goAspects' ),
     new Select('Drug associations ID', 'drugId' ),
     new Select('Own protein sequences in FASTA format', 'fastaFile'  )
    
    ];
  }
  getWhere(){
    return this._qmpkb.dropDownStorage;
  }
}<file_sep>/client/qmpkb-app/src/app/contact/contact.component.ts
import { Component, OnInit, HostListener } from '@angular/core';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
	contactForm: FormGroup;
	disabledSubmitButton: boolean = true;
	optionsSelect: Array<any>;

	@HostListener('input') oninput() {
		if (this.contactForm.valid) {
			this.disabledSubmitButton = false;
		}
	}
	constructor(
		private http: HttpClient,
		private fb: FormBuilder
		) {
		this.contactForm = fb.group({
			'contactFormName': ['', Validators.required],
			'contactFormEmail': ['', Validators.compose([Validators.required, Validators.email])],
			'contactFormMessage': ['', Validators.required],
			'contactFormCopy': [''],
		});
	}

	ngOnInit() { }

	onSubmit() {
		if (this.contactForm.valid) {
			alert('Your message has been sent.');
			this.http.get('/contactapi/?contactdetails=' + JSON.stringify(this.contactForm.value)).subscribe(response => {},errors => {console.log(errors)});
			this.contactForm.reset();
			this.disabledSubmitButton = true;
		}
	}

}