Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def recordParser(paper):
tagList = []
doneReading = False
l = (0, '')
for l in paper:
if len(l[1]) < 3:
#Line too short
raise BadWOSRecord("Missing field on line {} : {}".format(l[0], l[1]))
elif 'ER' in l[1][:2]:
... | [
"This is function that is used to create [Records](../classes/Record.html#metaknowledge.Record) from files.\n\n **recordParser**() reads the file _paper_ until it reaches 'ER'. For each field tag it adds an entry to the returned dict with the tag as the key and a list of the entries as the value, the list has ea... |
Please provide a description of the function:def writeRecord(self, infile):
if self.bad:
raise BadWOSRecord("This record cannot be converted to a file as the input was malformed.\nThe original line number (if any) is: {} and the original file is: '{}'".format(self._sourceLine, self._sourceF... | [
"Writes to _infile_ the original contents of the Record. This is intended for use by [RecordCollections](./RecordCollection.html#metaknowledge.RecordCollection) to write to file. What is written to _infile_ is bit for bit identical to the original record file (if utf-8 is used). No newline is inserted above the wri... |
Please provide a description of the function:def getInstitutions(self, tags = None, seperator = ";", _getTag = False):
if tags is None:
tags = []
elif isinstance(tags, str):
tags = [tags]
for k in self.keys():
if 'institution' in k.lower() and k not i... | [
"Returns a list with the names of the institution. The optional arguments are ignored\n\n # Returns\n\n `list [str]`\n\n > A list with 1 entry the name of the institution\n "
] |
Please provide a description of the function:def medlineRecordParser(record):
tagDict = collections.OrderedDict()
tag = 'PMID'
mostRecentAuthor = None
for lineNum, line in record:
tmptag = line[:4].rstrip()
contents = line[6:-1]
if tmptag.isalpha() and line[4] == '-':
... | [
"The parser [`MedlineRecord`](../classes/MedlineRecord.html#metaknowledge.medline.MedlineRecord) use. This takes an entry from [medlineParser()](#metaknowledge.medline.medlineHandlers.medlineParser) and parses it a part of the creation of a `MedlineRecord`.\n\n # Parameters\n\n _record_ : `enumerate object`\n... |
Please provide a description of the function:def writeRecord(self, f):
if self.bad:
raise BadPubmedRecord("This record cannot be converted to a file as the input was malformed.\nThe original line number (if any) is: {} and the original file is: '{}'".format(self._sourceLine, self._sourceFil... | [
"This is nearly identical to the original the FAU tag is the only tag not writen in the same place, doing so would require changing the parser and lots of extra logic.\n "
] |
Please provide a description of the function:def quickVisual(G, showLabel = False):
colours = "brcmykwg"
f = plt.figure(1)
ax = f.add_subplot(1,1,1)
ndTypes = []
ndColours = []
layout = nx.spring_layout(G, k = 4 / math.sqrt(len(G.nodes())))
for nd in G.nodes(data = True):
if 'ty... | [
"Just makes a simple _matplotlib_ figure and displays it, with each node coloured by its type. You can add labels with _showLabel_. This looks a bit nicer than the one provided my _networkx_'s defaults.\n\n # Parameters\n\n _showLabel_ : `optional [bool]`\n\n > Default `False`, if `True` labels will be add... |
Please provide a description of the function:def graphDensityContourPlot(G, iters = 50, layout = None, layoutScaleFactor = 1, overlay = False, nodeSize = 10, axisSamples = 100, blurringFactor = .1, contours = 15, graphType = 'coloured'):
from mpl_toolkits.mplot3d import Axes3D
if not isinstance(G, nx.clas... | [
"Creates a 3D plot giving the density of nodes on a 2D plane, as a surface in 3D.\n\n Most of the options are for tweaking the final appearance. _layout_ and _layoutScaleFactor_ allow a pre-layout graph to be provided. If a layout is not provided the [networkx.spring_layout()](https://networkx.github.io/document... |
Please provide a description of the function:def getMonth(s):
monthOrSeason = s.split('-')[0].upper()
if monthOrSeason in monthDict:
return monthDict[monthOrSeason]
else:
monthOrSeason = s.split('-')[1].upper()
if monthOrSeason.isdigit():
return monthOrSeason
... | [
"\n Known formats:\n Month (\"%b\")\n Month Day (\"%b %d\")\n Month-Month (\"%b-%b\") --- this gets coerced to the first %b, dropping the month range\n Season (\"%s\") --- this gets coerced to use the first month of the given season\n Month Day Year (\"%b %d %Y\")\n Month Year (\"%b %Y\")\n ... |
Please provide a description of the function:def makeBiDirectional(d):
dTmp = d.copy()
for k in d:
dTmp[d[k]] = k
return dTmp | [
"\n Helper for generating tagNameConverter\n Makes dict that maps from key to value and back\n "
] |
Please provide a description of the function:def reverseDict(d):
retD = {}
for k in d:
retD[d[k]] = k
return retD | [
"\n Helper for generating fullToTag\n Makes dict of value to key\n "
] |
Please provide a description of the function:def proQuestRecordParser(enRecordFile, recNum):
tagDict = collections.OrderedDict()
currentEntry = 'Name'
while True:
lineNum, line = next(enRecordFile)
if line == '_' * 60 + '\n':
break
elif line == '\n':
pass... | [
"The parser [ProQuestRecords](../classes/ProQuestRecord.html#metaknowledge.proquest.ProQuestRecord) use. This takes an entry from [proQuestParser()](#metaknowledge.proquest.proQuestHandlers.proQuestParser) and parses it a part of the creation of a `ProQuestRecord`.\n\n # Parameters\n\n _enRecordFile_ : `enume... |
Please provide a description of the function:def addToNetwork(grph, nds, count, weighted, nodeType, nodeInfo, fullInfo, coreCitesDict, coreValues, detailedValues, addCR, recordToCite = True, headNd = None):
if headNd is not None:
hID = makeID(headNd, nodeType)
if nodeType == 'full' or nodeType ... | [
"Addeds the citations _nds_ to _grph_, according to the rules give by _nodeType_, _fullInfo_, etc.\n\n _headNd_ is the citation of the Record\n "
] |
Please provide a description of the function:def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR):
d = {}
if nodeInfo:
if nodeType == 'full':
if coreValues:
if citation in coreCitesDict:
... | [
"Makes a tuple of idVal and a dict of the selected attributes"
] |
Please provide a description of the function:def expandRecs(G, RecCollect, nodeType, weighted):
for Rec in RecCollect:
fullCiteList = [makeID(c, nodeType) for c in Rec.createCitation(multiCite = True)]
if len(fullCiteList) > 1:
for i, citeID1 in enumerate(fullCiteList):
... | [
"Expand all the citations from _RecCollect_"
] |
Please provide a description of the function:def dropNonJournals(self, ptVal = 'J', dropBad = True, invert = False):
if dropBad:
self.dropBadEntries()
if invert:
self._collection = {r for r in self._collection if r['pubType'] != ptVal.upper()}
else:
s... | [
"Drops the non journal type `Records` from the collection, this is done by checking _ptVal_ against the PT tag\n\n # Parameters\n\n _ptVal_ : `optional [str]`\n\n > Default `'J'`, The value of the PT tag to be kept, default is `'J'` the journal tag, other tags can be substituted.\n\n _dr... |
Please provide a description of the function:def writeFile(self, fname = None):
if len(self._collectedTypes) < 2:
recEncoding = self.peek().encoding()
else:
recEncoding = 'utf-8'
if fname:
f = open(fname, mode = 'w', encoding = recEncoding)
el... | [
"Writes the `RecordCollection` to a file, the written file's format is identical to those download from WOS. The order of `Records` written is random.\n\n # Parameters\n\n _fname_ : `optional [str]`\n\n > Default `None`, if given the output file will written to _fanme_, if `None` the `RecordCol... |
Please provide a description of the function:def writeCSV(self, fname = None, splitByTag = None, onlyTheseTags = None, numAuthors = True, genderCounts = True, longNames = False, firstTags = None, csvDelimiter = ',', csvQuote = '"', listDelimiter = '|'):
if firstTags is None:
firstTags = ['i... | [
"Writes all the `Records` from the collection into a csv file with each row a record and each column a tag.\n\n # Parameters\n\n _fname_ : `optional [str]`\n\n > Default `None`, the name of the file to write to, if `None` it uses the collections name suffixed by .csv.\n\n _splitByTag_ : ... |
Please provide a description of the function:def writeBib(self, fname = None, maxStringLength = 1000, wosMode = False, reducedOutput = False, niceIDs = True):
if fname:
f = open(fname, mode = 'w', encoding = 'utf-8')
else:
f = open(self.name[:200] + '.bib', mode = 'w', e... | [
"Writes a bibTex entry to _fname_ for each `Record` in the collection.\n\n If the Record is of a journal article (PT J) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number and all the Record's fields are given as entries with their long names.\n\n ... |
Please provide a description of the function:def findProbableCopyright(self):
retCopyrights = set()
for R in self:
begin, abS = findCopyright(R.get('abstract', ''))
if abS != '':
retCopyrights.add(abS)
return list(retCopyrights) | [
"Finds the (likely) copyright string from all abstracts in the `RecordCollection`\n\n # Returns\n\n `list[str]`\n\n > A deduplicated list of all the copyright strings\n "
] |
Please provide a description of the function:def forBurst(self, tag, outputFile = None, dropList = None, lower = True, removeNumbers = True, removeNonWords = True, removeWhitespace = True, stemmer = None):
whiteSpaceRegex = re.compile(r'\s+')
if removeNumbers:
if removeNonWords:
... | [
"Creates a pandas friendly dictionary with 2 columns one `'year'` and the other `'word'`. Each row is a word that occurred in the field given by _tag_ in a `Record` and the year of the record. Unfortunately getting the month or day with any type of accuracy has proved to be impossible so year is the only option.\n\... |
Please provide a description of the function:def forNLP(self, outputFile = None, extraColumns = None, dropList = None, lower = True, removeNumbers = True, removeNonWords = True, removeWhitespace = True, removeCopyright = False, stemmer = None):
whiteSpaceRegex = re.compile(r'\s+')
if removeNum... | [
"Creates a pandas friendly dictionary with each row a `Record` in the `RecordCollection` and the columns fields natural language processing uses (id, title, publication year, keywords and the abstract). The abstract is by default is processed to remove non-word, non-space characters and the case is lowered.\n\n ... |
Please provide a description of the function:def makeDict(self, onlyTheseTags = None, longNames = False, raw = False, numAuthors = True, genderCounts = True):
if onlyTheseTags:
for i in range(len(onlyTheseTags)):
if onlyTheseTags[i] in fullToTagDict:
only... | [
"Returns a dict with each key a tag and the values being lists of the values for each of the Records in the collection, `None` is given when there is no value and they are in the same order across each tag.\n\n When used with pandas: `pandas.DataFrame(RC.makeDict())` returns a data frame with each column a t... |
Please provide a description of the function:def rpys(self, minYear = None, maxYear = None, dropYears = None, rankEmptyYears = False):
def deviation(targetYear, targetValue, targetDict):
yearCounts = [targetValue]
for deltaY in [-2, -1, 1, 2]:
try:
... | [
"This implements _Referenced Publication Years Spectroscopy_ a techinique for finding import years in citation data. The authors of the original papers have a website with more information, found [here](http://www.leydesdorff.net/software/rpys/).\n\n This function computes the spectra of the `RecordCollectio... |
Please provide a description of the function:def genderStats(self, asFractions = False):
maleCount = 0
femaleCount = 0
unknownCount = 0
for R in self:
m, f, u = R.authGenders(_countsTuple = True)
maleCount += m
femaleCount += f
un... | [
"Creates a dict (`{'Male' : maleCount, 'Female' : femaleCount, 'Unknown' : unknownCount}`) with the numbers of male, female and unknown names in the collection.\n\n # Parameters\n\n _asFractions_ : `optional bool`\n\n > Default `False`, if `True` the counts will be divided by the total number o... |
Please provide a description of the function:def getCitations(self, field = None, values = None, pandasFriendly = True, counts = True):
retCites = []
if values is not None:
if isinstance(values, (str, int, float)) or not isinstance(values, collections.abc.Container):
... | [
"Creates a pandas ready dict with each row a different citation the contained Records and columns containing the original string, year, journal, author's name and the number of times it occured.\n\n There are also options to filter the output citations with _field_ and _values_\n\n # Parameters\n\n ... |
Please provide a description of the function:def networkCoAuthor(self, detailedInfo = False, weighted = True, dropNonJournals = False, count = True, useShortNames = False, citeProfile = False):
grph = nx.Graph()
pcount = 0
progArgs = (0, "Starting to make a co-authorship network")
... | [
"Creates a coauthorship network for the RecordCollection.\n\n # Parameters\n\n _detailedInfo_ : `optional [bool or iterable[WOS tag Strings]]`\n\n > Default `False`, if `True` all nodes will be given info strings composed of information from the Record objects themselves. This is Equivalent to ... |
Please provide a description of the function:def networkCoCitation(self, dropAnon = True, nodeType = "full", nodeInfo = True, fullInfo = False, weighted = True, dropNonJournals = False, count = True, keyWords = None, detailedCore = True, detailedCoreAttributes = False, coreOnly = False, expandedCore = False, addCR = Fa... | [
"Creates a co-citation network for the RecordCollection.\n\n # Parameters\n\n _nodeType_ : `optional [str]`\n\n > One of `\"full\"`, `\"original\"`, `\"author\"`, `\"journal\"` or `\"year\"`. Specifies the value of the nodes in the graph. The default `\"full\"` causes the citations to be compar... |
Please provide a description of the function:def networkBibCoupling(self, weighted = True, fullInfo = False, addCR = False):
progArgs = (0, "Make a citation network for coupling")
if metaknowledge.VERBOSE_MODE:
progKwargs = {'dummy' : False}
else:
progKwargs = {'... | [
"Creates a bibliographic coupling network based on citations for the RecordCollection.\n\n # Parameters\n\n _weighted_ : `optional bool`\n\n > Default `True`, if `True` the weight of the edges will be added to the network\n\n _fullInfo_ : `optional bool`\n\n > Default `False`, if ... |
Please provide a description of the function:def yearSplit(self, startYear, endYear, dropMissingYears = True):
recordsInRange = set()
for R in self:
try:
if R.get('year') >= startYear and R.get('year') <= endYear:
recordsInRange.add(R)
... | [
"Creates a RecordCollection of Records from the years between _startYear_ and _endYear_ inclusive.\n\n # Parameters\n\n _startYear_ : `int`\n\n > The smallest year to be included in the returned RecordCollection\n\n _endYear_ : `int`\n\n > The largest year to be included in the re... |
Please provide a description of the function:def localCiteStats(self, pandasFriendly = False, keyType = "citation"):
count = 0
recCount = len(self)
progArgs = (0, "Starting to get the local stats on {}s.".format(keyType))
if metaknowledge.VERBOSE_MODE:
progKwargs = {... | [
"Returns a dict with all the citations in the CR field as keys and the number of times they occur as the values\n\n # Parameters\n\n _pandasFriendly_ : `optional [bool]`\n\n > default `False`, makes the output be a dict with two keys one `'Citations'` is the citations the other is their occurre... |
Please provide a description of the function:def localCitesOf(self, rec):
localCites = []
if isinstance(rec, Record):
recCite = rec.createCitation()
if isinstance(rec, str):
try:
recCite = self.getID(rec)
except ValueError:
... | [
"Takes in a Record, WOS string, citation string or Citation and returns a RecordCollection of all records that cite it.\n\n # Parameters\n\n _rec_ : `Record, str or Citation`\n\n > The object that is being cited\n\n # Returns\n\n `RecordCollection`\n\n > A `RecordCollection... |
Please provide a description of the function:def citeFilter(self, keyString = '', field = 'all', reverse = False, caseSensitive = False):
retRecs = []
keyString = str(keyString)
for R in self:
try:
if field == 'all':
for cite in R.get('cit... | [
"Filters `Records` by some string, _keyString_, in their citations and returns all `Records` with at least one citation possessing _keyString_ in the field given by _field_.\n\n # Parameters\n\n _keyString_ : `optional [str]`\n\n > Default `''`, gives the string to be searched for, if it is is ... |
Please provide a description of the function:def filterNonJournals(citesLst, invert = False):
retCites = []
for c in citesLst:
if c.isJournal():
if not invert:
retCites.append(c)
elif invert:
retCites.append(c)
return retCites | [
"Removes the `Citations` from _citesLst_ that are not journals\n\n # Parameters\n\n _citesLst_ : `list [Citation]`\n\n > A list of citations to be filtered\n\n _invert_ : `optional [bool]`\n\n > Default `False`, if `True` non-journals will be kept instead of journals\n\n # Returns\n\n `list [Ci... |
Please provide a description of the function:def allButDOI(self):
extraTags = ['extraAuthors', 'V', 'issue', 'P', 'misc']
s = self.ID()
extras = []
for tag in extraTags:
if getattr(self, tag, False):
extras.append(str(getattr(self, tag)))
if l... | [
"\n Returns a string of the normalized values from the Citation excluding the DOI number. Equivalent to getting the ID with [ID()](#metaknowledge.citation.Citation.ID) then appending the extra values from [Extra()](#metaknowledge.citation.Citation.Extra) and then removing the substring containing the DOI num... |
Please provide a description of the function:def Extra(self):
extraTags = ['V', 'P', 'DOI', 'misc']
retVal = ""
for tag in extraTags:
if getattr(self, tag):
retVal += getattr(self, tag) + ', '
if len(retVal) > 2:
return retVal[:-2]
... | [
"\n Returns any `V`, `P`, `DOI` or `misc` values as a string. These are all the values not returned by [ID()](#metaknowledge.citation.Citation.ID), they are separated by `' ,'`.\n\n # Returns\n\n `str`\n\n > A string containing the data not in the ID of the `Citation`.\n "
] |
Please provide a description of the function:def isJournal(self, dbname = abrevDBname, manualDB = manualDBname, returnDict ='both', checkIfExcluded = False):
global abbrevDict
if abbrevDict is None:
abbrevDict = getj9dict(dbname = dbname, manualDB = manualDB, returnDict = returnDict... | [
"Returns `True` if the `Citation`'s `journal` field is a journal abbreviation from the WOS listing found at [http://images.webofknowledge.com/WOK46/help/WOS/A_abrvjt.html](http://images.webofknowledge.com/WOK46/help/WOS/A_abrvjt.html), i.e. checks if the citation is citing a journal.\n\n **Note**: Requires t... |
Please provide a description of the function:def FullJournalName(self):
global abbrevDict
if abbrevDict is None:
abbrevDict = getj9dict()
if self.isJournal():
return abbrevDict[self.journal][0]
else:
return None | [
"Returns the full name of the Citation's journal field. Requires the [j9Abbreviations](../modules/journalAbbreviations.html#metaknowledge.journalAbbreviations.backend.getj9dict) database file.\n\n **Note**: Requires the [j9Abbreviations](../modules/journalAbbreviations.html#metaknowledge.journalAbbreviations... |
Please provide a description of the function:def addToDB(self, manualName = None, manualDB = manualDBname, invert = False):
try:
if invert:
d = {self.journal : ''}
elif manualName is None:
d = {self.journal : self.journal}
else:
... | [
"Adds the journal of this Citation to the user created database of journals. This will cause [isJournal()](#metaknowledge.citation.Citation.isJournal) to return `True` for this Citation and all others with its `journal`.\n\n **Note**: Requires the [j9Abbreviations](../modules/journalAbbreviations.html#metakn... |
Please provide a description of the function:def add(self, elem):
if isinstance(elem, self._allowedTypes):
self._collection.add(elem)
self._collectedTypes.add(type(elem).__name__)
else:
raise CollectionTypeError("{} can only contain '{}', '{}' is not allowed.... | [
" Adds _elem_ to the collection.\n\n # Parameters\n\n _elem_ : `object`\n\n > The object to be added\n "
] |
Please provide a description of the function:def remove(self, elem):
try:
return self._collection.remove(elem)
except KeyError:
raise KeyError("'{}' was not found in the {}: '{}'.".format(elem, type(self).__name__, self)) from None | [
"Removes _elem_ from the collection, will raise a KeyError is _elem_ is missing\n\n # Parameters\n\n _elem_ : `object`\n\n > The object to be removed\n "
] |
Please provide a description of the function:def clear(self):
self.bad = False
self.errors = {}
self._collection.clear() | [
"\"Removes all elements from the collection and resets the error handling\n "
] |
Please provide a description of the function:def pop(self):
try:
return self._collection.pop()
except KeyError:
raise KeyError("Nothing left in the {}: '{}'.".format(type(self).__name__, self)) from None | [
"Removes a random element from the collection and returns it\n\n # Returns\n\n `object`\n\n > A random object from the collection\n "
] |
Please provide a description of the function:def copy(self):
collectedCopy = copy.copy(self)
collectedCopy._collection = copy.copy(collectedCopy._collection)
self._collectedTypes = copy.copy(self._collectedTypes)
self._allowedTypes = copy.copy(self._allowedTypes)
collect... | [
"Creates a shallow copy of the collection\n\n # Returns\n\n `Collection`\n\n > A copy of the `Collection`\n "
] |
Please provide a description of the function:def chunk(self, maxSize):
chunks = []
currentSize = maxSize + 1
for i in self:
if currentSize >= maxSize:
currentSize = 0
chunks.append(type(self)({i}, name = 'Chunk-{}-of-{}'.format(len(chunks), se... | [
"Splits the `Collection` into _maxSize_ size or smaller `Collections`\n\n # Parameters\n\n _maxSize_ : `int`\n\n > The maximum number of elements in a retuned `Collection`\n\n\n # Returns\n\n `list [Collection]`\n\n > A list of `Collections` that if all merged (`|` operator... |
Please provide a description of the function:def split(self, maxSize):
chunks = []
currentSize = maxSize + 1
try:
while True:
if currentSize >= maxSize:
currentSize = 0
chunks.append(type(self)({self.pop()}, name = 'Chu... | [
"Destructively, splits the `Collection` into _maxSize_ size or smaller `Collections`. The source `Collection` will be empty after this operation\n\n # Parameters\n\n _maxSize_ : `int`\n\n > The maximum number of elements in a retuned `Collection`\n\n # Returns\n\n `list [Collectio... |
Please provide a description of the function:def containsID(self, idVal):
for i in self:
if i.id == idVal:
return True
return False | [
"Checks if the collected items contains the give _idVal_\n\n # Parameters\n\n _idVal_ : `str`\n\n > The queried id string\n\n # Returns\n\n `bool`\n\n > `True` if the item is in the collection\n "
] |
Please provide a description of the function:def discardID(self, idVal):
for i in self:
if i.id == idVal:
self._collection.discard(i)
return | [
"Checks if the collected items contains the give _idVal_ and discards it if it is found, will not raise an exception if item is not found\n\n # Parameters\n\n _idVal_ : `str`\n\n > The discarded id string\n "
] |
Please provide a description of the function:def removeID(self, idVal):
for i in self:
if i.id == idVal:
self._collection.remove(i)
return
raise KeyError("A Record with the ID '{}' was not found in the RecordCollection: '{}'.".format(idVal, self)) | [
"Checks if the collected items contains the give _idVal_ and removes it if it is found, will raise a `KeyError` if item is not found\n\n # Parameters\n\n _idVal_ : `str`\n\n > The removed id string\n "
] |
Please provide a description of the function:def badEntries(self):
badEntries = set()
for i in self:
if i.bad:
badEntries.add(i)
return type(self)(badEntries, quietStart = True) | [
"Creates a new collection of the same type with only the bad entries\n\n # Returns\n\n `CollectionWithIDs`\n\n > A collection of only the bad entries\n "
] |
Please provide a description of the function:def dropBadEntries(self):
self._collection = set((i for i in self if not i.bad))
self.bad = False
self.errors = {} | [
"Removes all the bad entries from the collection\n "
] |
Please provide a description of the function:def tags(self):
tags = set()
for i in self:
tags |= set(i.keys())
return tags | [
"Creates a list of all the tags of the contained items\n\n # Returns\n\n `list [str]`\n\n > A list of all the tags\n "
] |
Please provide a description of the function:def glimpse(self, *tags, compact = False):
return _glimpse(self, *tags, compact = compact) | [
"Creates a printable table with the most frequently occurring values of each of the requested _tags_, or if none are provided the top authors, journals and citations. The table will be as wide and as tall as the terminal (or 80x24 if there is no terminal) so `print(RC.glimpse())`should always create a nice looking ... |
Please provide a description of the function:def rankedSeries(self, tag, outputFile = None, giveCounts = True, giveRanks = False, greatestFirst = True, pandasMode = True, limitTo = None):
if giveRanks and giveCounts:
raise mkException("rankedSeries cannot return counts and ranks only one of... | [
"Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by their number of occurrences. A list can also be returned with the the counts or ranks added or it can be written to a file.\n\n # Parameters\n\n _tag_ : `str`\n\n > The tag to be ranked\n\n _output... |
Please provide a description of the function:def timeSeries(self, tag = None, outputFile = None, giveYears = True, greatestFirst = True, limitTo = False, pandasMode = True):
seriesDict = {}
for R in self:
#This should be faster than using get, since get is a wrapper for __getitem__
... | [
"Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list can also be returned with the the counts or years added or it can be written to a file.\n\n If no _tag_ is given the `Records` in... |
Please provide a description of the function:def cooccurrenceCounts(self, keyTag, *countedTags):
if not isinstance(keyTag, str):
raise TagError("'{}' is not a string it cannot be used as a tag.".format(keyTag))
if len(countedTags) < 1:
TagError("You need to provide atlea... | [
"Counts the number of times values from any of the _countedTags_ occurs with _keyTag_. The counts are retuned as a dictionary with the values of _keyTag_ mapping to dictionaries with each of the _countedTags_ values mapping to thier counts.\n\n # Parameters\n\n _keyTag_ : `str`\n\n > The tag us... |
Please provide a description of the function:def networkMultiLevel(self, *modes, nodeCount = True, edgeWeight = True, stemmer = None, edgeAttribute = None, nodeAttribute = None, _networkTypeString = 'n-level network'):
stemCheck = False
if stemmer is not None:
if isinstance(stemmer,... | [
"Creates a network of the objects found by any number of tags _modes_, with edges between all co-occurring values. IF you only want edges between co-occurring values from different tags use [networkMultiMode()](#metaknowledge.CollectionWithIDs.networkMultiMode).\n\n A **networkMultiLevel**() looks are each e... |
Please provide a description of the function:def networkOneMode(self, mode, nodeCount = True, edgeWeight = True, stemmer = None, edgeAttribute = None, nodeAttribute = None):
return self.networkMultiLevel(mode, nodeCount = nodeCount, edgeWeight = edgeWeight, stemmer = stemmer, edgeAttribute = edgeAttrib... | [
"Creates a network of the objects found by one tag _mode_. This is the same as [networkMultiLevel()](#metaknowledge.CollectionWithIDs.networkMultiLevel) with only one tag.\n\n A **networkOneMode**() looks are each entry in the collection and extracts its values for the tag given by _mode_, e.g. the `'authors... |
Please provide a description of the function:def networkTwoMode(self, tag1, tag2, directed = False, recordType = True, nodeCount = True, edgeWeight = True, stemmerTag1 = None, stemmerTag2 = None, edgeAttribute = None):
if not isinstance(tag1, str):
raise TagError("{} is not a string it cann... | [
"Creates a network of the objects found by two WOS tags _tag1_ and _tag2_, each node marked by which tag spawned it making the resultant graph bipartite.\n\n A **networkTwoMode()** looks at each Record in the `RecordCollection` and extracts its values for the tags given by _tag1_ and _tag2_, e.g. the `'WC'` ... |
Please provide a description of the function:def networkMultiMode(self, *tags, recordType = True, nodeCount = True, edgeWeight = True, stemmer = None, edgeAttribute = None):
if len(tags) == 1:
if not isinstance(tags[0], str):
try:
tags = list(tags[0])
... | [
"Creates a network of the objects found by all tags in _tags_, each node is marked by which tag spawned it making the resultant graph n-partite.\n\n A **networkMultiMode()** looks are each item in the collection and extracts its values for the tags given by _tags_. Then for all objects returned an edge is cr... |
Please provide a description of the function:def diffusionGraph(source, target, weighted = True, sourceType = "raw", targetType = "raw", labelEdgesBy = None):
if sourceType != "raw" and sourceType not in tagsAndNameSet:
raise RuntimeError("{} is not a valid node type, only 'raw' or those strings in tag... | [
"Takes in two [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) and produces a graph of the citations of _source_ by the [Records](../classes/Record.html#metaknowledge.Record) in _target_. By default the nodes in the are `Record` objects but this can be changed with the _sourceTyp... |
Please provide a description of the function:def diffusionCount(source, target, sourceType = "raw", extraValue = None, pandasFriendly = False, compareCounts = False, numAuthors = True, useAllAuthors = True, _ProgBar = None, extraMapping = None):
sourceCountString = "SourceCount"
targetCountString = "Targe... | [
"Takes in two [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) and produces a `dict` counting the citations of _source_ by the [Records](../classes/Record.html#metaknowledge.Record) of _target_. By default the `dict` uses `Record` objects as keys but this can be changed with the ... |
Please provide a description of the function:def makeNodeID(Rec, ndType, extras = None):
if ndType == 'raw':
recID = Rec
else:
recID = Rec.get(ndType)
if recID is None:
pass
elif isinstance(recID, list):
recID = tuple(recID)
else:
recID = recID
extraD... | [
"Helper to make a node ID, extras is currently not used"
] |
Please provide a description of the function:def diffusionAddCountsFromSource(grph, source, target, nodeType = 'citations', extraType = None, diffusionLabel = 'DiffusionCount', extraKeys = None, countsDict = None, extraMapping = None):
progArgs = (0, "Starting to add counts to graph")
if metaknowledge.VERB... | [
"Does a diffusion using [diffusionCount()](#metaknowledge.diffusion.diffusionCount) and updates _grph_ with it, using the nodes in the graph as keys in the diffusion, i.e. the source. The name of the attribute the counts are added to is given by _diffusionLabel_. If the graph is not composed of citations from the s... |
Please provide a description of the function:def pandoc_process(app, what, name, obj, options, lines):
if not lines:
return None
input_format = app.config.mkdsupport_use_parser
output_format = 'rst'
# Since default encoding for sphinx.ext.autodoc is unicode and pypandoc.convert_text, whi... | [
"\"Convert docstrings in Markdown into reStructureText using pandoc\n "
] |
Please provide a description of the function:def beginningPage(R):
p = R['PG']
if p.startswith('suppl '):
p = p[6:]
return p.split(' ')[0].split('-')[0].replace(';', '') | [
"As pages may not be given as numbers this is the most accurate this function can be"
] |
Please provide a description of the function:def _bibFormatter(s, maxLength):
if isinstance(s, list):
s = ' and '.join((str(v) for v in s))
elif not isinstance(s, str):
s = str(s)
if len(s) > maxLength:
s = s.replace('"', '')
s = [s[i * maxLength: (i + 1) * maxLength] fo... | [
"Formats a string, list or number to make it good for a bib file by:\n * if too long splits up the string correctly\n * tries to use the best quoting characters\n * expands lists into ' and ' seperated values, as per spec for authors field\n Note, this does not escape characters. LaTeX may h... |
Please provide a description of the function:def copy(self):
c = copy.copy(self)
c._fieldDict = c._fieldDict.copy()
return c | [
"Correctly copies the `Record`\n\n # Returns\n\n `Record`\n\n > A completely decoupled copy of the original\n "
] |
Please provide a description of the function:def get(self, tag, default = None, raw = False):
if raw:
if tag in self._fieldDict:
return self._fieldDict[tag]
elif self.getAltName(tag) in self._fieldDict:
return self._fieldDict[self.getAltName(tag)]... | [
"Allows access to the raw values or is an Exception safe wrapper to `__getitem__`.\n\n # Parameters\n\n _tag_ : `str`\n\n > The requested tag\n\n _default_ : `optional [Object]`\n\n > Default `None`, the object returned when _tag_ is not found\n\n _raw_ : `optional [bool]`\... |
Please provide a description of the function:def values(self, raw = False):
if raw:
return self._fieldDict.values()
else:
return collections.abc.Mapping.values(self) | [
"Like `values` for dicts but with a `raw` option\n\n # Parameters\n\n _raw_ : `optional [bool]`\n\n > Default `False`, if `True` the `ValuesView` contains the raw values\n\n # Returns\n\n `ValuesView`\n\n > The values of the record\n "
] |
Please provide a description of the function:def items(self, raw = False):
if raw:
return self._fieldDict.items()
else:
return collections.abc.Mapping.items(self) | [
"Like `items` for dicts but with a `raw` option\n\n # Parameters\n\n _raw_ : `optional [bool]`\n\n > Default `False`, if `True` the `KeysView` contains the raw values as the values\n\n # Returns\n\n `KeysView`\n\n > The key-value pairs of the record\n "
] |
Please provide a description of the function:def getCitations(self, field = None, values = None, pandasFriendly = True):
retCites = []
if values is not None:
if isinstance(values, (str, int, float)) or not isinstance(values, collections.abc.Container):
values = [valu... | [
"Creates a pandas ready dict with each row a different citation and columns containing the original string, year, journal and author's name.\n\n There are also options to filter the output citations with _field_ and _values_\n\n # Parameters\n\n _field_ : `optional str`\n\n > Default `No... |
Please provide a description of the function:def subDict(self, tags, raw = False):
retDict = {}
for tag in tags:
retDict[tag] = self.get(tag, raw = raw)
return retDict | [
"Creates a dict of values of _tags_ from the Record. The tags are the keys and the values are the values. If the tag is missing the value will be `None`.\n\n # Parameters\n\n _tags_ : `list[str]`\n\n > The list of tags requested\n\n _raw_ : `optional [bool]`\n\n >default `False` i... |
Please provide a description of the function:def createCitation(self, multiCite = False):
#Need to put the import here to avoid circular import issues
from .citation import Citation
valsLst = []
if multiCite:
auths = []
for auth in self.get("authorsShort"... | [
"Creates a citation string, using the same format as other WOS citations, for the [Record](./Record.html#metaknowledge.Record) by reading the relevant special tags (`'year'`, `'J9'`, `'volume'`, `'beginningPage'`, `'DOI'`) and using it to create a [Citation](./Citation.html#metaknowledge.citation.Citation) object.\... |
Please provide a description of the function:def authGenders(self, countsOnly = False, fractionsMode = False, _countsTuple = False):
authDict = recordGenders(self)
if _countsTuple or countsOnly or fractionsMode:
rawList = list(authDict.values())
countsList = []
... | [
"Creates a dict mapping `'Male'`, `'Female'` and `'Unknown'` to lists of the names of all the authors.\n\n # Parameters\n\n _countsOnly_ : `optional bool`\n\n > Default `False`, if `True` the counts (lengths of the lists) will be given instead of the lists of names\n\n _fractionsMode_ : ... |
Please provide a description of the function:def bibString(self, maxLength = 1000, WOSMode = False, restrictedOutput = False, niceID = True):
keyEntries = []
if self.bad:
raise BadRecord("This record cannot be converted to a bibtex entry as the input was malformed.\nThe original lin... | [
"Makes a string giving the Record as a bibTex entry. If the Record is of a journal article (`PT J`) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number and all the Record's fields are given as entries with their long names.\n\n **Note** This is not m... |
Please provide a description of the function:def proQuestParser(proFile):
#assumes the file is ProQuest
nameDict = {}
recSet = set()
error = None
lineNum = 0
try:
with open(proFile, 'r', encoding = 'utf-8') as openfile:
f = enumerate(openfile, start = 1)
for ... | [
"Parses a ProQuest file, _proFile_, to extract the individual entries.\n\n A ProQuest file has three sections, first a list of the contained entries, second the full metadata and finally a bibtex formatted entry for the record. This parser only uses the first two as the bibtex contains no information the second ... |
Please provide a description of the function:def getInvestigators(self, tags = None, seperator = ";", _getTag = False):
if tags is None:
tags = ['Investigator']
elif isinstance(tags, str):
tags = ['Investigator', tags]
else:
tags.append('Investigator'... | [
"Returns a list of the names of investigators. The optional arguments are ignored.\n\n # Returns\n\n `list [str]`\n\n > A list of all the found investigator's names\n "
] |
Please provide a description of the function:def medlineParser(pubFile):
#assumes the file is MEDLINE
recSet = set()
error = None
lineNum = 0
try:
with open(pubFile, 'r', encoding = 'latin-1') as openfile:
f = enumerate(openfile, start = 1)
lineNum, line = next(f... | [
"Parses a medline file, _pubFile_, to extract the individual entries as [MedlineRecords](#metaknowledge.medline.recordMedline.MedlineRecord).\n\n A medline file is a series of entries, each entry is a series of tags. A tag is a 2 to 4 character string each tag is padded with spaces on the left to make it 4 chara... |
Please provide a description of the function:def nameStringGender(s, noExcept = False):
global mappingDict
try:
first = s.split(', ')[1].split(' ')[0].title()
except IndexError:
if noExcept:
return 'Unknown'
else:
return GenderException("The given String:... | [
"Expects `first, last`"
] |
Please provide a description of the function:def j9urlGenerator(nameDict = False):
start = "https://images.webofknowledge.com/images/help/WOS/"
end = "_abrvjt.html"
if nameDict:
urls = {"0-9" : start + "0-9" + end}
for c in string.ascii_uppercase:
urls[c] = start + c + end
... | [
"How to get all the urls for the WOS Journal Title Abbreviations. Each is varies by only a few characters. These are the currently in use urls they may change.\n\n They are of the form:\n\n > \"https://images.webofknowledge.com/images/help/WOS/{VAL}_abrvjt.html\"\n > Where {VAL} is a capital letter or the ... |
Please provide a description of the function:def _j9SaveCurrent(sDir = '.'):
dname = os.path.normpath(sDir + '/' + datetime.datetime.now().strftime("%Y-%m-%d_J9_AbbreviationDocs"))
if not os.path.isdir(dname):
os.mkdir(dname)
os.chdir(dname)
else:
os.chdir(dname)
for urlID,... | [
"Downloads and saves all the webpages\n\n For Backend\n "
] |
Please provide a description of the function:def _getDict(j9Page):
slines = j9Page.read().decode('utf-8').split('\n')
while slines.pop(0) != "<DL>":
pass
currentName = slines.pop(0).split('"></A><DT>')[1]
currentTag = slines.pop(0).split("<B><DD>\t")[1]
j9Dict = {}
while True:
... | [
"Parses a Journal Title Abbreviations page\n\n Note the pages are not well formatted html as the <DT> tags are not closes so html parses (Beautiful Soup) do not work. This is a simple parser that only works on the webpages and may fail if they are changed\n\n For Backend\n "
] |
Please provide a description of the function:def _getCurrentj9Dict():
urls = j9urlGenerator()
j9Dict = {}
for url in urls:
d = _getDict(urllib.request.urlopen(url))
if len(d) == 0:
raise RuntimeError("Parsing failed, this is could require an update of the parser.")
j... | [
"Downloads and parses all the webpages\n\n For Backend\n "
] |
Please provide a description of the function:def updatej9DB(dbname = abrevDBname, saveRawHTML = False):
if saveRawHTML:
rawDir = '{}/j9Raws'.format(os.path.dirname(__file__))
if not os.path.isdir(rawDir):
os.mkdir(rawDir)
_j9SaveCurrent(sDir = rawDir)
dbLoc = os.path.joi... | [
"Updates the database of Journal Title Abbreviations. Requires an internet connection. The data base is saved relative to the source file not the working directory.\n\n # Parameters\n\n _dbname_ : `optional [str]`\n\n > The name of the database file, default is \"j9Abbreviations.db\"\n\n _saveRawHTML_ :... |
Please provide a description of the function:def getj9dict(dbname = abrevDBname, manualDB = manualDBname, returnDict ='both'):
dbLoc = os.path.normpath(os.path.dirname(__file__))
retDict = {}
try:
if returnDict == 'both' or returnDict == 'WOS':
with dbm.dumb.open(dbLoc + '/{}'.form... | [
"Returns the dictionary of journal abbreviations mapping to a list of the associated journal names. By default the local database is used. The database is in the file _dbname_ in the same directory as this source file\n\n # Parameters\n\n _dbname_ : `optional [str]`\n\n > The name of the downloaded databas... |
Please provide a description of the function:def addToDB(abbr = None, dbname = manualDBname):
dbLoc = os.path.normpath(os.path.dirname(__file__))
with dbm.dumb.open(dbLoc + '/' + dbname) as db:
if isinstance(abbr, str):
db[abbr] = abbr
elif isinstance(abbr, dict):
tr... | [
"Adds _abbr_ to the database of journals. The database is kept separate from the one scraped from WOS, this supersedes it. The database by default is stored with the WOS one and the name is given by `metaknowledge.journalAbbreviations.manualDBname`. To create an empty database run **addToDB** without an _abbr_ argu... |
Please provide a description of the function:def excludeFromDB(abbr = None, dbname = manualDBname):
dbLoc = os.path.normpath(os.path.dirname(__file__))
with dbm.dumb.open(dbLoc + '/' + dbname) as db:
if isinstance(abbr, str):
db[abbr] = ''
elif isinstance(abbr, list) or isinstan... | [
"Marks _abbr_ to be excluded the database of journals. The database is kept separate from the one scraped from WOS, this supersedes it. The database by default is stored with the WOS one and the name is given by `metaknowledge.journalAbbreviations.manualDBname`. To create an empty database run [addToDB()](#metaknow... |
Please provide a description of the function:def normalizeToTag(val):
try:
val = val.upper()
except AttributeError:
raise KeyError("{} is not a tag or name string".format(val))
if val not in tagsAndNameSetUpper:
raise KeyError("{} is not a tag or name string".format(val))
el... | [
"Converts tags or full names to 2 character tags, case insensitive\n\n # Parameters\n\n _val_: `str`\n\n > A two character string giving the tag or its full name\n\n # Returns\n\n `str`\n\n > The short name of _val_\n "
] |
Please provide a description of the function:def normalizeToName(val):
if val not in tagsAndNameSet:
raise KeyError("{} is not a tag or name string".format(val))
else:
try:
return tagToFullDict[val]
except KeyError:
return val | [
"Converts tags or full names to full names, case sensitive\n\n # Parameters\n\n _val_: `str`\n\n > A two character string giving the tag or its full name\n\n # Returns\n\n `str`\n\n > The full name of _val_\n "
] |
Please provide a description of the function:def authAddress(val):
ret = []
for a in val:
if a[0] == '[':
ret.append('] '.join(a.split('] ')[1:]))
else:
ret.append(a)
return ret | [
"\n # The C1 Tag\n\n extracts the address of the authors as given by WOS. **Warning** the mapping of author to address is not very good and is given in multiple ways.\n\n # Parameters\n\n _val_: `list[str]`\n\n > The raw data from a WOS file\n\n # Returns\n\n `list[str]`\n\n > A list of addr... |
Please provide a description of the function:def citations(val):
retCites = []
for c in val:
retCites.append(Citation(c))
return retCites | [
"\n # The CR Tag\n\n extracts a list of all the citations in the record, the citations are the [metaknowledge.Citation](../classes/Citation.html#metaknowledge.citation.Citation) class.\n\n # Parameters\n\n _val_: `list[str]`\n\n > The raw data from a WOS file\n\n # Returns\n\n ` list[metaknowle... |
Please provide a description of the function:def getInvestigators(self, tags = None, seperator = ";", _getTag = False):
#By default we don't know which field has the investigators
investVal = []
retTag = None
if tags is not None:
if not isinstance(tags, list):
... | [
"Returns a list of the names of investigators. This is done by looking (in order) for any of fields in _tags_ and splitting the strings on _seperator_. If no strings are found an empty list will be returned.\n\n *Note* for some Grants `getInvestigators` has been overwritten and will ignore the arguments and ... |
Please provide a description of the function:def getInstitutions(self, tags = None, seperator = ";", _getTag = False):
return self.getInvestigators(tags = tags, seperator = seperator, _getTag = _getTag) | [
"Returns a list of the names of institutions. This is done by looking (in order) for any of fields in _tags_ and splitting the strings on _seperator_ (in case of multiple institutions). If no strings are found an empty list will be returned.\n\n *Note* for some Grants `getInstitutions` has been overwritten a... |
Please provide a description of the function:def update(self, other):
if type(self) != type(other):
return NotImplemented
else:
if other.bad:
self.error = other.error
self.bad = True
self._fieldDict.update(other._fieldDict) | [
"Adds all the tag-entry pairs from _other_ to the `Grant`. If there is a conflict _other_ takes precedence.\n\n # Parameters\n\n _other_ : `Grant`\n\n > Another `Grant` of the same type as _self_\n "
] |
Please provide a description of the function:def networkCoInvestigatorInstitution(self, targetTags = None, tagSeperator = ';', count = True, weighted = True):
return self.networkCoInvestigator(targetTags = targetTags, tagSeperator = tagSeperator, count = count, weighted = weighted, _institutionLevel = ... | [
"This works the same as [networkCoInvestigator()](#metaknowledge.GrantCollection.networkCoInvestigator) see it for details."
] |
Please provide a description of the function:def networkCoInvestigator(self, targetTags = None, tagSeperator = ';', count = True, weighted = True, _institutionLevel = False):
grph = nx.Graph()
pcount = 0
if _institutionLevel:
progArgs = (0, "Starting to make a co-institution... | [
"Creates a co-investigator from the collection\n\n Most grants do not have a known investigator tag so it must be provided by the user in _targetTags_ and the separator character if it is not a semicolon should also be given.\n\n # Parameters\n\n > _targetTags_ : `optional list[str]`\n\n ... |
Please provide a description of the function:def proQuestTagToFunc(tag):
if tag in singleLineEntries:
return lambda x : x[0]
elif tag in customTags:
return customTags[tag]
else:
return lambda x : x | [
"Takes a tag string, _tag_, and returns the processing function for its data. If their is not a predefined function returns the identity function (`lambda x : x`).\n\n # Parameters\n\n _tag_ : `str`\n\n > The requested tag\n\n # Returns\n\n `function`\n\n > A function to process the tag's data\n ... |
Please provide a description of the function:def scopusRecordParser(record, header = None):
if header is None:
header = scopusHeader
splitRecord = record[:-1].split(',')
tagDict = {}
quoted = False
for key in reversed(header):
currentVal = splitRecord.pop()
if currentVal... | [
"The parser [ScopusRecords](../classes/ScopusRecord.html#metaknowledge.scopus.ScopusRecord) use. This takes a line from [scopusParser()](#metaknowledge.scopus.scopusHandlers.scopusParser) and parses it as a part of the creation of a `ScopusRecord`.\n\n **Note** this is for csv files downloaded from scopus _not_ ... |
Please provide a description of the function:def createCitation(self, multiCite = False):
#Need to put the import here to avoid circular import issues
from ..citation import Citation
valsStr = ''
if multiCite:
auths = []
for auth in self.get("authorsShort... | [
"Overwriting the general [citation creator](./ExtendedRecord.html#metaknowledge.ExtendedRecord.createCitation) to deal with scopus weirdness.\n\n Creates a citation string, using the same format as other WOS citations, for the [Record](./Record.html#metaknowledge.Record) by reading the relevant special tags ... |
Please provide a description of the function:def isWOSFile(infile, checkedLines = 3):
try:
with open(infile, 'r', encoding='utf-8-sig') as openfile:
f = enumerate(openfile, start = 0)
for i in range(checkedLines):
if "VR 1.0" in f.__next__()[1]:
... | [
"Determines if _infile_ is the path to a WOS file. A file is considerd to be a WOS file if it has the correct encoding (`utf-8` with a BOM) and within the first _checkedLines_ a line starts with `\"VR 1.0\"`.\n\n # Parameters\n\n _infile_ : `str`\n\n > The path to the targets file\n\n _checkedLines_ : `... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.