repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
makinacorpus/landez
landez/tiles.py
ImageExporter.export_image
def export_image(self, bbox, zoomlevel, imagepath): """ Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel. """ assert has_pil, _("Cannot export image without python PIL") grid = self.grid_tiles(bbox, zoomlevel) width = len(grid[0]) height = len(grid) widthpix = width * self.tile_size heightpix = height * self.tile_size result = Image.new("RGBA", (widthpix, heightpix)) offset = (0, 0) for i, row in enumerate(grid): for j, (x, y) in enumerate(row): offset = (j * self.tile_size, i * self.tile_size) img = self._tile_image(self.tile((zoomlevel, x, y))) result.paste(img, offset) logger.info(_("Save resulting image to '%s'") % imagepath) result.save(imagepath)
python
def export_image(self, bbox, zoomlevel, imagepath): """ Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel. """ assert has_pil, _("Cannot export image without python PIL") grid = self.grid_tiles(bbox, zoomlevel) width = len(grid[0]) height = len(grid) widthpix = width * self.tile_size heightpix = height * self.tile_size result = Image.new("RGBA", (widthpix, heightpix)) offset = (0, 0) for i, row in enumerate(grid): for j, (x, y) in enumerate(row): offset = (j * self.tile_size, i * self.tile_size) img = self._tile_image(self.tile((zoomlevel, x, y))) result.paste(img, offset) logger.info(_("Save resulting image to '%s'") % imagepath) result.save(imagepath)
[ "def", "export_image", "(", "self", ",", "bbox", ",", "zoomlevel", ",", "imagepath", ")", ":", "assert", "has_pil", ",", "_", "(", "\"Cannot export image without python PIL\"", ")", "grid", "=", "self", ".", "grid_tiles", "(", "bbox", ",", "zoomlevel", ")", ...
Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel.
[ "Writes", "to", "imagepath", "the", "tiles", "for", "the", "specified", "bounding", "box", "and", "zoomlevel", "." ]
6e5c71ded6071158e7943df204cd7bd1ed623a30
https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L426-L445
train
39,600
robotools/extractor
Lib/extractor/formats/opentype.py
_makeScriptOrder
def _makeScriptOrder(gpos): """ Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front. """ scripts = [] for scriptRecord in gpos.ScriptList.ScriptRecord: scripts.append(scriptRecord.ScriptTag) if "DFLT" in scripts: scripts.remove("DFLT") scripts.insert(0, "DFLT") return sorted(scripts)
python
def _makeScriptOrder(gpos): """ Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front. """ scripts = [] for scriptRecord in gpos.ScriptList.ScriptRecord: scripts.append(scriptRecord.ScriptTag) if "DFLT" in scripts: scripts.remove("DFLT") scripts.insert(0, "DFLT") return sorted(scripts)
[ "def", "_makeScriptOrder", "(", "gpos", ")", ":", "scripts", "=", "[", "]", "for", "scriptRecord", "in", "gpos", ".", "ScriptList", ".", "ScriptRecord", ":", "scripts", ".", "append", "(", "scriptRecord", ".", "ScriptTag", ")", "if", "\"DFLT\"", "in", "scr...
Run therough GPOS and make an alphabetically ordered list of scripts. If DFLT is in the list, move it to the front.
[ "Run", "therough", "GPOS", "and", "make", "an", "alphabetically", "ordered", "list", "of", "scripts", ".", "If", "DFLT", "is", "in", "the", "list", "move", "it", "to", "the", "front", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L408-L420
train
39,601
robotools/extractor
Lib/extractor/formats/opentype.py
_gatherDataFromLookups
def _gatherDataFromLookups(gpos, scriptOrder): """ Gather kerning and classes from the applicable lookups and return them in script order. """ lookupIndexes = _gatherLookupIndexes(gpos) seenLookups = set() kerningDictionaries = [] leftClassDictionaries = [] rightClassDictionaries = [] for script in scriptOrder: kerning = [] leftClasses = [] rightClasses = [] for lookupIndex in lookupIndexes[script]: if lookupIndex in seenLookups: continue seenLookups.add(lookupIndex) result = _gatherKerningForLookup(gpos, lookupIndex) if result is None: continue k, lG, rG = result kerning.append(k) leftClasses.append(lG) rightClasses.append(rG) if kerning: kerningDictionaries.append(kerning) leftClassDictionaries.append(leftClasses) rightClassDictionaries.append(rightClasses) return kerningDictionaries, leftClassDictionaries, rightClassDictionaries
python
def _gatherDataFromLookups(gpos, scriptOrder): """ Gather kerning and classes from the applicable lookups and return them in script order. """ lookupIndexes = _gatherLookupIndexes(gpos) seenLookups = set() kerningDictionaries = [] leftClassDictionaries = [] rightClassDictionaries = [] for script in scriptOrder: kerning = [] leftClasses = [] rightClasses = [] for lookupIndex in lookupIndexes[script]: if lookupIndex in seenLookups: continue seenLookups.add(lookupIndex) result = _gatherKerningForLookup(gpos, lookupIndex) if result is None: continue k, lG, rG = result kerning.append(k) leftClasses.append(lG) rightClasses.append(rG) if kerning: kerningDictionaries.append(kerning) leftClassDictionaries.append(leftClasses) rightClassDictionaries.append(rightClasses) return kerningDictionaries, leftClassDictionaries, rightClassDictionaries
[ "def", "_gatherDataFromLookups", "(", "gpos", ",", "scriptOrder", ")", ":", "lookupIndexes", "=", "_gatherLookupIndexes", "(", "gpos", ")", "seenLookups", "=", "set", "(", ")", "kerningDictionaries", "=", "[", "]", "leftClassDictionaries", "=", "[", "]", "rightC...
Gather kerning and classes from the applicable lookups and return them in script order.
[ "Gather", "kerning", "and", "classes", "from", "the", "applicable", "lookups", "and", "return", "them", "in", "script", "order", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L422-L451
train
39,602
robotools/extractor
Lib/extractor/formats/opentype.py
_handleLookupType2Format1
def _handleLookupType2Format1(subtable): """ Extract a kerning dictionary from a Lookup Type 2 Format 1. """ kerning = {} coverage = subtable.Coverage.glyphs valueFormat1 = subtable.ValueFormat1 pairSets = subtable.PairSet for index, leftGlyphName in enumerate(coverage): pairSet = pairSets[index] for pairValueRecord in pairSet.PairValueRecord: rightGlyphName = pairValueRecord.SecondGlyph if valueFormat1: value = pairValueRecord.Value1 else: value = pairValueRecord.Value2 if hasattr(value, "XAdvance"): value = value.XAdvance kerning[leftGlyphName, rightGlyphName] = value return kerning
python
def _handleLookupType2Format1(subtable): """ Extract a kerning dictionary from a Lookup Type 2 Format 1. """ kerning = {} coverage = subtable.Coverage.glyphs valueFormat1 = subtable.ValueFormat1 pairSets = subtable.PairSet for index, leftGlyphName in enumerate(coverage): pairSet = pairSets[index] for pairValueRecord in pairSet.PairValueRecord: rightGlyphName = pairValueRecord.SecondGlyph if valueFormat1: value = pairValueRecord.Value1 else: value = pairValueRecord.Value2 if hasattr(value, "XAdvance"): value = value.XAdvance kerning[leftGlyphName, rightGlyphName] = value return kerning
[ "def", "_handleLookupType2Format1", "(", "subtable", ")", ":", "kerning", "=", "{", "}", "coverage", "=", "subtable", ".", "Coverage", ".", "glyphs", "valueFormat1", "=", "subtable", ".", "ValueFormat1", "pairSets", "=", "subtable", ".", "PairSet", "for", "ind...
Extract a kerning dictionary from a Lookup Type 2 Format 1.
[ "Extract", "a", "kerning", "dictionary", "from", "a", "Lookup", "Type", "2", "Format", "1", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L553-L572
train
39,603
robotools/extractor
Lib/extractor/formats/opentype.py
_handleLookupType2Format2
def _handleLookupType2Format2(subtable, lookupIndex, subtableIndex): """ Extract kerning, left class and right class dictionaries from a Lookup Type 2 Format 2. """ # extract the classes leftClasses = _extractFeatureClasses(lookupIndex=lookupIndex, subtableIndex=subtableIndex, classDefs=subtable.ClassDef1.classDefs, coverage=subtable.Coverage.glyphs) rightClasses = _extractFeatureClasses(lookupIndex=lookupIndex, subtableIndex=subtableIndex, classDefs=subtable.ClassDef2.classDefs) # extract the pairs kerning = {} for class1RecordIndex, class1Record in enumerate(subtable.Class1Record): for class2RecordIndex, class2Record in enumerate(class1Record.Class2Record): leftClass = (lookupIndex, subtableIndex, class1RecordIndex) rightClass = (lookupIndex, subtableIndex, class2RecordIndex) valueFormat1 = subtable.ValueFormat1 if valueFormat1: value = class2Record.Value1 else: value = class2Record.Value2 if hasattr(value, "XAdvance") and value.XAdvance != 0: value = value.XAdvance kerning[leftClass, rightClass] = value return kerning, leftClasses, rightClasses
python
def _handleLookupType2Format2(subtable, lookupIndex, subtableIndex): """ Extract kerning, left class and right class dictionaries from a Lookup Type 2 Format 2. """ # extract the classes leftClasses = _extractFeatureClasses(lookupIndex=lookupIndex, subtableIndex=subtableIndex, classDefs=subtable.ClassDef1.classDefs, coverage=subtable.Coverage.glyphs) rightClasses = _extractFeatureClasses(lookupIndex=lookupIndex, subtableIndex=subtableIndex, classDefs=subtable.ClassDef2.classDefs) # extract the pairs kerning = {} for class1RecordIndex, class1Record in enumerate(subtable.Class1Record): for class2RecordIndex, class2Record in enumerate(class1Record.Class2Record): leftClass = (lookupIndex, subtableIndex, class1RecordIndex) rightClass = (lookupIndex, subtableIndex, class2RecordIndex) valueFormat1 = subtable.ValueFormat1 if valueFormat1: value = class2Record.Value1 else: value = class2Record.Value2 if hasattr(value, "XAdvance") and value.XAdvance != 0: value = value.XAdvance kerning[leftClass, rightClass] = value return kerning, leftClasses, rightClasses
[ "def", "_handleLookupType2Format2", "(", "subtable", ",", "lookupIndex", ",", "subtableIndex", ")", ":", "# extract the classes", "leftClasses", "=", "_extractFeatureClasses", "(", "lookupIndex", "=", "lookupIndex", ",", "subtableIndex", "=", "subtableIndex", ",", "clas...
Extract kerning, left class and right class dictionaries from a Lookup Type 2 Format 2.
[ "Extract", "kerning", "left", "class", "and", "right", "class", "dictionaries", "from", "a", "Lookup", "Type", "2", "Format", "2", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L574-L595
train
39,604
robotools/extractor
Lib/extractor/formats/opentype.py
_mergeKerningDictionaries
def _mergeKerningDictionaries(kerningDictionaries): """ Merge all of the kerning dictionaries found into one flat dictionary. """ # work through the dictionaries backwards since # this uses an update to load the kerning. this # will ensure that the script order is honored. kerning = {} for dictionaryGroup in reversed(kerningDictionaries): for dictionary in dictionaryGroup: kerning.update(dictionary) # done. return kerning
python
def _mergeKerningDictionaries(kerningDictionaries): """ Merge all of the kerning dictionaries found into one flat dictionary. """ # work through the dictionaries backwards since # this uses an update to load the kerning. this # will ensure that the script order is honored. kerning = {} for dictionaryGroup in reversed(kerningDictionaries): for dictionary in dictionaryGroup: kerning.update(dictionary) # done. return kerning
[ "def", "_mergeKerningDictionaries", "(", "kerningDictionaries", ")", ":", "# work through the dictionaries backwards since", "# this uses an update to load the kerning. this", "# will ensure that the script order is honored.", "kerning", "=", "{", "}", "for", "dictionaryGroup", "in", ...
Merge all of the kerning dictionaries found into one flat dictionary.
[ "Merge", "all", "of", "the", "kerning", "dictionaries", "found", "into", "one", "flat", "dictionary", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L597-L610
train
39,605
robotools/extractor
Lib/extractor/formats/opentype.py
_findSingleMemberGroups
def _findSingleMemberGroups(classDictionaries): """ Find all classes that have only one member. """ toRemove = {} for classDictionaryGroup in classDictionaries: for classDictionary in classDictionaryGroup: for name, members in list(classDictionary.items()): if len(members) == 1: toRemove[name] = list(members)[0] del classDictionary[name] return toRemove
python
def _findSingleMemberGroups(classDictionaries): """ Find all classes that have only one member. """ toRemove = {} for classDictionaryGroup in classDictionaries: for classDictionary in classDictionaryGroup: for name, members in list(classDictionary.items()): if len(members) == 1: toRemove[name] = list(members)[0] del classDictionary[name] return toRemove
[ "def", "_findSingleMemberGroups", "(", "classDictionaries", ")", ":", "toRemove", "=", "{", "}", "for", "classDictionaryGroup", "in", "classDictionaries", ":", "for", "classDictionary", "in", "classDictionaryGroup", ":", "for", "name", ",", "members", "in", "list", ...
Find all classes that have only one member.
[ "Find", "all", "classes", "that", "have", "only", "one", "member", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L612-L623
train
39,606
robotools/extractor
Lib/extractor/formats/opentype.py
_removeSingleMemberGroupReferences
def _removeSingleMemberGroupReferences(kerning, leftGroups, rightGroups): """ Translate group names into glyph names in pairs if the group only contains one glyph. """ new = {} for (left, right), value in kerning.items(): left = leftGroups.get(left, left) right = rightGroups.get(right, right) new[left, right] = value return new
python
def _removeSingleMemberGroupReferences(kerning, leftGroups, rightGroups): """ Translate group names into glyph names in pairs if the group only contains one glyph. """ new = {} for (left, right), value in kerning.items(): left = leftGroups.get(left, left) right = rightGroups.get(right, right) new[left, right] = value return new
[ "def", "_removeSingleMemberGroupReferences", "(", "kerning", ",", "leftGroups", ",", "rightGroups", ")", ":", "new", "=", "{", "}", "for", "(", "left", ",", "right", ")", ",", "value", "in", "kerning", ".", "items", "(", ")", ":", "left", "=", "leftGroup...
Translate group names into glyph names in pairs if the group only contains one glyph.
[ "Translate", "group", "names", "into", "glyph", "names", "in", "pairs", "if", "the", "group", "only", "contains", "one", "glyph", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L625-L635
train
39,607
robotools/extractor
Lib/extractor/formats/opentype.py
_setGroupNames
def _setGroupNames(classes, classRename): """ Set the final names into the groups. """ groups = {} for groupName, glyphList in classes.items(): groupName = classRename.get(groupName, groupName) # if the glyph list has only one member, # the glyph name will be used in the pairs. # no group is needed. if len(glyphList) == 1: continue groups[groupName] = glyphList return groups
python
def _setGroupNames(classes, classRename): """ Set the final names into the groups. """ groups = {} for groupName, glyphList in classes.items(): groupName = classRename.get(groupName, groupName) # if the glyph list has only one member, # the glyph name will be used in the pairs. # no group is needed. if len(glyphList) == 1: continue groups[groupName] = glyphList return groups
[ "def", "_setGroupNames", "(", "classes", ",", "classRename", ")", ":", "groups", "=", "{", "}", "for", "groupName", ",", "glyphList", "in", "classes", ".", "items", "(", ")", ":", "groupName", "=", "classRename", ".", "get", "(", "groupName", ",", "group...
Set the final names into the groups.
[ "Set", "the", "final", "names", "into", "the", "groups", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L672-L685
train
39,608
robotools/extractor
Lib/extractor/formats/opentype.py
_validateClasses
def _validateClasses(classes): """ Check to make sure that a glyph is not part of more than one class. If this is found, an ExtractorError is raised. """ glyphToClass = {} for className, glyphList in classes.items(): for glyphName in glyphList: if glyphName not in glyphToClass: glyphToClass[glyphName] = set() glyphToClass[glyphName].add(className) for glyphName, groupList in glyphToClass.items(): if len(groupList) > 1: raise ExtractorError("Kerning classes are in an conflicting state.")
python
def _validateClasses(classes): """ Check to make sure that a glyph is not part of more than one class. If this is found, an ExtractorError is raised. """ glyphToClass = {} for className, glyphList in classes.items(): for glyphName in glyphList: if glyphName not in glyphToClass: glyphToClass[glyphName] = set() glyphToClass[glyphName].add(className) for glyphName, groupList in glyphToClass.items(): if len(groupList) > 1: raise ExtractorError("Kerning classes are in an conflicting state.")
[ "def", "_validateClasses", "(", "classes", ")", ":", "glyphToClass", "=", "{", "}", "for", "className", ",", "glyphList", "in", "classes", ".", "items", "(", ")", ":", "for", "glyphName", "in", "glyphList", ":", "if", "glyphName", "not", "in", "glyphToClas...
Check to make sure that a glyph is not part of more than one class. If this is found, an ExtractorError is raised.
[ "Check", "to", "make", "sure", "that", "a", "glyph", "is", "not", "part", "of", "more", "than", "one", "class", ".", "If", "this", "is", "found", "an", "ExtractorError", "is", "raised", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L687-L700
train
39,609
robotools/extractor
Lib/extractor/formats/opentype.py
_replaceRenamedPairMembers
def _replaceRenamedPairMembers(kerning, leftRename, rightRename): """ Populate the renamed pair members into the kerning. """ renamedKerning = {} for (left, right), value in kerning.items(): left = leftRename.get(left, left) right = rightRename.get(right, right) renamedKerning[left, right] = value return renamedKerning
python
def _replaceRenamedPairMembers(kerning, leftRename, rightRename): """ Populate the renamed pair members into the kerning. """ renamedKerning = {} for (left, right), value in kerning.items(): left = leftRename.get(left, left) right = rightRename.get(right, right) renamedKerning[left, right] = value return renamedKerning
[ "def", "_replaceRenamedPairMembers", "(", "kerning", ",", "leftRename", ",", "rightRename", ")", ":", "renamedKerning", "=", "{", "}", "for", "(", "left", ",", "right", ")", ",", "value", "in", "kerning", ".", "items", "(", ")", ":", "left", "=", "leftRe...
Populate the renamed pair members into the kerning.
[ "Populate", "the", "renamed", "pair", "members", "into", "the", "kerning", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L702-L711
train
39,610
robotools/extractor
Lib/extractor/formats/opentype.py
_renameClasses
def _renameClasses(classes, prefix): """ Replace class IDs with nice strings. """ renameMap = {} for classID, glyphList in classes.items(): if len(glyphList) == 0: groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2]) elif len(glyphList) == 1: groupName = list(glyphList)[0] else: glyphList = list(sorted(glyphList)) groupName = prefix + glyphList[0] renameMap[classID] = groupName return renameMap
python
def _renameClasses(classes, prefix): """ Replace class IDs with nice strings. """ renameMap = {} for classID, glyphList in classes.items(): if len(glyphList) == 0: groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2]) elif len(glyphList) == 1: groupName = list(glyphList)[0] else: glyphList = list(sorted(glyphList)) groupName = prefix + glyphList[0] renameMap[classID] = groupName return renameMap
[ "def", "_renameClasses", "(", "classes", ",", "prefix", ")", ":", "renameMap", "=", "{", "}", "for", "classID", ",", "glyphList", "in", "classes", ".", "items", "(", ")", ":", "if", "len", "(", "glyphList", ")", "==", "0", ":", "groupName", "=", "\"%...
Replace class IDs with nice strings.
[ "Replace", "class", "IDs", "with", "nice", "strings", "." ]
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L713-L727
train
39,611
robotools/extractor
Lib/extractor/formats/opentype.py
_extractFeatureClasses
def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None): """ Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are clearly not all to be used in kerning pairs. In the case of a missing class 0, the coverage is used as a basis for the class and glyph names used in classed 1+ are filtered out. In the case of class 0 having glyph names that are not part of the kerning pairs, the coverage is used to filter out the unnecessary glyph names. """ # gather the class members classDict = {} for glyphName, classIndex in classDefs.items(): if classIndex not in classDict: classDict[classIndex] = set() classDict[classIndex].add(glyphName) # specially handle class index 0 revisedClass0 = set() if coverage is not None and 0 in classDict: for glyphName in classDict[0]: if glyphName in coverage: revisedClass0.add(glyphName) elif coverage is not None and 0 not in classDict: revisedClass0 = set(coverage) for glyphList in classDict.values(): revisedClass0 = revisedClass0 - glyphList classDict[0] = revisedClass0 # flip the class map around classes = {} for classIndex, glyphList in classDict.items(): classes[lookupIndex, subtableIndex, classIndex] = frozenset(glyphList) return classes
python
def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None): """ Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are clearly not all to be used in kerning pairs. In the case of a missing class 0, the coverage is used as a basis for the class and glyph names used in classed 1+ are filtered out. In the case of class 0 having glyph names that are not part of the kerning pairs, the coverage is used to filter out the unnecessary glyph names. """ # gather the class members classDict = {} for glyphName, classIndex in classDefs.items(): if classIndex not in classDict: classDict[classIndex] = set() classDict[classIndex].add(glyphName) # specially handle class index 0 revisedClass0 = set() if coverage is not None and 0 in classDict: for glyphName in classDict[0]: if glyphName in coverage: revisedClass0.add(glyphName) elif coverage is not None and 0 not in classDict: revisedClass0 = set(coverage) for glyphList in classDict.values(): revisedClass0 = revisedClass0 - glyphList classDict[0] = revisedClass0 # flip the class map around classes = {} for classIndex, glyphList in classDict.items(): classes[lookupIndex, subtableIndex, classIndex] = frozenset(glyphList) return classes
[ "def", "_extractFeatureClasses", "(", "lookupIndex", ",", "subtableIndex", ",", "classDefs", ",", "coverage", "=", "None", ")", ":", "# gather the class members", "classDict", "=", "{", "}", "for", "glyphName", ",", "classIndex", "in", "classDefs", ".", "items", ...
Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are clearly not all to be used in kerning pairs. In the case of a missing class 0, the coverage is used as a basis for the class and glyph names used in classed 1+ are filtered out. In the case of class 0 having glyph names that are not part of the kerning pairs, the coverage is used to filter out the unnecessary glyph names.
[ "Extract", "classes", "for", "a", "specific", "lookup", "in", "a", "specific", "subtable", ".", "This", "is", "relatively", "straightforward", "except", "for", "class", "0", "interpretation", ".", "Some", "fonts", "don", "t", "have", "class", "0", ".", "Some...
da3c2c92bfd3da863dd5de29bd8bc94cbbf433df
https://github.com/robotools/extractor/blob/da3c2c92bfd3da863dd5de29bd8bc94cbbf433df/Lib/extractor/formats/opentype.py#L729-L762
train
39,612
thriftrw/thriftrw-python
thriftrw/compile/compiler.py
ModuleSpec.add_include
def add_include(self, name, module_spec): """Adds a module as an included module. :param name: Name under which the included module should be exposed in the current module. :param module_spec: ModuleSpec of the included module. """ assert name, 'name is required' assert self.can_include if name in self.includes: raise ThriftCompilerError( 'Cannot include module "%s" as "%s" in "%s". ' 'The name is already taken.' % (module_spec.name, name, self.path) ) self.includes[name] = module_spec self.scope.add_include(name, module_spec.scope, module_spec.surface)
python
def add_include(self, name, module_spec): """Adds a module as an included module. :param name: Name under which the included module should be exposed in the current module. :param module_spec: ModuleSpec of the included module. """ assert name, 'name is required' assert self.can_include if name in self.includes: raise ThriftCompilerError( 'Cannot include module "%s" as "%s" in "%s". ' 'The name is already taken.' % (module_spec.name, name, self.path) ) self.includes[name] = module_spec self.scope.add_include(name, module_spec.scope, module_spec.surface)
[ "def", "add_include", "(", "self", ",", "name", ",", "module_spec", ")", ":", "assert", "name", ",", "'name is required'", "assert", "self", ".", "can_include", "if", "name", "in", "self", ".", "includes", ":", "raise", "ThriftCompilerError", "(", "'Cannot inc...
Adds a module as an included module. :param name: Name under which the included module should be exposed in the current module. :param module_spec: ModuleSpec of the included module.
[ "Adds", "a", "module", "as", "an", "included", "module", "." ]
4f2f71acd7a0ac716c9ea5cdcea2162aa561304a
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/compile/compiler.py#L90-L110
train
39,613
thriftrw/thriftrw-python
thriftrw/compile/compiler.py
ModuleSpec.link
def link(self): """Link all the types in this module and all included modules.""" if self.linked: return self self.linked = True included_modules = [] # Link includes for include in self.includes.values(): included_modules.append(include.link().surface) self.scope.add_surface('__includes__', tuple(included_modules)) self.scope.add_surface('__thrift_source__', self.thrift_source) # Link self for linker in LINKERS: linker(self.scope).link() self.scope.add_surface('loads', Deserializer(self.protocol)) self.scope.add_surface('dumps', Serializer(self.protocol)) return self
python
def link(self): """Link all the types in this module and all included modules.""" if self.linked: return self self.linked = True included_modules = [] # Link includes for include in self.includes.values(): included_modules.append(include.link().surface) self.scope.add_surface('__includes__', tuple(included_modules)) self.scope.add_surface('__thrift_source__', self.thrift_source) # Link self for linker in LINKERS: linker(self.scope).link() self.scope.add_surface('loads', Deserializer(self.protocol)) self.scope.add_surface('dumps', Serializer(self.protocol)) return self
[ "def", "link", "(", "self", ")", ":", "if", "self", ".", "linked", ":", "return", "self", "self", ".", "linked", "=", "True", "included_modules", "=", "[", "]", "# Link includes", "for", "include", "in", "self", ".", "includes", ".", "values", "(", ")"...
Link all the types in this module and all included modules.
[ "Link", "all", "the", "types", "in", "this", "module", "and", "all", "included", "modules", "." ]
4f2f71acd7a0ac716c9ea5cdcea2162aa561304a
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/compile/compiler.py#L112-L135
train
39,614
thriftrw/thriftrw-python
thriftrw/compile/compiler.py
Compiler.compile
def compile(self, name, contents, path=None): """Compile the given Thrift document into a Python module. The generated module contains, .. py:attribute:: __services__ A collection of generated classes for all services defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``services`` to ``__services__``. .. py:attribute:: __types__ A collection of generated types for all types defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``types`` to ``__types__``. .. py:attribute:: __includes__ A collection of modules included by this module. .. versionadded:: 1.0 .. py:attribute:: __constants__ A mapping of constant name to value for all constants defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``constants`` to ``__constants__``. .. py:attribute:: __thrift_source__ Contents of the .thrift file from which this module was compiled. .. versionadded:: 1.1 .. py:function:: dumps(obj) Serializes the given object using the protocol the compiler was instantiated with. .. py:function:: loads(cls, payload) Deserializes an object of type ``cls`` from ``payload`` using the protocol the compiler was instantiated with. .. py:function:: dumps.message(obj, seqid=0) Serializes the given request or response into a :py:class:`~thriftrw.wire.Message` using the protocol that the compiler was instantiated with. See :ref:`calling-apache-thrift`. .. versionadded:: 1.0 .. py:function:: loads.message(service, payload) Deserializes a :py:class:`~thriftrw.wire.Message` from ``payload`` using the protocol the compiler was instantiated with. A request or response of a method defined in the given service is parsed in the message body. See :ref:`calling-apache-thrift`. .. versionadded:: 1.0 And one class each for every struct, union, exception, enum, and service defined in the IDL. Service classes have references to :py:class:`thriftrw.spec.ServiceFunction` objects for each method defined in the service. :param str name: Name of the Thrift document. This will be the name of the generated module. :param str contents: Thrift document to compile :param str path: Path to the Thrift file being compiled. If not specified, imports from within the Thrift file will be disallowed. :returns: ModuleSpec of the generated module. """ assert name if path: path = os.path.abspath(path) if path in self._module_specs: return self._module_specs[path] module_spec = ModuleSpec(name, self.protocol, path, contents) if path: self._module_specs[path] = module_spec program = self.parser.parse(contents) header_processor = HeaderProcessor(self, module_spec, self.include_as) for header in program.headers: header.apply(header_processor) generator = Generator(module_spec.scope, strict=self.strict) for definition in program.definitions: generator.process(definition) return module_spec
python
def compile(self, name, contents, path=None): """Compile the given Thrift document into a Python module. The generated module contains, .. py:attribute:: __services__ A collection of generated classes for all services defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``services`` to ``__services__``. .. py:attribute:: __types__ A collection of generated types for all types defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``types`` to ``__types__``. .. py:attribute:: __includes__ A collection of modules included by this module. .. versionadded:: 1.0 .. py:attribute:: __constants__ A mapping of constant name to value for all constants defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``constants`` to ``__constants__``. .. py:attribute:: __thrift_source__ Contents of the .thrift file from which this module was compiled. .. versionadded:: 1.1 .. py:function:: dumps(obj) Serializes the given object using the protocol the compiler was instantiated with. .. py:function:: loads(cls, payload) Deserializes an object of type ``cls`` from ``payload`` using the protocol the compiler was instantiated with. .. py:function:: dumps.message(obj, seqid=0) Serializes the given request or response into a :py:class:`~thriftrw.wire.Message` using the protocol that the compiler was instantiated with. See :ref:`calling-apache-thrift`. .. versionadded:: 1.0 .. py:function:: loads.message(service, payload) Deserializes a :py:class:`~thriftrw.wire.Message` from ``payload`` using the protocol the compiler was instantiated with. A request or response of a method defined in the given service is parsed in the message body. See :ref:`calling-apache-thrift`. .. versionadded:: 1.0 And one class each for every struct, union, exception, enum, and service defined in the IDL. Service classes have references to :py:class:`thriftrw.spec.ServiceFunction` objects for each method defined in the service. :param str name: Name of the Thrift document. This will be the name of the generated module. :param str contents: Thrift document to compile :param str path: Path to the Thrift file being compiled. If not specified, imports from within the Thrift file will be disallowed. :returns: ModuleSpec of the generated module. """ assert name if path: path = os.path.abspath(path) if path in self._module_specs: return self._module_specs[path] module_spec = ModuleSpec(name, self.protocol, path, contents) if path: self._module_specs[path] = module_spec program = self.parser.parse(contents) header_processor = HeaderProcessor(self, module_spec, self.include_as) for header in program.headers: header.apply(header_processor) generator = Generator(module_spec.scope, strict=self.strict) for definition in program.definitions: generator.process(definition) return module_spec
[ "def", "compile", "(", "self", ",", "name", ",", "contents", ",", "path", "=", "None", ")", ":", "assert", "name", "if", "path", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "path", "in", "self", ".", "_module_specs"...
Compile the given Thrift document into a Python module. The generated module contains, .. py:attribute:: __services__ A collection of generated classes for all services defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``services`` to ``__services__``. .. py:attribute:: __types__ A collection of generated types for all types defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``types`` to ``__types__``. .. py:attribute:: __includes__ A collection of modules included by this module. .. versionadded:: 1.0 .. py:attribute:: __constants__ A mapping of constant name to value for all constants defined in the thrift file. .. versionchanged:: 1.0 Renamed from ``constants`` to ``__constants__``. .. py:attribute:: __thrift_source__ Contents of the .thrift file from which this module was compiled. .. versionadded:: 1.1 .. py:function:: dumps(obj) Serializes the given object using the protocol the compiler was instantiated with. .. py:function:: loads(cls, payload) Deserializes an object of type ``cls`` from ``payload`` using the protocol the compiler was instantiated with. .. py:function:: dumps.message(obj, seqid=0) Serializes the given request or response into a :py:class:`~thriftrw.wire.Message` using the protocol that the compiler was instantiated with. See :ref:`calling-apache-thrift`. .. versionadded:: 1.0 .. py:function:: loads.message(service, payload) Deserializes a :py:class:`~thriftrw.wire.Message` from ``payload`` using the protocol the compiler was instantiated with. A request or response of a method defined in the given service is parsed in the message body. See :ref:`calling-apache-thrift`. .. versionadded:: 1.0 And one class each for every struct, union, exception, enum, and service defined in the IDL. Service classes have references to :py:class:`thriftrw.spec.ServiceFunction` objects for each method defined in the service. :param str name: Name of the Thrift document. This will be the name of the generated module. :param str contents: Thrift document to compile :param str path: Path to the Thrift file being compiled. If not specified, imports from within the Thrift file will be disallowed. :returns: ModuleSpec of the generated module.
[ "Compile", "the", "given", "Thrift", "document", "into", "a", "Python", "module", "." ]
4f2f71acd7a0ac716c9ea5cdcea2162aa561304a
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/compile/compiler.py#L164-L278
train
39,615
thriftrw/thriftrw-python
thriftrw/idl/lexer.py
Lexer.input
def input(self, data): """Reset the lexer and feed in new input. :param data: String of input data. """ # input(..) doesn't reset the lineno. We have to do that manually. self._lexer.lineno = 1 return self._lexer.input(data)
python
def input(self, data): """Reset the lexer and feed in new input. :param data: String of input data. """ # input(..) doesn't reset the lineno. We have to do that manually. self._lexer.lineno = 1 return self._lexer.input(data)
[ "def", "input", "(", "self", ",", "data", ")", ":", "# input(..) doesn't reset the lineno. We have to do that manually.", "self", ".", "_lexer", ".", "lineno", "=", "1", "return", "self", ".", "_lexer", ".", "input", "(", "data", ")" ]
Reset the lexer and feed in new input. :param data: String of input data.
[ "Reset", "the", "lexer", "and", "feed", "in", "new", "input", "." ]
4f2f71acd7a0ac716c9ea5cdcea2162aa561304a
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/idl/lexer.py#L169-L177
train
39,616
Spinmob/spinmob
egg/example_sweeper.py
get_data
def get_data(): """ Currently pretends to talk to an instrument and get back the magnitud and phase of the measurement. """ # pretend we're measuring a noisy resonance at zero y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1 # and that it takes time to do so _t.sleep(0.1) # return mag phase return abs(y), _n.angle(y, True)
python
def get_data(): """ Currently pretends to talk to an instrument and get back the magnitud and phase of the measurement. """ # pretend we're measuring a noisy resonance at zero y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1 # and that it takes time to do so _t.sleep(0.1) # return mag phase return abs(y), _n.angle(y, True)
[ "def", "get_data", "(", ")", ":", "# pretend we're measuring a noisy resonance at zero", "y", "=", "1.0", "/", "(", "1.0", "+", "1j", "*", "(", "n_x", ".", "get_value", "(", ")", "-", "0.002", ")", "*", "1000", ")", "+", "_n", ".", "random", ".", "rand...
Currently pretends to talk to an instrument and get back the magnitud and phase of the measurement.
[ "Currently", "pretends", "to", "talk", "to", "an", "instrument", "and", "get", "back", "the", "magnitud", "and", "phase", "of", "the", "measurement", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/example_sweeper.py#L61-L74
train
39,617
Spinmob/spinmob
_settings.py
settings.List
def List(self): """ Lists the keys and values. """ print() for key in list(self.keys()): print(key,'=',self[key]) print()
python
def List(self): """ Lists the keys and values. """ print() for key in list(self.keys()): print(key,'=',self[key]) print()
[ "def", "List", "(", "self", ")", ":", "print", "(", ")", "for", "key", "in", "list", "(", "self", ".", "keys", "(", ")", ")", ":", "print", "(", "key", ",", "'='", ",", "self", "[", "key", "]", ")", "print", "(", ")" ]
Lists the keys and values.
[ "Lists", "the", "keys", "and", "values", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_settings.py#L67-L74
train
39,618
Spinmob/spinmob
_settings.py
settings.Set
def Set(self, key, value): """ Sets the key-value pair and dumps to the preferences file. """ if not value == None: self.prefs[key] = value else: self.prefs.pop(key) self.Dump()
python
def Set(self, key, value): """ Sets the key-value pair and dumps to the preferences file. """ if not value == None: self.prefs[key] = value else: self.prefs.pop(key) self.Dump()
[ "def", "Set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "not", "value", "==", "None", ":", "self", ".", "prefs", "[", "key", "]", "=", "value", "else", ":", "self", ".", "prefs", ".", "pop", "(", "key", ")", "self", ".", "Dump", ...
Sets the key-value pair and dumps to the preferences file.
[ "Sets", "the", "key", "-", "value", "pair", "and", "dumps", "to", "the", "preferences", "file", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_settings.py#L85-L92
train
39,619
Spinmob/spinmob
_settings.py
settings.MakeDir
def MakeDir(self, path="temp"): """ Creates a directory of the specified path in the .spinmob directory. """ full_path = _os.path.join(self.path_home, path) # only make it if it doesn't exist! if not _os.path.exists(full_path): _os.makedirs(full_path)
python
def MakeDir(self, path="temp"): """ Creates a directory of the specified path in the .spinmob directory. """ full_path = _os.path.join(self.path_home, path) # only make it if it doesn't exist! if not _os.path.exists(full_path): _os.makedirs(full_path)
[ "def", "MakeDir", "(", "self", ",", "path", "=", "\"temp\"", ")", ":", "full_path", "=", "_os", ".", "path", ".", "join", "(", "self", ".", "path_home", ",", "path", ")", "# only make it if it doesn't exist!", "if", "not", "_os", ".", "path", ".", "exist...
Creates a directory of the specified path in the .spinmob directory.
[ "Creates", "a", "directory", "of", "the", "specified", "path", "in", "the", ".", "spinmob", "directory", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_settings.py#L106-L113
train
39,620
thriftrw/thriftrw-python
thriftrw/idl/parser.py
ParserSpec._parse_seq
def _parse_seq(self, p): """Helper to parse sequence rules. Sequence rules are in the form:: foo : foo_item sep foo | foo_item foo | This function builds a deque of the items in-order. If the number of tokens doesn't match, an exception is raised. """ # This basically says: # # - When you reach the end of the list, construct and return an empty # deque. # - Otherwise, prepend to start of what you got from the parser. # # So this ends up constructing an in-order list. if len(p) == 4: p[3].appendleft(p[1]) p[0] = p[3] elif len(p) == 3: p[2].appendleft(p[1]) p[0] = p[2] elif len(p) == 1: p[0] = deque() else: raise ThriftParserError( 'Wrong number of tokens received for expression at line %d' % p.lineno(1) )
python
def _parse_seq(self, p): """Helper to parse sequence rules. Sequence rules are in the form:: foo : foo_item sep foo | foo_item foo | This function builds a deque of the items in-order. If the number of tokens doesn't match, an exception is raised. """ # This basically says: # # - When you reach the end of the list, construct and return an empty # deque. # - Otherwise, prepend to start of what you got from the parser. # # So this ends up constructing an in-order list. if len(p) == 4: p[3].appendleft(p[1]) p[0] = p[3] elif len(p) == 3: p[2].appendleft(p[1]) p[0] = p[2] elif len(p) == 1: p[0] = deque() else: raise ThriftParserError( 'Wrong number of tokens received for expression at line %d' % p.lineno(1) )
[ "def", "_parse_seq", "(", "self", ",", "p", ")", ":", "# This basically says:", "#", "# - When you reach the end of the list, construct and return an empty", "# deque.", "# - Otherwise, prepend to start of what you got from the parser.", "#", "# So this ends up constructing an in-order...
Helper to parse sequence rules. Sequence rules are in the form:: foo : foo_item sep foo | foo_item foo | This function builds a deque of the items in-order. If the number of tokens doesn't match, an exception is raised.
[ "Helper", "to", "parse", "sequence", "rules", "." ]
4f2f71acd7a0ac716c9ea5cdcea2162aa561304a
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/idl/parser.py#L413-L445
train
39,621
thriftrw/thriftrw-python
thriftrw/idl/parser.py
Parser.parse
def parse(self, input, **kwargs): """Parse the given input. :param input: String containing the text to be parsed. :raises thriftrw.errors.ThriftParserError: For parsing errors. """ return self._parser.parse(input, lexer=self._lexer, **kwargs)
python
def parse(self, input, **kwargs): """Parse the given input. :param input: String containing the text to be parsed. :raises thriftrw.errors.ThriftParserError: For parsing errors. """ return self._parser.parse(input, lexer=self._lexer, **kwargs)
[ "def", "parse", "(", "self", ",", "input", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_parser", ".", "parse", "(", "input", ",", "lexer", "=", "self", ".", "_lexer", ",", "*", "*", "kwargs", ")" ]
Parse the given input. :param input: String containing the text to be parsed. :raises thriftrw.errors.ThriftParserError: For parsing errors.
[ "Parse", "the", "given", "input", "." ]
4f2f71acd7a0ac716c9ea5cdcea2162aa561304a
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/idl/parser.py#L460-L468
train
39,622
Spinmob/spinmob
egg/example_other_widgets.py
acquire_fake_data
def acquire_fake_data(number_of_points=1000): """ This function generates some fake data and returns two channels of data in the form time_array, [channel1, channel2] """ # time array t = _n.linspace(0,10,number_of_points) return(t, [_n.cos(t)*(1.0+0.2*_n.random.random(number_of_points)), _n.sin(t +0.5*_n.random.random(number_of_points))])
python
def acquire_fake_data(number_of_points=1000): """ This function generates some fake data and returns two channels of data in the form time_array, [channel1, channel2] """ # time array t = _n.linspace(0,10,number_of_points) return(t, [_n.cos(t)*(1.0+0.2*_n.random.random(number_of_points)), _n.sin(t +0.5*_n.random.random(number_of_points))])
[ "def", "acquire_fake_data", "(", "number_of_points", "=", "1000", ")", ":", "# time array", "t", "=", "_n", ".", "linspace", "(", "0", ",", "10", ",", "number_of_points", ")", "return", "(", "t", ",", "[", "_n", ".", "cos", "(", "t", ")", "*", "(", ...
This function generates some fake data and returns two channels of data in the form time_array, [channel1, channel2]
[ "This", "function", "generates", "some", "fake", "data", "and", "returns", "two", "channels", "of", "data", "in", "the", "form" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/example_other_widgets.py#L90-L101
train
39,623
Spinmob/spinmob
_data.py
load
def load(path=None, first_data_line='auto', filters='*.*', text='Select a file, FACEHEAD.', default_directory='default_directory', quiet=True, header_only=False, transpose=False, **kwargs): """ Loads a data file into the databox data class. Returns the data object. Most keyword arguments are sent to databox.load() so check there for documentation.(if their function isn't obvious). Parameters ---------- path=None Supply a path to a data file; None means use a dialog. first_data_line="auto" Specify the index of the first data line, or have it figure this out automatically. filters="*.*" Specify file filters. text="Select a file, FACEHEAD." Window title text. default_directory="default_directory" Which directory to start in (by key). This lives in spinmob.settings. quiet=True Don't print stuff while loading. header_only=False Load only the header information. transpose = False Return databox.transpose(). Additioinal optional keyword arguments are sent to spinmob.data.databox(), so check there for more information. """ d = databox(**kwargs) d.load_file(path=path, first_data_line=first_data_line, filters=filters, text=text, default_directory=default_directory, header_only=header_only) if not quiet: print("\nloaded", d.path, "\n") if transpose: return d.transpose() return d
python
def load(path=None, first_data_line='auto', filters='*.*', text='Select a file, FACEHEAD.', default_directory='default_directory', quiet=True, header_only=False, transpose=False, **kwargs): """ Loads a data file into the databox data class. Returns the data object. Most keyword arguments are sent to databox.load() so check there for documentation.(if their function isn't obvious). Parameters ---------- path=None Supply a path to a data file; None means use a dialog. first_data_line="auto" Specify the index of the first data line, or have it figure this out automatically. filters="*.*" Specify file filters. text="Select a file, FACEHEAD." Window title text. default_directory="default_directory" Which directory to start in (by key). This lives in spinmob.settings. quiet=True Don't print stuff while loading. header_only=False Load only the header information. transpose = False Return databox.transpose(). Additioinal optional keyword arguments are sent to spinmob.data.databox(), so check there for more information. """ d = databox(**kwargs) d.load_file(path=path, first_data_line=first_data_line, filters=filters, text=text, default_directory=default_directory, header_only=header_only) if not quiet: print("\nloaded", d.path, "\n") if transpose: return d.transpose() return d
[ "def", "load", "(", "path", "=", "None", ",", "first_data_line", "=", "'auto'", ",", "filters", "=", "'*.*'", ",", "text", "=", "'Select a file, FACEHEAD.'", ",", "default_directory", "=", "'default_directory'", ",", "quiet", "=", "True", ",", "header_only", "...
Loads a data file into the databox data class. Returns the data object. Most keyword arguments are sent to databox.load() so check there for documentation.(if their function isn't obvious). Parameters ---------- path=None Supply a path to a data file; None means use a dialog. first_data_line="auto" Specify the index of the first data line, or have it figure this out automatically. filters="*.*" Specify file filters. text="Select a file, FACEHEAD." Window title text. default_directory="default_directory" Which directory to start in (by key). This lives in spinmob.settings. quiet=True Don't print stuff while loading. header_only=False Load only the header information. transpose = False Return databox.transpose(). Additioinal optional keyword arguments are sent to spinmob.data.databox(), so check there for more information.
[ "Loads", "a", "data", "file", "into", "the", "databox", "data", "class", ".", "Returns", "the", "data", "object", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L3013-L3051
train
39,624
Spinmob/spinmob
_data.py
databox.more_info
def more_info(self): """ Prints out more information about the databox. """ print("\nDatabox Instance", self.path) print("\nHeader") for h in self.hkeys: print(" "+h+":", self.h(h)) s = "\nColumns ("+str(len(self.ckeys))+"): " for c in self.ckeys: s = s+c+", " print(s[:-2])
python
def more_info(self): """ Prints out more information about the databox. """ print("\nDatabox Instance", self.path) print("\nHeader") for h in self.hkeys: print(" "+h+":", self.h(h)) s = "\nColumns ("+str(len(self.ckeys))+"): " for c in self.ckeys: s = s+c+", " print(s[:-2])
[ "def", "more_info", "(", "self", ")", ":", "print", "(", "\"\\nDatabox Instance\"", ",", "self", ".", "path", ")", "print", "(", "\"\\nHeader\"", ")", "for", "h", "in", "self", ".", "hkeys", ":", "print", "(", "\" \"", "+", "h", "+", "\":\"", ",", "...
Prints out more information about the databox.
[ "Prints", "out", "more", "information", "about", "the", "databox", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L101-L110
train
39,625
Spinmob/spinmob
_data.py
databox.execute_script
def execute_script(self, script, g=None): """ Runs a script, returning the result. Parameters ---------- script String script to be evaluated (see below). g=None Optional dictionary of additional globals for the script evaluation. These will automatically be inserted into self.extra_globals. Usage ----- Scripts are of the form: "3.0 + x/y - d[0] where x=3.0*c('my_column')+h('setting'); y=d[1]" By default, "d" refers to the databox object itself, giving access to everything and enabling complete control over the universe. Meanwhile, c() and h() give quick reference to d.c() and d.h() to get columns and header lines. Additionally, these scripts can see all of the numpy functions like sin, cos, sqrt, etc. If you would like access to additional globals in a script, there are a few options in addition to specifying the g parametres. You can set self.extra_globals to the appropriate globals dictionary or add globals using self.insert_global(). Setting g=globals() will automatically insert all of your current globals into this databox instance. There are a few shorthand scripts available as well. You can simply type a column name such as 'my_column' or a column number like 2. However, I only added this functionality as a shortcut, and something like "2.0*a where a=my_column" will not work unless 'my_column is otherwise defined. I figure since you're already writing a complicated script in that case, you don't want to accidentally shortcut your way into using a column instead of a constant! Use "2.0*a where a=c('my_column')" instead. """ # add any extra user-supplied global variables for the eventual eval() call. if not g==None: self.extra_globals.update(g) # If the script is not a list of scripts, return the script value. # This is the termination of a recursive call. if not _s.fun.is_iterable(script): # special case if script is None: return None # get the expression and variables dictionary [expression, v] = self._parse_script(script) # if there was a problem parsing the script if v is None: print("ERROR: Could not parse '"+script+"'") return None # get all the numpy stuff too g = self._globals() g.update(v) # otherwise, evaluate the script using python's eval command return eval(expression, g) # Otherwise, this is a list of (lists of) scripts. Make the recursive call. output = [] for s in script: output.append(self.execute_script(s)) return output
python
def execute_script(self, script, g=None): """ Runs a script, returning the result. Parameters ---------- script String script to be evaluated (see below). g=None Optional dictionary of additional globals for the script evaluation. These will automatically be inserted into self.extra_globals. Usage ----- Scripts are of the form: "3.0 + x/y - d[0] where x=3.0*c('my_column')+h('setting'); y=d[1]" By default, "d" refers to the databox object itself, giving access to everything and enabling complete control over the universe. Meanwhile, c() and h() give quick reference to d.c() and d.h() to get columns and header lines. Additionally, these scripts can see all of the numpy functions like sin, cos, sqrt, etc. If you would like access to additional globals in a script, there are a few options in addition to specifying the g parametres. You can set self.extra_globals to the appropriate globals dictionary or add globals using self.insert_global(). Setting g=globals() will automatically insert all of your current globals into this databox instance. There are a few shorthand scripts available as well. You can simply type a column name such as 'my_column' or a column number like 2. However, I only added this functionality as a shortcut, and something like "2.0*a where a=my_column" will not work unless 'my_column is otherwise defined. I figure since you're already writing a complicated script in that case, you don't want to accidentally shortcut your way into using a column instead of a constant! Use "2.0*a where a=c('my_column')" instead. """ # add any extra user-supplied global variables for the eventual eval() call. if not g==None: self.extra_globals.update(g) # If the script is not a list of scripts, return the script value. # This is the termination of a recursive call. if not _s.fun.is_iterable(script): # special case if script is None: return None # get the expression and variables dictionary [expression, v] = self._parse_script(script) # if there was a problem parsing the script if v is None: print("ERROR: Could not parse '"+script+"'") return None # get all the numpy stuff too g = self._globals() g.update(v) # otherwise, evaluate the script using python's eval command return eval(expression, g) # Otherwise, this is a list of (lists of) scripts. Make the recursive call. output = [] for s in script: output.append(self.execute_script(s)) return output
[ "def", "execute_script", "(", "self", ",", "script", ",", "g", "=", "None", ")", ":", "# add any extra user-supplied global variables for the eventual eval() call.", "if", "not", "g", "==", "None", ":", "self", ".", "extra_globals", ".", "update", "(", "g", ")", ...
Runs a script, returning the result. Parameters ---------- script String script to be evaluated (see below). g=None Optional dictionary of additional globals for the script evaluation. These will automatically be inserted into self.extra_globals. Usage ----- Scripts are of the form: "3.0 + x/y - d[0] where x=3.0*c('my_column')+h('setting'); y=d[1]" By default, "d" refers to the databox object itself, giving access to everything and enabling complete control over the universe. Meanwhile, c() and h() give quick reference to d.c() and d.h() to get columns and header lines. Additionally, these scripts can see all of the numpy functions like sin, cos, sqrt, etc. If you would like access to additional globals in a script, there are a few options in addition to specifying the g parametres. You can set self.extra_globals to the appropriate globals dictionary or add globals using self.insert_global(). Setting g=globals() will automatically insert all of your current globals into this databox instance. There are a few shorthand scripts available as well. You can simply type a column name such as 'my_column' or a column number like 2. However, I only added this functionality as a shortcut, and something like "2.0*a where a=my_column" will not work unless 'my_column is otherwise defined. I figure since you're already writing a complicated script in that case, you don't want to accidentally shortcut your way into using a column instead of a constant! Use "2.0*a where a=c('my_column')" instead.
[ "Runs", "a", "script", "returning", "the", "result", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L702-L772
train
39,626
Spinmob/spinmob
_data.py
databox.copy_headers
def copy_headers(self, source_databox): """ Loops over the hkeys of the source_databox, updating this databoxes' header. """ for k in source_databox.hkeys: self.insert_header(k, source_databox.h(k)) return self
python
def copy_headers(self, source_databox): """ Loops over the hkeys of the source_databox, updating this databoxes' header. """ for k in source_databox.hkeys: self.insert_header(k, source_databox.h(k)) return self
[ "def", "copy_headers", "(", "self", ",", "source_databox", ")", ":", "for", "k", "in", "source_databox", ".", "hkeys", ":", "self", ".", "insert_header", "(", "k", ",", "source_databox", ".", "h", "(", "k", ")", ")", "return", "self" ]
Loops over the hkeys of the source_databox, updating this databoxes' header.
[ "Loops", "over", "the", "hkeys", "of", "the", "source_databox", "updating", "this", "databoxes", "header", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L880-L886
train
39,627
Spinmob/spinmob
_data.py
databox.copy_columns
def copy_columns(self, source_databox): """ Loops over the ckeys of the source_databox, updating this databoxes' columns. """ for k in source_databox.ckeys: self.insert_column(source_databox[k], k) return self
python
def copy_columns(self, source_databox): """ Loops over the ckeys of the source_databox, updating this databoxes' columns. """ for k in source_databox.ckeys: self.insert_column(source_databox[k], k) return self
[ "def", "copy_columns", "(", "self", ",", "source_databox", ")", ":", "for", "k", "in", "source_databox", ".", "ckeys", ":", "self", ".", "insert_column", "(", "source_databox", "[", "k", "]", ",", "k", ")", "return", "self" ]
Loops over the ckeys of the source_databox, updating this databoxes' columns.
[ "Loops", "over", "the", "ckeys", "of", "the", "source_databox", "updating", "this", "databoxes", "columns", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L888-L894
train
39,628
Spinmob/spinmob
_data.py
databox.copy_all
def copy_all(self, source_databox): """ Copies the header and columns from source_databox to this databox. """ self.copy_headers(source_databox) self.copy_columns(source_databox) return self
python
def copy_all(self, source_databox): """ Copies the header and columns from source_databox to this databox. """ self.copy_headers(source_databox) self.copy_columns(source_databox) return self
[ "def", "copy_all", "(", "self", ",", "source_databox", ")", ":", "self", ".", "copy_headers", "(", "source_databox", ")", "self", ".", "copy_columns", "(", "source_databox", ")", "return", "self" ]
Copies the header and columns from source_databox to this databox.
[ "Copies", "the", "header", "and", "columns", "from", "source_databox", "to", "this", "databox", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L896-L902
train
39,629
Spinmob/spinmob
_data.py
databox.insert_globals
def insert_globals(self, *args, **kwargs): """ Appends or overwrites the supplied object in the self.extra_globals. Use this to expose execute_script() or _parse_script() etc... to external objects and functions. Regular arguments are assumed to have a __name__ attribute (as is the case for functions) to use as the key, and keyword arguments will just be added as dictionary elements. """ for a in args: kwargs[a.__name__] = a self.extra_globals.update(kwargs)
python
def insert_globals(self, *args, **kwargs): """ Appends or overwrites the supplied object in the self.extra_globals. Use this to expose execute_script() or _parse_script() etc... to external objects and functions. Regular arguments are assumed to have a __name__ attribute (as is the case for functions) to use as the key, and keyword arguments will just be added as dictionary elements. """ for a in args: kwargs[a.__name__] = a self.extra_globals.update(kwargs)
[ "def", "insert_globals", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "a", "in", "args", ":", "kwargs", "[", "a", ".", "__name__", "]", "=", "a", "self", ".", "extra_globals", ".", "update", "(", "kwargs", ")" ]
Appends or overwrites the supplied object in the self.extra_globals. Use this to expose execute_script() or _parse_script() etc... to external objects and functions. Regular arguments are assumed to have a __name__ attribute (as is the case for functions) to use as the key, and keyword arguments will just be added as dictionary elements.
[ "Appends", "or", "overwrites", "the", "supplied", "object", "in", "the", "self", ".", "extra_globals", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L904-L916
train
39,630
Spinmob/spinmob
_data.py
databox.pop_header
def pop_header(self, hkey, ignore_error=False): """ This will remove and return the specified header value. Parameters ---------- hkey Header key you wish to pop. You can specify either a key string or an index. ignore_error=False Whether to quietly ignore any errors (i.e., hkey not found). """ # try the integer approach first to allow negative values if type(hkey) is not str: try: return self.headers.pop(self.hkeys.pop(hkey)) except: if not ignore_error: print("ERROR: pop_header() could not find hkey "+str(hkey)) return None else: try: # find the key integer and pop it hkey = self.hkeys.index(hkey) # pop it! return self.headers.pop(self.hkeys.pop(hkey)) except: if not ignore_error: print("ERROR: pop_header() could not find hkey "+str(hkey)) return
python
def pop_header(self, hkey, ignore_error=False): """ This will remove and return the specified header value. Parameters ---------- hkey Header key you wish to pop. You can specify either a key string or an index. ignore_error=False Whether to quietly ignore any errors (i.e., hkey not found). """ # try the integer approach first to allow negative values if type(hkey) is not str: try: return self.headers.pop(self.hkeys.pop(hkey)) except: if not ignore_error: print("ERROR: pop_header() could not find hkey "+str(hkey)) return None else: try: # find the key integer and pop it hkey = self.hkeys.index(hkey) # pop it! return self.headers.pop(self.hkeys.pop(hkey)) except: if not ignore_error: print("ERROR: pop_header() could not find hkey "+str(hkey)) return
[ "def", "pop_header", "(", "self", ",", "hkey", ",", "ignore_error", "=", "False", ")", ":", "# try the integer approach first to allow negative values", "if", "type", "(", "hkey", ")", "is", "not", "str", ":", "try", ":", "return", "self", ".", "headers", ".",...
This will remove and return the specified header value. Parameters ---------- hkey Header key you wish to pop. You can specify either a key string or an index. ignore_error=False Whether to quietly ignore any errors (i.e., hkey not found).
[ "This", "will", "remove", "and", "return", "the", "specified", "header", "value", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1022-L1055
train
39,631
Spinmob/spinmob
_data.py
databox.pop_column
def pop_column(self, ckey): """ This will remove and return the data in the specified column. You can specify either a key string or an index. """ # try the integer approach first to allow negative values if type(ckey) is not str: return self.columns.pop(self.ckeys.pop(ckey)) else: # find the key integer and pop it ckey = self.ckeys.index(ckey) # if we didn't find the column, quit if ckey < 0: print("Column does not exist (yes, we looked).") return # pop it! return self.columns.pop(self.ckeys.pop(ckey))
python
def pop_column(self, ckey): """ This will remove and return the data in the specified column. You can specify either a key string or an index. """ # try the integer approach first to allow negative values if type(ckey) is not str: return self.columns.pop(self.ckeys.pop(ckey)) else: # find the key integer and pop it ckey = self.ckeys.index(ckey) # if we didn't find the column, quit if ckey < 0: print("Column does not exist (yes, we looked).") return # pop it! return self.columns.pop(self.ckeys.pop(ckey))
[ "def", "pop_column", "(", "self", ",", "ckey", ")", ":", "# try the integer approach first to allow negative values", "if", "type", "(", "ckey", ")", "is", "not", "str", ":", "return", "self", ".", "columns", ".", "pop", "(", "self", ".", "ckeys", ".", "pop"...
This will remove and return the data in the specified column. You can specify either a key string or an index.
[ "This", "will", "remove", "and", "return", "the", "data", "in", "the", "specified", "column", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1059-L1079
train
39,632
Spinmob/spinmob
_data.py
databox.rename_header
def rename_header(self, old_name, new_name): """ This will rename the header. The supplied names need to be strings. """ self.hkeys[self.hkeys.index(old_name)] = new_name self.headers[new_name] = self.headers.pop(old_name) return self
python
def rename_header(self, old_name, new_name): """ This will rename the header. The supplied names need to be strings. """ self.hkeys[self.hkeys.index(old_name)] = new_name self.headers[new_name] = self.headers.pop(old_name) return self
[ "def", "rename_header", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "self", ".", "hkeys", "[", "self", ".", "hkeys", ".", "index", "(", "old_name", ")", "]", "=", "new_name", "self", ".", "headers", "[", "new_name", "]", "=", "self", "."...
This will rename the header. The supplied names need to be strings.
[ "This", "will", "rename", "the", "header", ".", "The", "supplied", "names", "need", "to", "be", "strings", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1153-L1159
train
39,633
Spinmob/spinmob
_data.py
databox.rename_column
def rename_column(self, column, new_name): """ This will rename the column. The supplied column can be an integer or the old column name. """ if type(column) is not str: column = self.ckeys[column] self.ckeys[self.ckeys.index(column)] = new_name self.columns[new_name] = self.columns.pop(column) return self
python
def rename_column(self, column, new_name): """ This will rename the column. The supplied column can be an integer or the old column name. """ if type(column) is not str: column = self.ckeys[column] self.ckeys[self.ckeys.index(column)] = new_name self.columns[new_name] = self.columns.pop(column) return self
[ "def", "rename_column", "(", "self", ",", "column", ",", "new_name", ")", ":", "if", "type", "(", "column", ")", "is", "not", "str", ":", "column", "=", "self", ".", "ckeys", "[", "column", "]", "self", ".", "ckeys", "[", "self", ".", "ckeys", ".",...
This will rename the column. The supplied column can be an integer or the old column name.
[ "This", "will", "rename", "the", "column", ".", "The", "supplied", "column", "can", "be", "an", "integer", "or", "the", "old", "column", "name", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1161-L1169
train
39,634
Spinmob/spinmob
_data.py
databox.transpose
def transpose(self): """ Returns a copy of this databox with the columns as rows. Currently requires that the databox has equal-length columns. """ # Create an empty databox with the same headers and delimiter. d = databox(delimter=self.delimiter) self.copy_headers(d) # Get the transpose z = _n.array(self[:]).transpose() # Build the columns of the new databox for n in range(len(z)): d['c'+str(n)] = z[n] return d
python
def transpose(self): """ Returns a copy of this databox with the columns as rows. Currently requires that the databox has equal-length columns. """ # Create an empty databox with the same headers and delimiter. d = databox(delimter=self.delimiter) self.copy_headers(d) # Get the transpose z = _n.array(self[:]).transpose() # Build the columns of the new databox for n in range(len(z)): d['c'+str(n)] = z[n] return d
[ "def", "transpose", "(", "self", ")", ":", "# Create an empty databox with the same headers and delimiter.", "d", "=", "databox", "(", "delimter", "=", "self", ".", "delimiter", ")", "self", ".", "copy_headers", "(", "d", ")", "# Get the transpose", "z", "=", "_n"...
Returns a copy of this databox with the columns as rows. Currently requires that the databox has equal-length columns.
[ "Returns", "a", "copy", "of", "this", "databox", "with", "the", "columns", "as", "rows", ".", "Currently", "requires", "that", "the", "databox", "has", "equal", "-", "length", "columns", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1202-L1218
train
39,635
Spinmob/spinmob
_data.py
fitter._update_functions
def _update_functions(self): """ Uses internal settings to update the functions. """ self.f = [] self.bg = [] self._fnames = [] self._bgnames = [] self._odr_models = [] # Like f, but different parameters, for use in ODR f = self._f_raw bg = self._bg_raw # make sure f and bg are lists of matching length if not _s.fun.is_iterable(f) : f = [f] if not _s.fun.is_iterable(bg): bg = [bg] while len(bg) < len(f): bg.append(None) # get a comma-delimited string list of parameter names for the "normal" function pstring = 'x, ' + ', '.join(self._pnames) # get the comma-delimited string for the ODR function pstring_odr = 'x, ' for n in range(len(self._pnames)): pstring_odr = pstring_odr+'p['+str(n)+'], ' # update the globals for the functions # the way this is done, we must redefine the functions # every time we change a constant for cname in self._cnames: self._globals[cname] = self[cname] # loop over all the functions and create the master list for n in range(len(f)): # if f[n] is a string, define a function on the fly. if isinstance(f[n], str): # "Normal" least squares function (y-error bars only) self.f.append( eval('lambda ' + pstring + ': ' + f[n], self._globals)) self._fnames.append(f[n]) # "ODR" compatible function (for x-error bars), based on self.f self._odr_models.append( _odr.Model(eval('lambda p,x: self.f[n]('+pstring_odr+')', dict(self=self, n=n)))) # Otherwise, just append it. else: self.f.append(f[n]) self._fnames.append(f[n].__name__) # if bg[n] is a string, define a function on the fly. if isinstance(bg[n], str): self.bg.append(eval('lambda ' + pstring + ': ' + bg[n], self._globals)) self._bgnames.append(bg[n]) else: self.bg.append(bg[n]) if bg[n] is None: self._bgnames.append("None") else: self._bgnames.append(bg[n].__name__) # update the format of all the settings for k in list(self._settings.keys()): self[k] = self[k] # make sure we don't think our fit results are valid! self.clear_results()
python
def _update_functions(self): """ Uses internal settings to update the functions. """ self.f = [] self.bg = [] self._fnames = [] self._bgnames = [] self._odr_models = [] # Like f, but different parameters, for use in ODR f = self._f_raw bg = self._bg_raw # make sure f and bg are lists of matching length if not _s.fun.is_iterable(f) : f = [f] if not _s.fun.is_iterable(bg): bg = [bg] while len(bg) < len(f): bg.append(None) # get a comma-delimited string list of parameter names for the "normal" function pstring = 'x, ' + ', '.join(self._pnames) # get the comma-delimited string for the ODR function pstring_odr = 'x, ' for n in range(len(self._pnames)): pstring_odr = pstring_odr+'p['+str(n)+'], ' # update the globals for the functions # the way this is done, we must redefine the functions # every time we change a constant for cname in self._cnames: self._globals[cname] = self[cname] # loop over all the functions and create the master list for n in range(len(f)): # if f[n] is a string, define a function on the fly. if isinstance(f[n], str): # "Normal" least squares function (y-error bars only) self.f.append( eval('lambda ' + pstring + ': ' + f[n], self._globals)) self._fnames.append(f[n]) # "ODR" compatible function (for x-error bars), based on self.f self._odr_models.append( _odr.Model(eval('lambda p,x: self.f[n]('+pstring_odr+')', dict(self=self, n=n)))) # Otherwise, just append it. else: self.f.append(f[n]) self._fnames.append(f[n].__name__) # if bg[n] is a string, define a function on the fly. if isinstance(bg[n], str): self.bg.append(eval('lambda ' + pstring + ': ' + bg[n], self._globals)) self._bgnames.append(bg[n]) else: self.bg.append(bg[n]) if bg[n] is None: self._bgnames.append("None") else: self._bgnames.append(bg[n].__name__) # update the format of all the settings for k in list(self._settings.keys()): self[k] = self[k] # make sure we don't think our fit results are valid! self.clear_results()
[ "def", "_update_functions", "(", "self", ")", ":", "self", ".", "f", "=", "[", "]", "self", ".", "bg", "=", "[", "]", "self", ".", "_fnames", "=", "[", "]", "self", ".", "_bgnames", "=", "[", "]", "self", ".", "_odr_models", "=", "[", "]", "# L...
Uses internal settings to update the functions.
[ "Uses", "internal", "settings", "to", "update", "the", "functions", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1776-L1839
train
39,636
Spinmob/spinmob
_data.py
fitter.set_data
def set_data(self, xdata=[1,2,3,4,5], ydata=[1.7,2,3,4,3], eydata=None, **kwargs): """ This will handle the different types of supplied data and put everything in a standard format for processing. Parameters ---------- xdata, ydata These can be a single array of data or a list of data arrays. eydata=None Error bars for ydata. These can be None (for guessed error) or data / numbers matching the dimensionality of xdata and ydata Notes ----- xdata, ydata, and eydata can all be scripts or lists of scripts that produce arrays. Any python code will work, and the scripts automatically know about all numpy functions, the guessed parameters, and the data itself (as x, y, ey). However, the scripts are executed in order -- xdata, ydata, and eydata -- so the xdata script cannot know about ydata or eydata, the ydata script cannot know about eydata, and the eydata script knows about xdata and ydata. Example: xdata = [1,2,3,4,5] ydata = [[1,2,1,2,1], 'cos(x[0])'] eydata = ['arctan(y[1])*a+b', 5] In this example, there will be two data sets to fit (so there better be two functions!), they will share the same xdata, the second ydata set will be the array cos([1,2,3,4,5]) (note since there are multiple data sets assumed (always), you have to select the data set with an index on x and y), the error on the first data set will be this weird functional dependence on the second ydata set and fit parameters a and b (note, if a and b are not fit parameters, then you must send them as keyword arguments so that they are defined) and the second data set error bar will be a constant, 5. Note this function is "somewhat" smart about reshaping the input data to ease life a bit, but it can't handle ambiguities. If you want to play it safe, supply lists for all three arguments that match in dimensionality. results can be obtained by calling get_data() Additional optional keyword arguments are added to the globals for script evaluation. """ # SET UP DATA SETS TO MATCH EACH OTHER AND NUMBER OF FUNCTIONS # At this stage: # xdata, ydata 'script', [1,2,3], [[1,2,3],'script'], ['script', [1,2,3]] # eydata, exdata 'script', [1,1,1], [[1,1,1],'script'], ['script', [1,1,1]], 3, [3,[1,2,3]], None # if xdata, ydata, or eydata are bare scripts, make them into lists if type(xdata) is str: xdata = [xdata] if type(ydata) is str: ydata = [ydata] if type(eydata) is str or _s.fun.is_a_number(eydata) or eydata is None: eydata = [eydata] #if type(exdata) is str or _s.fun.is_a_number(exdata) or exdata is None: exdata = [exdata] # xdata and ydata ['script'], [1,2,3], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script'], [1,1,1], [[1,1,1],'script'], ['script', [1,1,1]], [3], [3,[1,2,3]], [None] # if the first element of data is a number, then this is a normal array if _s.fun.is_a_number(xdata[0]): xdata = [xdata] if _s.fun.is_a_number(ydata[0]): ydata = [ydata] # xdata and ydata ['script'], [[1,2,3]], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script'], [1,1,1], [[1,1,1],'script'], ['script', [1,1,1]], [3], [3,[1,2,3]], [None] # if the first element of eydata is a number, this could also just be an error bar value # Note: there is some ambiguity here, if the number of data sets equals the number of data points! if _s.fun.is_a_number(eydata[0]) and len(eydata) == len(ydata[0]): eydata = [eydata] #if _s.fun.is_a_number(exdata[0]) and len(exdata) == len(xdata[0]): exdata = [exdata] # xdata and ydata ['script'], [[1,2,3]], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script'], [[1,1,1]], [[1,1,1],'script'], ['script', [1,1,1]], [3], [3,[1,2,3]], [None] # Inflate the x, ex, and ey data sets to match the ydata sets while len(xdata) < len(ydata): xdata .append( xdata[0]) while len(ydata) < len(xdata): ydata .append( ydata[0]) #while len(exdata) < len(xdata): exdata.append(exdata[0]) while len(eydata) < len(ydata): eydata.append(eydata[0]) # make sure these lists are the same length as the number of functions while len(ydata) < len(self.f): ydata.append(ydata[0]) while len(xdata) < len(self.f): xdata.append(xdata[0]) while len(eydata) < len(self.f): eydata.append(eydata[0]) #while len(exdata) < len(self.f): exdata.append(exdata[0]) # xdata and ydata ['script','script'], [[1,2,3],[1,2,3]], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script','script'], [[1,1,1],[1,1,1]], [[1,1,1],'script'], ['script', [1,1,1]], [3,3], [3,[1,2,3]], [None,None] # Clean up exdata. If any element isn't None, the other None elements need # to be set to 0 so that ODR works. # if not exdata.count(None) == len(exdata): # # Search for and replace all None's with 0 # for n in range(len(exdata)): # if exdata[n] == None: exdata[n] = 0 # # store the data, script, or whatever it is! self._set_xdata = xdata self._set_ydata = ydata self._set_eydata = eydata #self._set_exdata = exdata self._set_data_globals.update(kwargs) # set the eyscale to 1 for each data set self['scale_eydata'] = [1.0]*len(self._set_xdata) #self['scale_exdata'] = [1.0]*len(self._set_xdata) # Update the settings so they match the number of data sets. for k in self._settings.keys(): self[k] = self[k] # Plot if necessary if self['autoplot']: self.plot() return self
python
def set_data(self, xdata=[1,2,3,4,5], ydata=[1.7,2,3,4,3], eydata=None, **kwargs): """ This will handle the different types of supplied data and put everything in a standard format for processing. Parameters ---------- xdata, ydata These can be a single array of data or a list of data arrays. eydata=None Error bars for ydata. These can be None (for guessed error) or data / numbers matching the dimensionality of xdata and ydata Notes ----- xdata, ydata, and eydata can all be scripts or lists of scripts that produce arrays. Any python code will work, and the scripts automatically know about all numpy functions, the guessed parameters, and the data itself (as x, y, ey). However, the scripts are executed in order -- xdata, ydata, and eydata -- so the xdata script cannot know about ydata or eydata, the ydata script cannot know about eydata, and the eydata script knows about xdata and ydata. Example: xdata = [1,2,3,4,5] ydata = [[1,2,1,2,1], 'cos(x[0])'] eydata = ['arctan(y[1])*a+b', 5] In this example, there will be two data sets to fit (so there better be two functions!), they will share the same xdata, the second ydata set will be the array cos([1,2,3,4,5]) (note since there are multiple data sets assumed (always), you have to select the data set with an index on x and y), the error on the first data set will be this weird functional dependence on the second ydata set and fit parameters a and b (note, if a and b are not fit parameters, then you must send them as keyword arguments so that they are defined) and the second data set error bar will be a constant, 5. Note this function is "somewhat" smart about reshaping the input data to ease life a bit, but it can't handle ambiguities. If you want to play it safe, supply lists for all three arguments that match in dimensionality. results can be obtained by calling get_data() Additional optional keyword arguments are added to the globals for script evaluation. """ # SET UP DATA SETS TO MATCH EACH OTHER AND NUMBER OF FUNCTIONS # At this stage: # xdata, ydata 'script', [1,2,3], [[1,2,3],'script'], ['script', [1,2,3]] # eydata, exdata 'script', [1,1,1], [[1,1,1],'script'], ['script', [1,1,1]], 3, [3,[1,2,3]], None # if xdata, ydata, or eydata are bare scripts, make them into lists if type(xdata) is str: xdata = [xdata] if type(ydata) is str: ydata = [ydata] if type(eydata) is str or _s.fun.is_a_number(eydata) or eydata is None: eydata = [eydata] #if type(exdata) is str or _s.fun.is_a_number(exdata) or exdata is None: exdata = [exdata] # xdata and ydata ['script'], [1,2,3], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script'], [1,1,1], [[1,1,1],'script'], ['script', [1,1,1]], [3], [3,[1,2,3]], [None] # if the first element of data is a number, then this is a normal array if _s.fun.is_a_number(xdata[0]): xdata = [xdata] if _s.fun.is_a_number(ydata[0]): ydata = [ydata] # xdata and ydata ['script'], [[1,2,3]], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script'], [1,1,1], [[1,1,1],'script'], ['script', [1,1,1]], [3], [3,[1,2,3]], [None] # if the first element of eydata is a number, this could also just be an error bar value # Note: there is some ambiguity here, if the number of data sets equals the number of data points! if _s.fun.is_a_number(eydata[0]) and len(eydata) == len(ydata[0]): eydata = [eydata] #if _s.fun.is_a_number(exdata[0]) and len(exdata) == len(xdata[0]): exdata = [exdata] # xdata and ydata ['script'], [[1,2,3]], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script'], [[1,1,1]], [[1,1,1],'script'], ['script', [1,1,1]], [3], [3,[1,2,3]], [None] # Inflate the x, ex, and ey data sets to match the ydata sets while len(xdata) < len(ydata): xdata .append( xdata[0]) while len(ydata) < len(xdata): ydata .append( ydata[0]) #while len(exdata) < len(xdata): exdata.append(exdata[0]) while len(eydata) < len(ydata): eydata.append(eydata[0]) # make sure these lists are the same length as the number of functions while len(ydata) < len(self.f): ydata.append(ydata[0]) while len(xdata) < len(self.f): xdata.append(xdata[0]) while len(eydata) < len(self.f): eydata.append(eydata[0]) #while len(exdata) < len(self.f): exdata.append(exdata[0]) # xdata and ydata ['script','script'], [[1,2,3],[1,2,3]], [[1,2,3],'script'], ['script', [1,2,3]] # eydata ['script','script'], [[1,1,1],[1,1,1]], [[1,1,1],'script'], ['script', [1,1,1]], [3,3], [3,[1,2,3]], [None,None] # Clean up exdata. If any element isn't None, the other None elements need # to be set to 0 so that ODR works. # if not exdata.count(None) == len(exdata): # # Search for and replace all None's with 0 # for n in range(len(exdata)): # if exdata[n] == None: exdata[n] = 0 # # store the data, script, or whatever it is! self._set_xdata = xdata self._set_ydata = ydata self._set_eydata = eydata #self._set_exdata = exdata self._set_data_globals.update(kwargs) # set the eyscale to 1 for each data set self['scale_eydata'] = [1.0]*len(self._set_xdata) #self['scale_exdata'] = [1.0]*len(self._set_xdata) # Update the settings so they match the number of data sets. for k in self._settings.keys(): self[k] = self[k] # Plot if necessary if self['autoplot']: self.plot() return self
[ "def", "set_data", "(", "self", ",", "xdata", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", "]", ",", "ydata", "=", "[", "1.7", ",", "2", ",", "3", ",", "4", ",", "3", "]", ",", "eydata", "=", "None", ",", "*", "*", "kwargs", "...
This will handle the different types of supplied data and put everything in a standard format for processing. Parameters ---------- xdata, ydata These can be a single array of data or a list of data arrays. eydata=None Error bars for ydata. These can be None (for guessed error) or data / numbers matching the dimensionality of xdata and ydata Notes ----- xdata, ydata, and eydata can all be scripts or lists of scripts that produce arrays. Any python code will work, and the scripts automatically know about all numpy functions, the guessed parameters, and the data itself (as x, y, ey). However, the scripts are executed in order -- xdata, ydata, and eydata -- so the xdata script cannot know about ydata or eydata, the ydata script cannot know about eydata, and the eydata script knows about xdata and ydata. Example: xdata = [1,2,3,4,5] ydata = [[1,2,1,2,1], 'cos(x[0])'] eydata = ['arctan(y[1])*a+b', 5] In this example, there will be two data sets to fit (so there better be two functions!), they will share the same xdata, the second ydata set will be the array cos([1,2,3,4,5]) (note since there are multiple data sets assumed (always), you have to select the data set with an index on x and y), the error on the first data set will be this weird functional dependence on the second ydata set and fit parameters a and b (note, if a and b are not fit parameters, then you must send them as keyword arguments so that they are defined) and the second data set error bar will be a constant, 5. Note this function is "somewhat" smart about reshaping the input data to ease life a bit, but it can't handle ambiguities. If you want to play it safe, supply lists for all three arguments that match in dimensionality. results can be obtained by calling get_data() Additional optional keyword arguments are added to the globals for script evaluation.
[ "This", "will", "handle", "the", "different", "types", "of", "supplied", "data", "and", "put", "everything", "in", "a", "standard", "format", "for", "processing", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1842-L1961
train
39,637
Spinmob/spinmob
_data.py
fitter.set_guess_to_fit_result
def set_guess_to_fit_result(self): """ If you have a fit result, set the guess parameters to the fit parameters. """ if self.results is None: print("No fit results to use! Run fit() first.") return # loop over the results and set the guess values for n in range(len(self._pguess)): self._pguess[n] = self.results[0][n] if self['autoplot']: self.plot() return self
python
def set_guess_to_fit_result(self): """ If you have a fit result, set the guess parameters to the fit parameters. """ if self.results is None: print("No fit results to use! Run fit() first.") return # loop over the results and set the guess values for n in range(len(self._pguess)): self._pguess[n] = self.results[0][n] if self['autoplot']: self.plot() return self
[ "def", "set_guess_to_fit_result", "(", "self", ")", ":", "if", "self", ".", "results", "is", "None", ":", "print", "(", "\"No fit results to use! Run fit() first.\"", ")", "return", "# loop over the results and set the guess values", "for", "n", "in", "range", "(", "l...
If you have a fit result, set the guess parameters to the fit parameters.
[ "If", "you", "have", "a", "fit", "result", "set", "the", "guess", "parameters", "to", "the", "fit", "parameters", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2080-L2094
train
39,638
Spinmob/spinmob
_data.py
fitter._massage_data
def _massage_data(self): """ Processes the data and stores it. """ self._xdata_massaged, self._ydata_massaged, self._eydata_massaged = self.get_processed_data() # # Create the odr data. # self._odr_datas = [] # for n in range(len(self._xdata_massaged)): # # Only exdata can be None; make sure it's zeros at least. # ex = self._exdata_massaged[n] # if ex == None: ex = _n.zeros(len(self._eydata_massaged[n])) # self._odr_datas.append(_odr.RealData(self._xdata_massaged[n], # self._ydata_massaged[n], # sx=ex, # sy=self._eydata_massaged[n])) return self
python
def _massage_data(self): """ Processes the data and stores it. """ self._xdata_massaged, self._ydata_massaged, self._eydata_massaged = self.get_processed_data() # # Create the odr data. # self._odr_datas = [] # for n in range(len(self._xdata_massaged)): # # Only exdata can be None; make sure it's zeros at least. # ex = self._exdata_massaged[n] # if ex == None: ex = _n.zeros(len(self._eydata_massaged[n])) # self._odr_datas.append(_odr.RealData(self._xdata_massaged[n], # self._ydata_massaged[n], # sx=ex, # sy=self._eydata_massaged[n])) return self
[ "def", "_massage_data", "(", "self", ")", ":", "self", ".", "_xdata_massaged", ",", "self", ".", "_ydata_massaged", ",", "self", ".", "_eydata_massaged", "=", "self", ".", "get_processed_data", "(", ")", "# # Create the odr data.", "# self._odr_datas = [...
Processes the data and stores it.
[ "Processes", "the", "data", "and", "stores", "it", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2190-L2206
train
39,639
Spinmob/spinmob
_data.py
fitter.free
def free(self, *args, **kwargs): """ Turns a constant into a parameter. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time. """ # first set all the keyword argument values self.set(**kwargs) # get everything into one big list cnames = list(args) + list(kwargs.keys()) # move each pname to the constants for cname in cnames: if not cname in self._cnames: self._error("Naughty. '"+cname+"' is not a valid constant name.") else: n = self._cnames.index(cname) # make the switcheroo if type(self._pnames) is not list: self._pnames = list(self._pnames) if type(self._pguess) is not list: self._pguess = list(self._pguess) if type(self._cnames) is not list: self._cnames = list(self._cnames) if type(self._constants) is not list: self._constants = list(self._constants) self._pnames.append(self._cnames.pop(n)) self._pguess.append(self._constants.pop(n)) # update self._update_functions() return self
python
def free(self, *args, **kwargs): """ Turns a constant into a parameter. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time. """ # first set all the keyword argument values self.set(**kwargs) # get everything into one big list cnames = list(args) + list(kwargs.keys()) # move each pname to the constants for cname in cnames: if not cname in self._cnames: self._error("Naughty. '"+cname+"' is not a valid constant name.") else: n = self._cnames.index(cname) # make the switcheroo if type(self._pnames) is not list: self._pnames = list(self._pnames) if type(self._pguess) is not list: self._pguess = list(self._pguess) if type(self._cnames) is not list: self._cnames = list(self._cnames) if type(self._constants) is not list: self._constants = list(self._constants) self._pnames.append(self._cnames.pop(n)) self._pguess.append(self._constants.pop(n)) # update self._update_functions() return self
[ "def", "free", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# first set all the keyword argument values", "self", ".", "set", "(", "*", "*", "kwargs", ")", "# get everything into one big list", "cnames", "=", "list", "(", "args", ")", "...
Turns a constant into a parameter. As arguments, parameters must be strings. As keyword arguments, they can be set at the same time.
[ "Turns", "a", "constant", "into", "a", "parameter", ".", "As", "arguments", "parameters", "must", "be", "strings", ".", "As", "keyword", "arguments", "they", "can", "be", "set", "at", "the", "same", "time", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2290-L2321
train
39,640
Spinmob/spinmob
_data.py
fitter._evaluate_f
def _evaluate_f(self, n, xdata, p=None): """ Evaluates a single function n for arbitrary xdata and p tuple. p=None means use the fit results """ # by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess # assemble the arguments for the function args = (xdata,) + tuple(p) # evaluate this function. return self.f[n](*args)
python
def _evaluate_f(self, n, xdata, p=None): """ Evaluates a single function n for arbitrary xdata and p tuple. p=None means use the fit results """ # by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess # assemble the arguments for the function args = (xdata,) + tuple(p) # evaluate this function. return self.f[n](*args)
[ "def", "_evaluate_f", "(", "self", ",", "n", ",", "xdata", ",", "p", "=", "None", ")", ":", "# by default, use the fit values, otherwise, use the guess values.", "if", "p", "is", "None", "and", "self", ".", "results", "is", "not", "None", ":", "p", "=", "sel...
Evaluates a single function n for arbitrary xdata and p tuple. p=None means use the fit results
[ "Evaluates", "a", "single", "function", "n", "for", "arbitrary", "xdata", "and", "p", "tuple", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2345-L2359
train
39,641
Spinmob/spinmob
_data.py
fitter._evaluate_bg
def _evaluate_bg(self, n, xdata, p=None): """ Evaluates a single background function n for arbitrary xdata and p tuple. p=None means use the fit results """ # by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess # return None if there is no background function if self.bg[n] is None: return None # assemble the arguments for the function args = (xdata,) + tuple(p) # evaluate the function return self.bg[n](*args)
python
def _evaluate_bg(self, n, xdata, p=None): """ Evaluates a single background function n for arbitrary xdata and p tuple. p=None means use the fit results """ # by default, use the fit values, otherwise, use the guess values. if p is None and self.results is not None: p = self.results[0] elif p is None and self.results is None: p = self._pguess # return None if there is no background function if self.bg[n] is None: return None # assemble the arguments for the function args = (xdata,) + tuple(p) # evaluate the function return self.bg[n](*args)
[ "def", "_evaluate_bg", "(", "self", ",", "n", ",", "xdata", ",", "p", "=", "None", ")", ":", "# by default, use the fit values, otherwise, use the guess values.", "if", "p", "is", "None", "and", "self", ".", "results", "is", "not", "None", ":", "p", "=", "se...
Evaluates a single background function n for arbitrary xdata and p tuple. p=None means use the fit results
[ "Evaluates", "a", "single", "background", "function", "n", "for", "arbitrary", "xdata", "and", "p", "tuple", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2361-L2378
train
39,642
Spinmob/spinmob
_data.py
fitter.chi_squareds
def chi_squareds(self, p=None): """ Returns a list of chi squared for each data set. Also uses ydata_massaged. p=None means use the fit results """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] # get the residuals rs = self.studentized_residuals(p) # Handle the none case if rs == None: return None # square em and sum em. cs = [] for r in rs: cs.append(sum(r**2)) return cs
python
def chi_squareds(self, p=None): """ Returns a list of chi squared for each data set. Also uses ydata_massaged. p=None means use the fit results """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] # get the residuals rs = self.studentized_residuals(p) # Handle the none case if rs == None: return None # square em and sum em. cs = [] for r in rs: cs.append(sum(r**2)) return cs
[ "def", "chi_squareds", "(", "self", ",", "p", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":", "return", "None", "if", "p", "is", "None", ":", ...
Returns a list of chi squared for each data set. Also uses ydata_massaged. p=None means use the fit results
[ "Returns", "a", "list", "of", "chi", "squared", "for", "each", "data", "set", ".", "Also", "uses", "ydata_massaged", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2449-L2468
train
39,643
Spinmob/spinmob
_data.py
fitter.degrees_of_freedom
def degrees_of_freedom(self): """ Returns the number of degrees of freedom. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None # Temporary hack: get the studentized residuals, which uses the massaged data # This should later be changed to get_massaged_data() r = self.studentized_residuals() # Happens if data / functions not defined if r == None: return # calculate the number of points N = 0.0 for i in range(len(r)): N += len(r[i]) return N-len(self._pnames)
python
def degrees_of_freedom(self): """ Returns the number of degrees of freedom. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None # Temporary hack: get the studentized residuals, which uses the massaged data # This should later be changed to get_massaged_data() r = self.studentized_residuals() # Happens if data / functions not defined if r == None: return # calculate the number of points N = 0.0 for i in range(len(r)): N += len(r[i]) return N-len(self._pnames)
[ "def", "degrees_of_freedom", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":", "return", "None", "# Temporary hack: get the studentized residuals, which uses the ...
Returns the number of degrees of freedom.
[ "Returns", "the", "number", "of", "degrees", "of", "freedom", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2481-L2498
train
39,644
Spinmob/spinmob
_data.py
fitter.reduced_chi_squareds
def reduced_chi_squareds(self, p=None): """ Returns the reduced chi squared for each massaged data set. p=None means use the fit results. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] r = self.studentized_residuals(p) # In case it's not possible to calculate if r is None: return # calculate the number of points N = 0 for i in range(len(r)): N += len(r[i]) # degrees of freedom dof_per_point = self.degrees_of_freedom()/N for n in range(len(r)): r[n] = sum(r[n]**2)/(len(r[n])*dof_per_point) return r
python
def reduced_chi_squareds(self, p=None): """ Returns the reduced chi squared for each massaged data set. p=None means use the fit results. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] r = self.studentized_residuals(p) # In case it's not possible to calculate if r is None: return # calculate the number of points N = 0 for i in range(len(r)): N += len(r[i]) # degrees of freedom dof_per_point = self.degrees_of_freedom()/N for n in range(len(r)): r[n] = sum(r[n]**2)/(len(r[n])*dof_per_point) return r
[ "def", "reduced_chi_squareds", "(", "self", ",", "p", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":", "return", "None", "if", "p", "is", "None", ...
Returns the reduced chi squared for each massaged data set. p=None means use the fit results.
[ "Returns", "the", "reduced", "chi", "squared", "for", "each", "massaged", "data", "set", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2502-L2526
train
39,645
Spinmob/spinmob
_data.py
fitter.reduced_chi_squared
def reduced_chi_squared(self, p=None): """ Returns the reduced chi squared for all massaged data sets. p=None means use the fit results. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] chi2 = self.chi_squared(p) dof = self.degrees_of_freedom() if not _s.fun.is_a_number(chi2) or not _s.fun.is_a_number(dof): return None return _n.divide(self.chi_squared(p), self.degrees_of_freedom())
python
def reduced_chi_squared(self, p=None): """ Returns the reduced chi squared for all massaged data sets. p=None means use the fit results. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] chi2 = self.chi_squared(p) dof = self.degrees_of_freedom() if not _s.fun.is_a_number(chi2) or not _s.fun.is_a_number(dof): return None return _n.divide(self.chi_squared(p), self.degrees_of_freedom())
[ "def", "reduced_chi_squared", "(", "self", ",", "p", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":", "return", "None", "if", "p", "is", "None", ...
Returns the reduced chi squared for all massaged data sets. p=None means use the fit results.
[ "Returns", "the", "reduced", "chi", "squared", "for", "all", "massaged", "data", "sets", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2528-L2543
train
39,646
Spinmob/spinmob
_data.py
fitter.autoscale_eydata
def autoscale_eydata(self): """ Rescales the error so the next fit will give reduced chi squareds of 1. Each data set will be scaled independently, and you may wish to run this a few times until it converges. """ if not self.results: self._error("You must complete a fit first.") return r = self.reduced_chi_squareds() # loop over the eydata and rescale for n in range(len(r)): self["scale_eydata"][n] *= _n.sqrt(r[n]) # the fit is no longer valid self.clear_results() # replot if self['autoplot']: self.plot() return self
python
def autoscale_eydata(self): """ Rescales the error so the next fit will give reduced chi squareds of 1. Each data set will be scaled independently, and you may wish to run this a few times until it converges. """ if not self.results: self._error("You must complete a fit first.") return r = self.reduced_chi_squareds() # loop over the eydata and rescale for n in range(len(r)): self["scale_eydata"][n] *= _n.sqrt(r[n]) # the fit is no longer valid self.clear_results() # replot if self['autoplot']: self.plot() return self
[ "def", "autoscale_eydata", "(", "self", ")", ":", "if", "not", "self", ".", "results", ":", "self", ".", "_error", "(", "\"You must complete a fit first.\"", ")", "return", "r", "=", "self", ".", "reduced_chi_squareds", "(", ")", "# loop over the eydata and rescal...
Rescales the error so the next fit will give reduced chi squareds of 1. Each data set will be scaled independently, and you may wish to run this a few times until it converges.
[ "Rescales", "the", "error", "so", "the", "next", "fit", "will", "give", "reduced", "chi", "squareds", "of", "1", ".", "Each", "data", "set", "will", "be", "scaled", "independently", "and", "you", "may", "wish", "to", "run", "this", "a", "few", "times", ...
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2545-L2566
train
39,647
Spinmob/spinmob
_data.py
fitter.trim
def trim(self, n='all', x=True, y=True): """ This will set xmin and xmax based on the current zoom-level of the figures. n='all' Which figure to use for setting xmin and xmax. 'all' means all figures. You may also specify a list. x=True Trim the x-range y=True Trim the y-range """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to trimming.") return if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(self._set_xdata))) # loop over the specified plots for i in n: try: if x: xmin, xmax = _p.figure(self['first_figure']+i).axes[1].get_xlim() self['xmin'][i] = xmin self['xmax'][i] = xmax if y: ymin, ymax = _p.figure(self['first_figure']+i).axes[1].get_ylim() self['ymin'][i] = ymin self['ymax'][i] = ymax except: self._error("Data "+str(i)+" is not currently plotted.") # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
python
def trim(self, n='all', x=True, y=True): """ This will set xmin and xmax based on the current zoom-level of the figures. n='all' Which figure to use for setting xmin and xmax. 'all' means all figures. You may also specify a list. x=True Trim the x-range y=True Trim the y-range """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to trimming.") return if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(self._set_xdata))) # loop over the specified plots for i in n: try: if x: xmin, xmax = _p.figure(self['first_figure']+i).axes[1].get_xlim() self['xmin'][i] = xmin self['xmax'][i] = xmax if y: ymin, ymax = _p.figure(self['first_figure']+i).axes[1].get_ylim() self['ymin'][i] = ymin self['ymax'][i] = ymax except: self._error("Data "+str(i)+" is not currently plotted.") # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
[ "def", "trim", "(", "self", ",", "n", "=", "'all'", ",", "x", "=", "True", ",", "y", "=", "True", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":", "self",...
This will set xmin and xmax based on the current zoom-level of the figures. n='all' Which figure to use for setting xmin and xmax. 'all' means all figures. You may also specify a list. x=True Trim the x-range y=True Trim the y-range
[ "This", "will", "set", "xmin", "and", "xmax", "based", "on", "the", "current", "zoom", "-", "level", "of", "the", "figures", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2872-L2909
train
39,648
Spinmob/spinmob
_data.py
fitter.zoom
def zoom(self, n='all', xfactor=2.0, yfactor=2.0): """ This will scale the chosen data set's plot range by the specified xfactor and yfactor, respectively, and set the trim limits xmin, xmax, ymin, ymax accordingly Parameters ---------- n='all' Which data set to perform this action upon. 'all' means all data sets, or you can specify a list. xfactor=2.0 Factor by which to scale the x range. yfactor=2.0 Factor by which to scale the y range. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to zooming.") return # get the data xdata, ydata, eydata = self.get_data() if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(xdata))) # loop over the specified plots for i in n: fig = self['first_figure']+i try: xmin, xmax = _p.figure(fig).axes[1].get_xlim() xc = 0.5*(xmin+xmax) xs = 0.5*abs(xmax-xmin) self['xmin'][i] = xc - xfactor*xs self['xmax'][i] = xc + xfactor*xs ymin, ymax = _p.figure(fig).axes[1].get_ylim() yc = 0.5*(ymin+ymax) ys = 0.5*abs(ymax-ymin) self['ymin'][i] = yc - yfactor*ys self['ymax'][i] = yc + yfactor*ys except: self._error("Data "+str(fig)+" is not currently plotted.") # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
python
def zoom(self, n='all', xfactor=2.0, yfactor=2.0): """ This will scale the chosen data set's plot range by the specified xfactor and yfactor, respectively, and set the trim limits xmin, xmax, ymin, ymax accordingly Parameters ---------- n='all' Which data set to perform this action upon. 'all' means all data sets, or you can specify a list. xfactor=2.0 Factor by which to scale the x range. yfactor=2.0 Factor by which to scale the y range. """ if len(self._set_xdata)==0 or len(self._set_ydata)==0: self._error("No data. Please use set_data() and plot() prior to zooming.") return # get the data xdata, ydata, eydata = self.get_data() if _s.fun.is_a_number(n): n = [n] elif isinstance(n,str): n = list(range(len(xdata))) # loop over the specified plots for i in n: fig = self['first_figure']+i try: xmin, xmax = _p.figure(fig).axes[1].get_xlim() xc = 0.5*(xmin+xmax) xs = 0.5*abs(xmax-xmin) self['xmin'][i] = xc - xfactor*xs self['xmax'][i] = xc + xfactor*xs ymin, ymax = _p.figure(fig).axes[1].get_ylim() yc = 0.5*(ymin+ymax) ys = 0.5*abs(ymax-ymin) self['ymin'][i] = yc - yfactor*ys self['ymax'][i] = yc + yfactor*ys except: self._error("Data "+str(fig)+" is not currently plotted.") # now show the update. self.clear_results() if self['autoplot']: self.plot() return self
[ "def", "zoom", "(", "self", ",", "n", "=", "'all'", ",", "xfactor", "=", "2.0", ",", "yfactor", "=", "2.0", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":",...
This will scale the chosen data set's plot range by the specified xfactor and yfactor, respectively, and set the trim limits xmin, xmax, ymin, ymax accordingly Parameters ---------- n='all' Which data set to perform this action upon. 'all' means all data sets, or you can specify a list. xfactor=2.0 Factor by which to scale the x range. yfactor=2.0 Factor by which to scale the y range.
[ "This", "will", "scale", "the", "chosen", "data", "set", "s", "plot", "range", "by", "the", "specified", "xfactor", "and", "yfactor", "respectively", "and", "set", "the", "trim", "limits", "xmin", "xmax", "ymin", "ymax", "accordingly" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2940-L2988
train
39,649
Spinmob/spinmob
_data.py
fitter.ginput
def ginput(self, data_set=0, **kwargs): """ Pops up the figure for the specified data set. Returns value from pylab.ginput(). kwargs are sent to pylab.ginput() """ # this will temporarily fix the deprecation warning import warnings import matplotlib.cbook warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) _s.tweaks.raise_figure_window(data_set+self['first_figure']) return _p.ginput(**kwargs)
python
def ginput(self, data_set=0, **kwargs): """ Pops up the figure for the specified data set. Returns value from pylab.ginput(). kwargs are sent to pylab.ginput() """ # this will temporarily fix the deprecation warning import warnings import matplotlib.cbook warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) _s.tweaks.raise_figure_window(data_set+self['first_figure']) return _p.ginput(**kwargs)
[ "def", "ginput", "(", "self", ",", "data_set", "=", "0", ",", "*", "*", "kwargs", ")", ":", "# this will temporarily fix the deprecation warning", "import", "warnings", "import", "matplotlib", ".", "cbook", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ","...
Pops up the figure for the specified data set. Returns value from pylab.ginput(). kwargs are sent to pylab.ginput()
[ "Pops", "up", "the", "figure", "for", "the", "specified", "data", "set", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L2991-L3005
train
39,650
Spinmob/spinmob
_plotting_mess.py
_match_data_sets
def _match_data_sets(x,y): """ Makes sure everything is the same shape. "Intelligently". """ # Handle the None for x or y if x is None: # If x is none, y can be either [1,2] or [[1,2],[1,2]] if _fun.is_iterable(y[0]): # make an array of arrays to match x = [] for n in range(len(y)): x.append(list(range(len(y[n])))) else: x = list(range(len(y))) if y is None: # If x is none, y can be either [1,2] or [[1,2],[1,2]] if _fun.is_iterable(x[0]): # make an array of arrays to match y = [] for n in range(len(x)): y.append(list(range(len(x[n])))) else: y = list(range(len(x))) # At this point they should be matched, but may still be 1D # Default behavior: if all elements are numbers in both, assume they match if _fun.elements_are_numbers(x) and _fun.elements_are_numbers(y): x = [x] y = [y] # Second default behavior: shared array [1,2,3], [[1,2,1],[1,2,1]] or vis versa if _fun.elements_are_numbers(x) and not _fun.elements_are_numbers(y): x = [x]*len(y) if _fun.elements_are_numbers(y) and not _fun.elements_are_numbers(x): y = [y]*len(x) # Clean up any remaining Nones for n in range(len(x)): if x[n] is None: x[n] = list(range(len(y[n]))) if y[n] is None: y[n] = list(range(len(x[n]))) return x, y
python
def _match_data_sets(x,y): """ Makes sure everything is the same shape. "Intelligently". """ # Handle the None for x or y if x is None: # If x is none, y can be either [1,2] or [[1,2],[1,2]] if _fun.is_iterable(y[0]): # make an array of arrays to match x = [] for n in range(len(y)): x.append(list(range(len(y[n])))) else: x = list(range(len(y))) if y is None: # If x is none, y can be either [1,2] or [[1,2],[1,2]] if _fun.is_iterable(x[0]): # make an array of arrays to match y = [] for n in range(len(x)): y.append(list(range(len(x[n])))) else: y = list(range(len(x))) # At this point they should be matched, but may still be 1D # Default behavior: if all elements are numbers in both, assume they match if _fun.elements_are_numbers(x) and _fun.elements_are_numbers(y): x = [x] y = [y] # Second default behavior: shared array [1,2,3], [[1,2,1],[1,2,1]] or vis versa if _fun.elements_are_numbers(x) and not _fun.elements_are_numbers(y): x = [x]*len(y) if _fun.elements_are_numbers(y) and not _fun.elements_are_numbers(x): y = [y]*len(x) # Clean up any remaining Nones for n in range(len(x)): if x[n] is None: x[n] = list(range(len(y[n]))) if y[n] is None: y[n] = list(range(len(x[n]))) return x, y
[ "def", "_match_data_sets", "(", "x", ",", "y", ")", ":", "# Handle the None for x or y", "if", "x", "is", "None", ":", "# If x is none, y can be either [1,2] or [[1,2],[1,2]]", "if", "_fun", ".", "is_iterable", "(", "y", "[", "0", "]", ")", ":", "# make an array o...
Makes sure everything is the same shape. "Intelligently".
[ "Makes", "sure", "everything", "is", "the", "same", "shape", ".", "Intelligently", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L26-L64
train
39,651
Spinmob/spinmob
_plotting_mess.py
_match_error_to_data_set
def _match_error_to_data_set(x, ex): """ Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array. """ # Simplest case, ex is None or a number if not _fun.is_iterable(ex): # Just make a matched list of Nones if ex is None: ex = [ex]*len(x) # Make arrays of numbers if _fun.is_a_number(ex): value = ex # temporary storage ex = [] for n in range(len(x)): ex.append([value]*len(x[n])) # Otherwise, ex is iterable # Default behavior: If the elements are all numbers and the length matches # that of the first x-array, assume this is meant to match all the x # data sets if _fun.elements_are_numbers(ex) and len(ex) == len(x[0]): ex = [ex]*len(x) # The user may specify a list of some iterable and some not. Assume # in this case that at least the lists are the same length for n in range(len(x)): # do nothing to the None's # Inflate single numbers to match if _fun.is_a_number(ex[n]): ex[n] = [ex[n]]*len(x[n]) return ex
python
def _match_error_to_data_set(x, ex): """ Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array. """ # Simplest case, ex is None or a number if not _fun.is_iterable(ex): # Just make a matched list of Nones if ex is None: ex = [ex]*len(x) # Make arrays of numbers if _fun.is_a_number(ex): value = ex # temporary storage ex = [] for n in range(len(x)): ex.append([value]*len(x[n])) # Otherwise, ex is iterable # Default behavior: If the elements are all numbers and the length matches # that of the first x-array, assume this is meant to match all the x # data sets if _fun.elements_are_numbers(ex) and len(ex) == len(x[0]): ex = [ex]*len(x) # The user may specify a list of some iterable and some not. Assume # in this case that at least the lists are the same length for n in range(len(x)): # do nothing to the None's # Inflate single numbers to match if _fun.is_a_number(ex[n]): ex[n] = [ex[n]]*len(x[n]) return ex
[ "def", "_match_error_to_data_set", "(", "x", ",", "ex", ")", ":", "# Simplest case, ex is None or a number", "if", "not", "_fun", ".", "is_iterable", "(", "ex", ")", ":", "# Just make a matched list of Nones", "if", "ex", "is", "None", ":", "ex", "=", "[", "ex",...
Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array.
[ "Inflates", "ex", "to", "match", "the", "dimensionality", "of", "x", "intelligently", ".", "x", "is", "assumed", "to", "be", "a", "2D", "array", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L66-L98
train
39,652
Spinmob/spinmob
_plotting_mess.py
complex_data
def complex_data(data, edata=None, draw=True, **kwargs): """ Plots the imaginary vs real for complex data. Parameters ---------- data Array of complex data edata=None Array of complex error bars draw=True Draw the plot after it's assembled? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # generate the data the easy way try: rdata = _n.real(data) idata = _n.imag(data) if edata is None: erdata = None eidata = None else: erdata = _n.real(edata) eidata = _n.imag(edata) # generate the data the hard way. except: rdata = [] idata = [] if edata is None: erdata = None eidata = None else: erdata = [] eidata = [] for n in range(len(data)): rdata.append(_n.real(data[n])) idata.append(_n.imag(data[n])) if not edata is None: erdata.append(_n.real(edata[n])) eidata.append(_n.imag(edata[n])) if 'xlabel' not in kwargs: kwargs['xlabel'] = 'Real' if 'ylabel' not in kwargs: kwargs['ylabel'] = 'Imaginary' xy_data(rdata, idata, eidata, erdata, draw=False, **kwargs) if draw: _pylab.ion() _pylab.draw() _pylab.show()
python
def complex_data(data, edata=None, draw=True, **kwargs): """ Plots the imaginary vs real for complex data. Parameters ---------- data Array of complex data edata=None Array of complex error bars draw=True Draw the plot after it's assembled? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # generate the data the easy way try: rdata = _n.real(data) idata = _n.imag(data) if edata is None: erdata = None eidata = None else: erdata = _n.real(edata) eidata = _n.imag(edata) # generate the data the hard way. except: rdata = [] idata = [] if edata is None: erdata = None eidata = None else: erdata = [] eidata = [] for n in range(len(data)): rdata.append(_n.real(data[n])) idata.append(_n.imag(data[n])) if not edata is None: erdata.append(_n.real(edata[n])) eidata.append(_n.imag(edata[n])) if 'xlabel' not in kwargs: kwargs['xlabel'] = 'Real' if 'ylabel' not in kwargs: kwargs['ylabel'] = 'Imaginary' xy_data(rdata, idata, eidata, erdata, draw=False, **kwargs) if draw: _pylab.ion() _pylab.draw() _pylab.show()
[ "def", "complex_data", "(", "data", ",", "edata", "=", "None", ",", "draw", "=", "True", ",", "*", "*", "kwargs", ")", ":", "_pylab", ".", "ioff", "(", ")", "# generate the data the easy way", "try", ":", "rdata", "=", "_n", ".", "real", "(", "data", ...
Plots the imaginary vs real for complex data. Parameters ---------- data Array of complex data edata=None Array of complex error bars draw=True Draw the plot after it's assembled? See spinmob.plot.xy.data() for additional optional keyword arguments.
[ "Plots", "the", "imaginary", "vs", "real", "for", "complex", "data", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L103-L157
train
39,653
Spinmob/spinmob
_plotting_mess.py
complex_files
def complex_files(script='d[1]+1j*d[2]', escript=None, paths=None, **kwargs): """ Loads files and plots complex data in the real-imaginary plane. Parameters ---------- script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars paths=None List of paths to open. None means use a dialog See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ ds = _data.load_multiple(paths=paths) if len(ds) == 0: return if 'title' not in kwargs: kwargs['title'] = _os.path.split(ds[0].path)[0] return complex_databoxes(ds, script=script, **kwargs)
python
def complex_files(script='d[1]+1j*d[2]', escript=None, paths=None, **kwargs): """ Loads files and plots complex data in the real-imaginary plane. Parameters ---------- script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars paths=None List of paths to open. None means use a dialog See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ ds = _data.load_multiple(paths=paths) if len(ds) == 0: return if 'title' not in kwargs: kwargs['title'] = _os.path.split(ds[0].path)[0] return complex_databoxes(ds, script=script, **kwargs)
[ "def", "complex_files", "(", "script", "=", "'d[1]+1j*d[2]'", ",", "escript", "=", "None", ",", "paths", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ds", "=", "_data", ".", "load_multiple", "(", "paths", "=", "paths", ")", "if", "len", "(", "ds"...
Loads files and plots complex data in the real-imaginary plane. Parameters ---------- script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars paths=None List of paths to open. None means use a dialog See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
[ "Loads", "files", "and", "plots", "complex", "data", "in", "the", "real", "-", "imaginary", "plane", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L202-L230
train
39,654
Spinmob/spinmob
_plotting_mess.py
magphase_databoxes
def magphase_databoxes(ds, xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate data and plot the complex magnitude and phase versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=magphase_data, g=g, **kwargs)
python
def magphase_databoxes(ds, xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate data and plot the complex magnitude and phase versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=magphase_data, g=g, **kwargs)
[ "def", "magphase_databoxes", "(", "ds", ",", "xscript", "=", "0", ",", "yscript", "=", "'d[1]+1j*d[2]'", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "databoxes", "(", "ds", ","...
Use databoxes and scripts to generate data and plot the complex magnitude and phase versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
[ "Use", "databoxes", "and", "scripts", "to", "generate", "data", "and", "plot", "the", "complex", "magnitude", "and", "phase", "versus", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L358-L381
train
39,655
Spinmob/spinmob
_plotting_mess.py
magphase_files
def magphase_files(xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's magnitude and phase versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=magphase_databoxes, paths=paths, g=g, **kwargs)
python
def magphase_files(xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's magnitude and phase versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=magphase_databoxes, paths=paths, g=g, **kwargs)
[ "def", "magphase_files", "(", "xscript", "=", "0", ",", "yscript", "=", "'d[1]+1j*d[2]'", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "paths", "=", "None", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "file...
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's magnitude and phase versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
[ "This", "will", "load", "a", "bunch", "of", "data", "files", "generate", "data", "based", "on", "the", "supplied", "scripts", "and", "then", "plot", "the", "ydata", "s", "magnitude", "and", "phase", "versus", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L383-L412
train
39,656
Spinmob/spinmob
_plotting_mess.py
realimag_data
def realimag_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', rscale='linear', iscale='linear', rlabel='Real', ilabel='Imaginary', figure='gcf', clear=1, draw=True, **kwargs): """ Plots the real and imaginary parts of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis rscale='linear' 'log' or 'linear' scale of the real axis iscale='linear' 'log' or 'linear' scale of the imaginary axis rlabel='Magnitude' y-axis label for real value plot ilabel='Phase' y-axis label for imaginary value plot figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when completed? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # Make sure the dimensionality of the data sets matches xdata, ydata = _match_data_sets(xdata, ydata) exdata = _match_error_to_data_set(xdata, exdata) eydata = _match_error_to_data_set(ydata, eydata) # convert to real imag, and get error bars rdata = [] idata = [] erdata = [] eidata = [] for l in range(len(ydata)): rdata.append(_n.real(ydata[l])) idata.append(_n.imag(ydata[l])) if eydata[l] is None: erdata.append(None) eidata.append(None) else: erdata.append(_n.real(eydata[l])) eidata.append(_n.imag(eydata[l])) # set up the figure and axes if figure == 'gcf': f = _pylab.gcf() if clear: f.clear() axes1 = _pylab.subplot(211) axes2 = _pylab.subplot(212,sharex=axes1) if 'xlabel' in kwargs : xlabel=kwargs.pop('xlabel') else: xlabel='' if 'ylabel' in kwargs : kwargs.pop('ylabel') if 'tall' not in kwargs: kwargs['tall'] = False if 'autoformat' not in kwargs: kwargs['autoformat'] = True autoformat = kwargs['autoformat'] kwargs['autoformat'] = False kwargs['xlabel'] = '' xy_data(xdata, rdata, eydata=erdata, exdata=exdata, ylabel=rlabel, axes=axes1, clear=0, xscale=xscale, yscale=rscale, draw=False, **kwargs) kwargs['autoformat'] = autoformat kwargs['xlabel'] = xlabel xy_data(xdata, idata, eydata=eidata, exdata=exdata, ylabel=ilabel, axes=axes2, clear=0, xscale=xscale, yscale=iscale, draw=False, **kwargs) axes2.set_title('') if draw: _pylab.ion() _pylab.draw() _pylab.show()
python
def realimag_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', rscale='linear', iscale='linear', rlabel='Real', ilabel='Imaginary', figure='gcf', clear=1, draw=True, **kwargs): """ Plots the real and imaginary parts of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis rscale='linear' 'log' or 'linear' scale of the real axis iscale='linear' 'log' or 'linear' scale of the imaginary axis rlabel='Magnitude' y-axis label for real value plot ilabel='Phase' y-axis label for imaginary value plot figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when completed? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # Make sure the dimensionality of the data sets matches xdata, ydata = _match_data_sets(xdata, ydata) exdata = _match_error_to_data_set(xdata, exdata) eydata = _match_error_to_data_set(ydata, eydata) # convert to real imag, and get error bars rdata = [] idata = [] erdata = [] eidata = [] for l in range(len(ydata)): rdata.append(_n.real(ydata[l])) idata.append(_n.imag(ydata[l])) if eydata[l] is None: erdata.append(None) eidata.append(None) else: erdata.append(_n.real(eydata[l])) eidata.append(_n.imag(eydata[l])) # set up the figure and axes if figure == 'gcf': f = _pylab.gcf() if clear: f.clear() axes1 = _pylab.subplot(211) axes2 = _pylab.subplot(212,sharex=axes1) if 'xlabel' in kwargs : xlabel=kwargs.pop('xlabel') else: xlabel='' if 'ylabel' in kwargs : kwargs.pop('ylabel') if 'tall' not in kwargs: kwargs['tall'] = False if 'autoformat' not in kwargs: kwargs['autoformat'] = True autoformat = kwargs['autoformat'] kwargs['autoformat'] = False kwargs['xlabel'] = '' xy_data(xdata, rdata, eydata=erdata, exdata=exdata, ylabel=rlabel, axes=axes1, clear=0, xscale=xscale, yscale=rscale, draw=False, **kwargs) kwargs['autoformat'] = autoformat kwargs['xlabel'] = xlabel xy_data(xdata, idata, eydata=eidata, exdata=exdata, ylabel=ilabel, axes=axes2, clear=0, xscale=xscale, yscale=iscale, draw=False, **kwargs) axes2.set_title('') if draw: _pylab.ion() _pylab.draw() _pylab.show()
[ "def", "realimag_data", "(", "xdata", ",", "ydata", ",", "eydata", "=", "None", ",", "exdata", "=", "None", ",", "xscale", "=", "'linear'", ",", "rscale", "=", "'linear'", ",", "iscale", "=", "'linear'", ",", "rlabel", "=", "'Real'", ",", "ilabel", "="...
Plots the real and imaginary parts of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis rscale='linear' 'log' or 'linear' scale of the real axis iscale='linear' 'log' or 'linear' scale of the imaginary axis rlabel='Magnitude' y-axis label for real value plot ilabel='Phase' y-axis label for imaginary value plot figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when completed? See spinmob.plot.xy.data() for additional optional keyword arguments.
[ "Plots", "the", "real", "and", "imaginary", "parts", "of", "complex", "ydata", "vs", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L441-L524
train
39,657
Spinmob/spinmob
_plotting_mess.py
realimag_databoxes
def realimag_databoxes(ds, xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate data and plot the real and imaginary ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=realimag_data, g=g, **kwargs)
python
def realimag_databoxes(ds, xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate data and plot the real and imaginary ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=realimag_data, g=g, **kwargs)
[ "def", "realimag_databoxes", "(", "ds", ",", "xscript", "=", "0", ",", "yscript", "=", "\"d[1]+1j*d[2]\"", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "databoxes", "(", "ds", "...
Use databoxes and scripts to generate data and plot the real and imaginary ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
[ "Use", "databoxes", "and", "scripts", "to", "generate", "data", "and", "plot", "the", "real", "and", "imaginary", "ydata", "versus", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L527-L550
train
39,658
Spinmob/spinmob
_plotting_mess.py
realimag_files
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=realimag_databoxes, paths=paths, g=g, **kwargs)
python
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=realimag_databoxes, paths=paths, g=g, **kwargs)
[ "def", "realimag_files", "(", "xscript", "=", "0", ",", "yscript", "=", "\"d[1]+1j*d[2]\"", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "paths", "=", "None", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "fi...
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
[ "This", "will", "load", "a", "bunch", "of", "data", "files", "generate", "data", "based", "on", "the", "supplied", "scripts", "and", "then", "plot", "the", "ydata", "s", "real", "and", "imaginary", "parts", "versus", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L552-L580
train
39,659
Spinmob/spinmob
_plotting_mess.py
xy_databoxes
def xy_databoxes(ds, xscript=0, yscript='d[1]', eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate and plot ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=xy_data, g=g, **kwargs)
python
def xy_databoxes(ds, xscript=0, yscript='d[1]', eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate and plot ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=xy_data, g=g, **kwargs)
[ "def", "xy_databoxes", "(", "ds", ",", "xscript", "=", "0", ",", "yscript", "=", "'d[1]'", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "databoxes", "(", "ds", ",", "xscript",...
Use databoxes and scripts to generate and plot ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
[ "Use", "databoxes", "and", "scripts", "to", "generate", "and", "plot", "ydata", "versus", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L748-L771
train
39,660
Spinmob/spinmob
_plotting_mess.py
xy_files
def xy_files(xscript=0, yscript='d[1]', eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=xy_databoxes, paths=paths, g=g, **kwargs)
python
def xy_files(xscript=0, yscript='d[1]', eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=xy_databoxes, paths=paths, g=g, **kwargs)
[ "def", "xy_files", "(", "xscript", "=", "0", ",", "yscript", "=", "'d[1]'", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "paths", "=", "None", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "files", "(", "...
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog.
[ "This", "will", "load", "a", "bunch", "of", "data", "files", "generate", "data", "based", "on", "the", "supplied", "scripts", "and", "then", "plot", "the", "ydata", "versus", "xdata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L774-L803
train
39,661
Spinmob/spinmob
_plotting_mess.py
files
def files(xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_databoxes, paths=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot this data using the specified databox plotter. xscript, yscript, eyscript, exscript scripts to generate x, y, and errors g optional dictionary of globals optional: filters="*.*" to set the file filters for the dialog. **kwargs are sent to plotter() """ if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None if 'filters' in kwargs: filters = kwargs.pop('filters') else: filters = '*.*' ds = _data.load_multiple(paths=paths, delimiter=delimiter, filters=filters) if ds is None or len(ds) == 0: return # generate a default title (the directory) if 'title' not in kwargs: kwargs['title']=_os.path.split(ds[0].path)[0] # run the databox plotter plotter(ds, xscript=xscript, yscript=yscript, eyscript=eyscript, exscript=exscript, g=g, **kwargs) return ds
python
def files(xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_databoxes, paths=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot this data using the specified databox plotter. xscript, yscript, eyscript, exscript scripts to generate x, y, and errors g optional dictionary of globals optional: filters="*.*" to set the file filters for the dialog. **kwargs are sent to plotter() """ if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None if 'filters' in kwargs: filters = kwargs.pop('filters') else: filters = '*.*' ds = _data.load_multiple(paths=paths, delimiter=delimiter, filters=filters) if ds is None or len(ds) == 0: return # generate a default title (the directory) if 'title' not in kwargs: kwargs['title']=_os.path.split(ds[0].path)[0] # run the databox plotter plotter(ds, xscript=xscript, yscript=yscript, eyscript=eyscript, exscript=exscript, g=g, **kwargs) return ds
[ "def", "files", "(", "xscript", "=", "0", ",", "yscript", "=", "1", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "g", "=", "None", ",", "plotter", "=", "xy_databoxes", ",", "paths", "=", "None", ",", "*", "*", "kwargs", ")", "...
This will load a bunch of data files, generate data based on the supplied scripts, and then plot this data using the specified databox plotter. xscript, yscript, eyscript, exscript scripts to generate x, y, and errors g optional dictionary of globals optional: filters="*.*" to set the file filters for the dialog. **kwargs are sent to plotter()
[ "This", "will", "load", "a", "bunch", "of", "data", "files", "generate", "data", "based", "on", "the", "supplied", "scripts", "and", "then", "plot", "this", "data", "using", "the", "specified", "databox", "plotter", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L929-L956
train
39,662
Spinmob/spinmob
_plotting_mess.py
image_function
def image_function(f='sin(5*x)*cos(5*y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p='x,y', g=None, **kwargs): """ Plots a 2-d function over the specified range Parameters ---------- f='sin(5*x)*cos(5*y)' Takes two inputs and returns one value. Can also be a string function such as sin(x*y) xmin=-1, xmax=1, ymin=-1, ymax=1 Range over which to generate/plot the data xsteps=100, ysteps=100 How many points to plot on the specified range p='x,y' If using strings for functions, this is a string of parameters. g=None Optional additional globals. Try g=globals()! See spinmob.plot.image.data() for additional optional keyword arguments. """ default_kwargs = dict(clabel=str(f), xlabel='x', ylabel='y') default_kwargs.update(kwargs) # aggregate globals if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] if type(f) == str: f = eval('lambda ' + p + ': ' + f, g) # generate the grid x and y coordinates xones = _n.linspace(1,1,ysteps) x = _n.linspace(xmin, xmax, xsteps) xgrid = _n.outer(xones, x) yones = _n.linspace(1,1,xsteps) y = _n.linspace(ymin, ymax, ysteps) ygrid = _n.outer(y, yones) # now get the z-grid try: # try it the fast numpy way. Add 0 to assure dimensions zgrid = f(xgrid, ygrid) + xgrid*0.0 except: print("Notice: function is not rocking hardcore. Generating grid the slow way...") # manually loop over the data to generate the z-grid zgrid = [] for ny in range(0, len(y)): zgrid.append([]) for nx in range(0, len(x)): zgrid[ny].append(f(x[nx], y[ny])) zgrid = _n.array(zgrid) # now plot! image_data(zgrid.transpose(), x, y, **default_kwargs)
python
def image_function(f='sin(5*x)*cos(5*y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p='x,y', g=None, **kwargs): """ Plots a 2-d function over the specified range Parameters ---------- f='sin(5*x)*cos(5*y)' Takes two inputs and returns one value. Can also be a string function such as sin(x*y) xmin=-1, xmax=1, ymin=-1, ymax=1 Range over which to generate/plot the data xsteps=100, ysteps=100 How many points to plot on the specified range p='x,y' If using strings for functions, this is a string of parameters. g=None Optional additional globals. Try g=globals()! See spinmob.plot.image.data() for additional optional keyword arguments. """ default_kwargs = dict(clabel=str(f), xlabel='x', ylabel='y') default_kwargs.update(kwargs) # aggregate globals if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] if type(f) == str: f = eval('lambda ' + p + ': ' + f, g) # generate the grid x and y coordinates xones = _n.linspace(1,1,ysteps) x = _n.linspace(xmin, xmax, xsteps) xgrid = _n.outer(xones, x) yones = _n.linspace(1,1,xsteps) y = _n.linspace(ymin, ymax, ysteps) ygrid = _n.outer(y, yones) # now get the z-grid try: # try it the fast numpy way. Add 0 to assure dimensions zgrid = f(xgrid, ygrid) + xgrid*0.0 except: print("Notice: function is not rocking hardcore. Generating grid the slow way...") # manually loop over the data to generate the z-grid zgrid = [] for ny in range(0, len(y)): zgrid.append([]) for nx in range(0, len(x)): zgrid[ny].append(f(x[nx], y[ny])) zgrid = _n.array(zgrid) # now plot! image_data(zgrid.transpose(), x, y, **default_kwargs)
[ "def", "image_function", "(", "f", "=", "'sin(5*x)*cos(5*y)'", ",", "xmin", "=", "-", "1", ",", "xmax", "=", "1", ",", "ymin", "=", "-", "1", ",", "ymax", "=", "1", ",", "xsteps", "=", "100", ",", "ysteps", "=", "100", ",", "p", "=", "'x,y'", "...
Plots a 2-d function over the specified range Parameters ---------- f='sin(5*x)*cos(5*y)' Takes two inputs and returns one value. Can also be a string function such as sin(x*y) xmin=-1, xmax=1, ymin=-1, ymax=1 Range over which to generate/plot the data xsteps=100, ysteps=100 How many points to plot on the specified range p='x,y' If using strings for functions, this is a string of parameters. g=None Optional additional globals. Try g=globals()! See spinmob.plot.image.data() for additional optional keyword arguments.
[ "Plots", "a", "2", "-", "d", "function", "over", "the", "specified", "range" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L1106-L1164
train
39,663
Spinmob/spinmob
_plotting_mess.py
image_file
def image_file(path=None, zscript='self[1:]', xscript='[0,1]', yscript='d[0]', g=None, **kwargs): """ Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xscript='[0,1]', yscript='d[0]' Determine the x and y arrays used for setting the axes bounds g=None Optional dictionary of globals for the scripts See spinmob.plot.image.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None d = _data.load(paths=path, delimiter = delimiter) if d is None or len(d) == 0: return # allows the user to overwrite the defaults default_kwargs = dict(xlabel = str(xscript), ylabel = str(yscript), title = d.path, clabel = str(zscript)) default_kwargs.update(kwargs) # get the data X = d(xscript, g) Y = d(yscript, g) Z = _n.array(d(zscript, g)) # Z = Z.transpose() # plot! image_data(Z, X, Y, **default_kwargs)
python
def image_file(path=None, zscript='self[1:]', xscript='[0,1]', yscript='d[0]', g=None, **kwargs): """ Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xscript='[0,1]', yscript='d[0]' Determine the x and y arrays used for setting the axes bounds g=None Optional dictionary of globals for the scripts See spinmob.plot.image.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None d = _data.load(paths=path, delimiter = delimiter) if d is None or len(d) == 0: return # allows the user to overwrite the defaults default_kwargs = dict(xlabel = str(xscript), ylabel = str(yscript), title = d.path, clabel = str(zscript)) default_kwargs.update(kwargs) # get the data X = d(xscript, g) Y = d(yscript, g) Z = _n.array(d(zscript, g)) # Z = Z.transpose() # plot! image_data(Z, X, Y, **default_kwargs)
[ "def", "image_file", "(", "path", "=", "None", ",", "zscript", "=", "'self[1:]'", ",", "xscript", "=", "'[0,1]'", ",", "yscript", "=", "'d[0]'", ",", "g", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'delimiter'", "in", "kwargs", ":", "deli...
Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xscript='[0,1]', yscript='d[0]' Determine the x and y arrays used for setting the axes bounds g=None Optional dictionary of globals for the scripts See spinmob.plot.image.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts.
[ "Loads", "an", "data", "file", "and", "plots", "it", "with", "color", ".", "Data", "file", "must", "have", "columns", "of", "the", "same", "length!" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L1167-L1207
train
39,664
Spinmob/spinmob
_plotting_mess.py
parametric_function
def parametric_function(fx='sin(t)', fy='cos(t)', tmin=-1, tmax=1, steps=200, p='t', g=None, erange=False, **kwargs): """ Plots the parametric function over the specified range Parameters ---------- fx='sin(t)', fy='cos(t)' Functions or (matching) lists of functions to plot; can be string functions or python functions taking one argument tmin=-1, tmax=1, steps=200 Range over which to plot, and how many points to plot p='t' If using strings for functions, p is the parameter name g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the t data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] # if the x-axis is a log scale, use erange if erange: r = _fun.erange(tmin, tmax, steps) else: r = _n.linspace(tmin, tmax, steps) # make sure it's a list so we can loop over it if not type(fy) in [type([]), type(())]: fy = [fy] if not type(fx) in [type([]), type(())]: fx = [fx] # loop over the list of functions xdatas = [] ydatas = [] labels = [] for fs in fx: if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs x = [] for z in r: x.append(a(z)) xdatas.append(x) labels.append(a.__name__) for n in range(len(fy)): fs = fy[n] if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs y = [] for z in r: y.append(a(z)) ydatas.append(y) labels[n] = labels[n]+', '+a.__name__ # plot! xy_data(xdatas, ydatas, label=labels, **kwargs)
python
def parametric_function(fx='sin(t)', fy='cos(t)', tmin=-1, tmax=1, steps=200, p='t', g=None, erange=False, **kwargs): """ Plots the parametric function over the specified range Parameters ---------- fx='sin(t)', fy='cos(t)' Functions or (matching) lists of functions to plot; can be string functions or python functions taking one argument tmin=-1, tmax=1, steps=200 Range over which to plot, and how many points to plot p='t' If using strings for functions, p is the parameter name g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the t data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] # if the x-axis is a log scale, use erange if erange: r = _fun.erange(tmin, tmax, steps) else: r = _n.linspace(tmin, tmax, steps) # make sure it's a list so we can loop over it if not type(fy) in [type([]), type(())]: fy = [fy] if not type(fx) in [type([]), type(())]: fx = [fx] # loop over the list of functions xdatas = [] ydatas = [] labels = [] for fs in fx: if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs x = [] for z in r: x.append(a(z)) xdatas.append(x) labels.append(a.__name__) for n in range(len(fy)): fs = fy[n] if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs y = [] for z in r: y.append(a(z)) ydatas.append(y) labels[n] = labels[n]+', '+a.__name__ # plot! xy_data(xdatas, ydatas, label=labels, **kwargs)
[ "def", "parametric_function", "(", "fx", "=", "'sin(t)'", ",", "fy", "=", "'cos(t)'", ",", "tmin", "=", "-", "1", ",", "tmax", "=", "1", ",", "steps", "=", "200", ",", "p", "=", "'t'", ",", "g", "=", "None", ",", "erange", "=", "False", ",", "*...
Plots the parametric function over the specified range Parameters ---------- fx='sin(t)', fy='cos(t)' Functions or (matching) lists of functions to plot; can be string functions or python functions taking one argument tmin=-1, tmax=1, steps=200 Range over which to plot, and how many points to plot p='t' If using strings for functions, p is the parameter name g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the t data? See spinmob.plot.xy.data() for additional optional keyword arguments.
[ "Plots", "the", "parametric", "function", "over", "the", "specified", "range" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L1213-L1279
train
39,665
Spinmob/spinmob
_plotting_mess.py
plot_style_cycle.reset
def reset(self): """ Resets the style cycle. """ for key in list(self.keys()): self.iterators[key] = _itertools.cycle(self[key]) return self
python
def reset(self): """ Resets the style cycle. """ for key in list(self.keys()): self.iterators[key] = _itertools.cycle(self[key]) return self
[ "def", "reset", "(", "self", ")", ":", "for", "key", "in", "list", "(", "self", ".", "keys", "(", ")", ")", ":", "self", ".", "iterators", "[", "key", "]", "=", "_itertools", ".", "cycle", "(", "self", "[", "key", "]", ")", "return", "self" ]
Resets the style cycle.
[ "Resets", "the", "style", "cycle", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_plotting_mess.py#L1320-L1325
train
39,666
Spinmob/spinmob
_pylab_tweaks.py
add_text
def add_text(text, x=0.01, y=0.01, axes="gca", draw=True, **kwargs): """ Adds text to the axes at the specified position. **kwargs go to the axes.text() function. """ if axes=="gca": axes = _pylab.gca() axes.text(x, y, text, transform=axes.transAxes, **kwargs) if draw: _pylab.draw()
python
def add_text(text, x=0.01, y=0.01, axes="gca", draw=True, **kwargs): """ Adds text to the axes at the specified position. **kwargs go to the axes.text() function. """ if axes=="gca": axes = _pylab.gca() axes.text(x, y, text, transform=axes.transAxes, **kwargs) if draw: _pylab.draw()
[ "def", "add_text", "(", "text", ",", "x", "=", "0.01", ",", "y", "=", "0.01", ",", "axes", "=", "\"gca\"", ",", "draw", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "axes", "==", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ...
Adds text to the axes at the specified position. **kwargs go to the axes.text() function.
[ "Adds", "text", "to", "the", "axes", "at", "the", "specified", "position", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L36-L44
train
39,667
Spinmob/spinmob
_pylab_tweaks.py
auto_zoom
def auto_zoom(zoomx=True, zoomy=True, axes="gca", x_space=0.04, y_space=0.04, draw=True): """ Looks at the bounds of the plotted data and zooms accordingly, leaving some space around the data. """ # Disable auto-updating by default. _pylab.ioff() if axes=="gca": axes = _pylab.gca() # get the current bounds x10, x20 = axes.get_xlim() y10, y20 = axes.get_ylim() # Autoscale using pylab's technique (catches the error bars!) axes.autoscale(enable=True, tight=True) # Add padding if axes.get_xscale() == 'linear': x1, x2 = axes.get_xlim() xc = 0.5*(x1+x2) xs = 0.5*(1+x_space)*(x2-x1) axes.set_xlim(xc-xs, xc+xs) if axes.get_yscale() == 'linear': y1, y2 = axes.get_ylim() yc = 0.5*(y1+y2) ys = 0.5*(1+y_space)*(y2-y1) axes.set_ylim(yc-ys, yc+ys) # If we weren't supposed to zoom x or y, reset them if not zoomx: axes.set_xlim(x10, x20) if not zoomy: axes.set_ylim(y10, y20) if draw: _pylab.ion() _pylab.draw()
python
def auto_zoom(zoomx=True, zoomy=True, axes="gca", x_space=0.04, y_space=0.04, draw=True): """ Looks at the bounds of the plotted data and zooms accordingly, leaving some space around the data. """ # Disable auto-updating by default. _pylab.ioff() if axes=="gca": axes = _pylab.gca() # get the current bounds x10, x20 = axes.get_xlim() y10, y20 = axes.get_ylim() # Autoscale using pylab's technique (catches the error bars!) axes.autoscale(enable=True, tight=True) # Add padding if axes.get_xscale() == 'linear': x1, x2 = axes.get_xlim() xc = 0.5*(x1+x2) xs = 0.5*(1+x_space)*(x2-x1) axes.set_xlim(xc-xs, xc+xs) if axes.get_yscale() == 'linear': y1, y2 = axes.get_ylim() yc = 0.5*(y1+y2) ys = 0.5*(1+y_space)*(y2-y1) axes.set_ylim(yc-ys, yc+ys) # If we weren't supposed to zoom x or y, reset them if not zoomx: axes.set_xlim(x10, x20) if not zoomy: axes.set_ylim(y10, y20) if draw: _pylab.ion() _pylab.draw()
[ "def", "auto_zoom", "(", "zoomx", "=", "True", ",", "zoomy", "=", "True", ",", "axes", "=", "\"gca\"", ",", "x_space", "=", "0.04", ",", "y_space", "=", "0.04", ",", "draw", "=", "True", ")", ":", "# Disable auto-updating by default.", "_pylab", ".", "io...
Looks at the bounds of the plotted data and zooms accordingly, leaving some space around the data.
[ "Looks", "at", "the", "bounds", "of", "the", "plotted", "data", "and", "zooms", "accordingly", "leaving", "some", "space", "around", "the", "data", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L46-L83
train
39,668
Spinmob/spinmob
_pylab_tweaks.py
click_estimate_slope
def click_estimate_slope(): """ Takes two clicks and returns the slope. Right-click aborts. """ c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])
python
def click_estimate_slope(): """ Takes two clicks and returns the slope. Right-click aborts. """ c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])
[ "def", "click_estimate_slope", "(", ")", ":", "c1", "=", "_pylab", ".", "ginput", "(", ")", "if", "len", "(", "c1", ")", "==", "0", ":", "return", "None", "c2", "=", "_pylab", ".", "ginput", "(", ")", "if", "len", "(", "c2", ")", "==", "0", ":"...
Takes two clicks and returns the slope. Right-click aborts.
[ "Takes", "two", "clicks", "and", "returns", "the", "slope", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L133-L148
train
39,669
Spinmob/spinmob
_pylab_tweaks.py
click_estimate_curvature
def click_estimate_curvature(): """ Takes two clicks and returns the curvature, assuming the first click was the minimum of a parabola and the second was some other point. Returns the second derivative of the function giving this parabola. Right-click aborts. """ c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return 2*(c2[0][1]-c1[0][1])/(c2[0][0]-c1[0][0])**2
python
def click_estimate_curvature(): """ Takes two clicks and returns the curvature, assuming the first click was the minimum of a parabola and the second was some other point. Returns the second derivative of the function giving this parabola. Right-click aborts. """ c1 = _pylab.ginput() if len(c1)==0: return None c2 = _pylab.ginput() if len(c2)==0: return None return 2*(c2[0][1]-c1[0][1])/(c2[0][0]-c1[0][0])**2
[ "def", "click_estimate_curvature", "(", ")", ":", "c1", "=", "_pylab", ".", "ginput", "(", ")", "if", "len", "(", "c1", ")", "==", "0", ":", "return", "None", "c2", "=", "_pylab", ".", "ginput", "(", ")", "if", "len", "(", "c2", ")", "==", "0", ...
Takes two clicks and returns the curvature, assuming the first click was the minimum of a parabola and the second was some other point. Returns the second derivative of the function giving this parabola. Right-click aborts.
[ "Takes", "two", "clicks", "and", "returns", "the", "curvature", "assuming", "the", "first", "click", "was", "the", "minimum", "of", "a", "parabola", "and", "the", "second", "was", "some", "other", "point", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L150-L168
train
39,670
Spinmob/spinmob
_pylab_tweaks.py
copy_figure_to_clipboard
def copy_figure_to_clipboard(figure='gcf'): """ Copies the specified figure to the system clipboard. Specifying 'gcf' will use the current figure. """ try: import pyqtgraph as _p # Get the current figure if necessary if figure is 'gcf': figure = _s.pylab.gcf() # Store the figure as an image path = _os.path.join(_s.settings.path_home, "clipboard.png") figure.savefig(path) # Set the clipboard. I know, it's weird to use pyqtgraph, but # This covers both Qt4 and Qt5 with their Qt4 wrapper! _p.QtGui.QApplication.instance().clipboard().setImage(_p.QtGui.QImage(path)) except: print("This function currently requires pyqtgraph to be installed.")
python
def copy_figure_to_clipboard(figure='gcf'): """ Copies the specified figure to the system clipboard. Specifying 'gcf' will use the current figure. """ try: import pyqtgraph as _p # Get the current figure if necessary if figure is 'gcf': figure = _s.pylab.gcf() # Store the figure as an image path = _os.path.join(_s.settings.path_home, "clipboard.png") figure.savefig(path) # Set the clipboard. I know, it's weird to use pyqtgraph, but # This covers both Qt4 and Qt5 with their Qt4 wrapper! _p.QtGui.QApplication.instance().clipboard().setImage(_p.QtGui.QImage(path)) except: print("This function currently requires pyqtgraph to be installed.")
[ "def", "copy_figure_to_clipboard", "(", "figure", "=", "'gcf'", ")", ":", "try", ":", "import", "pyqtgraph", "as", "_p", "# Get the current figure if necessary ", "if", "figure", "is", "'gcf'", ":", "figure", "=", "_s", ".", "pylab", ".", "gcf", "(", ")...
Copies the specified figure to the system clipboard. Specifying 'gcf' will use the current figure.
[ "Copies", "the", "specified", "figure", "to", "the", "system", "clipboard", ".", "Specifying", "gcf", "will", "use", "the", "current", "figure", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L188-L208
train
39,671
Spinmob/spinmob
_pylab_tweaks.py
get_figure_window_geometry
def get_figure_window_geometry(fig='gcf'): """ This will currently only work for Qt4Agg and WXAgg backends. Returns position, size postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object. """ if type(fig)==str: fig = _pylab.gcf() elif _fun.is_a_number(fig): fig = _pylab.figure(fig) # Qt4Agg backend. Probably would work for other Qt stuff if _pylab.get_backend().find('Qt') >= 0: size = fig.canvas.window().size() pos = fig.canvas.window().pos() return [[pos.x(),pos.y()], [size.width(),size.height()]] else: print("get_figure_window_geometry() only implemented for QtAgg backend.") return None
python
def get_figure_window_geometry(fig='gcf'): """ This will currently only work for Qt4Agg and WXAgg backends. Returns position, size postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object. """ if type(fig)==str: fig = _pylab.gcf() elif _fun.is_a_number(fig): fig = _pylab.figure(fig) # Qt4Agg backend. Probably would work for other Qt stuff if _pylab.get_backend().find('Qt') >= 0: size = fig.canvas.window().size() pos = fig.canvas.window().pos() return [[pos.x(),pos.y()], [size.width(),size.height()]] else: print("get_figure_window_geometry() only implemented for QtAgg backend.") return None
[ "def", "get_figure_window_geometry", "(", "fig", "=", "'gcf'", ")", ":", "if", "type", "(", "fig", ")", "==", "str", ":", "fig", "=", "_pylab", ".", "gcf", "(", ")", "elif", "_fun", ".", "is_a_number", "(", "fig", ")", ":", "fig", "=", "_pylab", "....
This will currently only work for Qt4Agg and WXAgg backends. Returns position, size postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object.
[ "This", "will", "currently", "only", "work", "for", "Qt4Agg", "and", "WXAgg", "backends", ".", "Returns", "position", "size" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L363-L385
train
39,672
Spinmob/spinmob
_pylab_tweaks.py
impose_legend_limit
def impose_legend_limit(limit=30, axes="gca", **kwargs): """ This will erase all but, say, 30 of the legend entries and remake the legend. You'll probably have to move it back into your favorite position at this point. """ if axes=="gca": axes = _pylab.gca() # make these axes current _pylab.axes(axes) # loop over all the lines_pylab. for n in range(0,len(axes.lines)): if n > limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("_nolegend_") if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("...") _pylab.legend(**kwargs)
python
def impose_legend_limit(limit=30, axes="gca", **kwargs): """ This will erase all but, say, 30 of the legend entries and remake the legend. You'll probably have to move it back into your favorite position at this point. """ if axes=="gca": axes = _pylab.gca() # make these axes current _pylab.axes(axes) # loop over all the lines_pylab. for n in range(0,len(axes.lines)): if n > limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("_nolegend_") if n == limit-1 and not n==len(axes.lines)-1: axes.lines[n].set_label("...") _pylab.legend(**kwargs)
[ "def", "impose_legend_limit", "(", "limit", "=", "30", ",", "axes", "=", "\"gca\"", ",", "*", "*", "kwargs", ")", ":", "if", "axes", "==", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "# make these axes current", "_pylab", ".", "axes", ...
This will erase all but, say, 30 of the legend entries and remake the legend. You'll probably have to move it back into your favorite position at this point.
[ "This", "will", "erase", "all", "but", "say", "30", "of", "the", "legend", "entries", "and", "remake", "the", "legend", ".", "You", "ll", "probably", "have", "to", "move", "it", "back", "into", "your", "favorite", "position", "at", "this", "point", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L418-L433
train
39,673
Spinmob/spinmob
_pylab_tweaks.py
image_coarsen
def image_coarsen(xlevel=0, ylevel=0, image="auto", method='average'): """ This will coarsen the image data by binning each xlevel+1 along the x-axis and each ylevel+1 points along the y-axis type can be 'average', 'min', or 'max' """ if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list global image_undo_list image_undo_list.append([image, Z]) if len(image_undo_list) > 10: image_undo_list.pop(0) # images have transposed data image.set_array(_fun.coarsen_matrix(Z, ylevel, xlevel, method)) # update the plot _pylab.draw()
python
def image_coarsen(xlevel=0, ylevel=0, image="auto", method='average'): """ This will coarsen the image data by binning each xlevel+1 along the x-axis and each ylevel+1 points along the y-axis type can be 'average', 'min', or 'max' """ if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list global image_undo_list image_undo_list.append([image, Z]) if len(image_undo_list) > 10: image_undo_list.pop(0) # images have transposed data image.set_array(_fun.coarsen_matrix(Z, ylevel, xlevel, method)) # update the plot _pylab.draw()
[ "def", "image_coarsen", "(", "xlevel", "=", "0", ",", "ylevel", "=", "0", ",", "image", "=", "\"auto\"", ",", "method", "=", "'average'", ")", ":", "if", "image", "==", "\"auto\"", ":", "image", "=", "_pylab", ".", "gca", "(", ")", ".", "images", "...
This will coarsen the image data by binning each xlevel+1 along the x-axis and each ylevel+1 points along the y-axis type can be 'average', 'min', or 'max'
[ "This", "will", "coarsen", "the", "image", "data", "by", "binning", "each", "xlevel", "+", "1", "along", "the", "x", "-", "axis", "and", "each", "ylevel", "+", "1", "points", "along", "the", "y", "-", "axis" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L449-L469
train
39,674
Spinmob/spinmob
_pylab_tweaks.py
image_neighbor_smooth
def image_neighbor_smooth(xlevel=0.2, ylevel=0.2, image="auto"): """ This will bleed nearest neighbor pixels into each other with the specified weight factors. """ if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list global image_undo_list image_undo_list.append([image, Z]) if len(image_undo_list) > 10: image_undo_list.pop(0) # get the diagonal smoothing level (eliptical, and scaled down by distance) dlevel = ((xlevel**2+ylevel**2)/2.0)**(0.5) # don't touch the first column new_Z = [Z[0]*1.0] for m in range(1,len(Z)-1): new_Z.append(Z[m]*1.0) for n in range(1,len(Z[0])-1): new_Z[-1][n] = (Z[m,n] + xlevel*(Z[m+1,n]+Z[m-1,n]) + ylevel*(Z[m,n+1]+Z[m,n-1]) \ + dlevel*(Z[m+1,n+1]+Z[m-1,n+1]+Z[m+1,n-1]+Z[m-1,n-1]) ) \ / (1.0+xlevel*2+ylevel*2 + dlevel*4) # don't touch the last column new_Z.append(Z[-1]*1.0) # images have transposed data image.set_array(_n.array(new_Z)) # update the plot _pylab.draw()
python
def image_neighbor_smooth(xlevel=0.2, ylevel=0.2, image="auto"): """ This will bleed nearest neighbor pixels into each other with the specified weight factors. """ if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list global image_undo_list image_undo_list.append([image, Z]) if len(image_undo_list) > 10: image_undo_list.pop(0) # get the diagonal smoothing level (eliptical, and scaled down by distance) dlevel = ((xlevel**2+ylevel**2)/2.0)**(0.5) # don't touch the first column new_Z = [Z[0]*1.0] for m in range(1,len(Z)-1): new_Z.append(Z[m]*1.0) for n in range(1,len(Z[0])-1): new_Z[-1][n] = (Z[m,n] + xlevel*(Z[m+1,n]+Z[m-1,n]) + ylevel*(Z[m,n+1]+Z[m,n-1]) \ + dlevel*(Z[m+1,n+1]+Z[m-1,n+1]+Z[m+1,n-1]+Z[m-1,n-1]) ) \ / (1.0+xlevel*2+ylevel*2 + dlevel*4) # don't touch the last column new_Z.append(Z[-1]*1.0) # images have transposed data image.set_array(_n.array(new_Z)) # update the plot _pylab.draw()
[ "def", "image_neighbor_smooth", "(", "xlevel", "=", "0.2", ",", "ylevel", "=", "0.2", ",", "image", "=", "\"auto\"", ")", ":", "if", "image", "==", "\"auto\"", ":", "image", "=", "_pylab", ".", "gca", "(", ")", ".", "images", "[", "0", "]", "Z", "=...
This will bleed nearest neighbor pixels into each other with the specified weight factors.
[ "This", "will", "bleed", "nearest", "neighbor", "pixels", "into", "each", "other", "with", "the", "specified", "weight", "factors", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L472-L506
train
39,675
Spinmob/spinmob
_pylab_tweaks.py
image_undo
def image_undo(): """ Undoes the last coarsen or smooth command. """ if len(image_undo_list) <= 0: print("no undos in memory") return [image, Z] = image_undo_list.pop(-1) image.set_array(Z) _pylab.draw()
python
def image_undo(): """ Undoes the last coarsen or smooth command. """ if len(image_undo_list) <= 0: print("no undos in memory") return [image, Z] = image_undo_list.pop(-1) image.set_array(Z) _pylab.draw()
[ "def", "image_undo", "(", ")", ":", "if", "len", "(", "image_undo_list", ")", "<=", "0", ":", "print", "(", "\"no undos in memory\"", ")", "return", "[", "image", ",", "Z", "]", "=", "image_undo_list", ".", "pop", "(", "-", "1", ")", "image", ".", "s...
Undoes the last coarsen or smooth command.
[ "Undoes", "the", "last", "coarsen", "or", "smooth", "command", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L508-L518
train
39,676
Spinmob/spinmob
_pylab_tweaks.py
image_set_aspect
def image_set_aspect(aspect=1.0, axes="gca"): """ sets the aspect ratio of the current zoom level of the imshow image """ if axes is "gca": axes = _pylab.gca() e = axes.get_images()[0].get_extent() axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
python
def image_set_aspect(aspect=1.0, axes="gca"): """ sets the aspect ratio of the current zoom level of the imshow image """ if axes is "gca": axes = _pylab.gca() e = axes.get_images()[0].get_extent() axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
[ "def", "image_set_aspect", "(", "aspect", "=", "1.0", ",", "axes", "=", "\"gca\"", ")", ":", "if", "axes", "is", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "e", "=", "axes", ".", "get_images", "(", ")", "[", "0", "]", ".", "get_...
sets the aspect ratio of the current zoom level of the imshow image
[ "sets", "the", "aspect", "ratio", "of", "the", "current", "zoom", "level", "of", "the", "imshow", "image" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L521-L528
train
39,677
Spinmob/spinmob
_pylab_tweaks.py
image_set_extent
def image_set_extent(x=None, y=None, axes="gca"): """ Set's the first image's extent, then redraws. Examples: x = [1,4] y = [33.3, 22] """ if axes == "gca": axes = _pylab.gca() # get the current plot limits xlim = axes.get_xlim() ylim = axes.get_ylim() # get the old extent extent = axes.images[0].get_extent() # calculate the fractional extents x0 = extent[0] y0 = extent[2] xwidth = extent[1]-x0 ywidth = extent[3]-y0 frac_x1 = (xlim[0]-x0)/xwidth frac_x2 = (xlim[1]-x0)/xwidth frac_y1 = (ylim[0]-y0)/ywidth frac_y2 = (ylim[1]-y0)/ywidth # set the new if not x == None: extent[0] = x[0] extent[1] = x[1] if not y == None: extent[2] = y[0] extent[3] = y[1] # get the new zoom window x0 = extent[0] y0 = extent[2] xwidth = extent[1]-x0 ywidth = extent[3]-y0 x1 = x0 + xwidth*frac_x1 x2 = x0 + xwidth*frac_x2 y1 = y0 + ywidth*frac_y1 y2 = y0 + ywidth*frac_y2 # set the extent axes.images[0].set_extent(extent) # rezoom us axes.set_xlim(x1,x2) axes.set_ylim(y1,y2) # draw image_set_aspect(1.0)
python
def image_set_extent(x=None, y=None, axes="gca"): """ Set's the first image's extent, then redraws. Examples: x = [1,4] y = [33.3, 22] """ if axes == "gca": axes = _pylab.gca() # get the current plot limits xlim = axes.get_xlim() ylim = axes.get_ylim() # get the old extent extent = axes.images[0].get_extent() # calculate the fractional extents x0 = extent[0] y0 = extent[2] xwidth = extent[1]-x0 ywidth = extent[3]-y0 frac_x1 = (xlim[0]-x0)/xwidth frac_x2 = (xlim[1]-x0)/xwidth frac_y1 = (ylim[0]-y0)/ywidth frac_y2 = (ylim[1]-y0)/ywidth # set the new if not x == None: extent[0] = x[0] extent[1] = x[1] if not y == None: extent[2] = y[0] extent[3] = y[1] # get the new zoom window x0 = extent[0] y0 = extent[2] xwidth = extent[1]-x0 ywidth = extent[3]-y0 x1 = x0 + xwidth*frac_x1 x2 = x0 + xwidth*frac_x2 y1 = y0 + ywidth*frac_y1 y2 = y0 + ywidth*frac_y2 # set the extent axes.images[0].set_extent(extent) # rezoom us axes.set_xlim(x1,x2) axes.set_ylim(y1,y2) # draw image_set_aspect(1.0)
[ "def", "image_set_extent", "(", "x", "=", "None", ",", "y", "=", "None", ",", "axes", "=", "\"gca\"", ")", ":", "if", "axes", "==", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "# get the current plot limits", "xlim", "=", "axes", ".", ...
Set's the first image's extent, then redraws. Examples: x = [1,4] y = [33.3, 22]
[ "Set", "s", "the", "first", "image", "s", "extent", "then", "redraws", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L530-L586
train
39,678
Spinmob/spinmob
_pylab_tweaks.py
image_scale
def image_scale(xscale=1.0, yscale=1.0, axes="gca"): """ Scales the image extent. """ if axes == "gca": axes = _pylab.gca() e = axes.images[0].get_extent() x1 = e[0]*xscale x2 = e[1]*xscale y1 = e[2]*yscale y2 = e[3]*yscale image_set_extent([x1,x2],[y1,y2], axes)
python
def image_scale(xscale=1.0, yscale=1.0, axes="gca"): """ Scales the image extent. """ if axes == "gca": axes = _pylab.gca() e = axes.images[0].get_extent() x1 = e[0]*xscale x2 = e[1]*xscale y1 = e[2]*yscale y2 = e[3]*yscale image_set_extent([x1,x2],[y1,y2], axes)
[ "def", "image_scale", "(", "xscale", "=", "1.0", ",", "yscale", "=", "1.0", ",", "axes", "=", "\"gca\"", ")", ":", "if", "axes", "==", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "e", "=", "axes", ".", "images", "[", "0", "]", ...
Scales the image extent.
[ "Scales", "the", "image", "extent", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L589-L601
train
39,679
Spinmob/spinmob
_pylab_tweaks.py
image_shift
def image_shift(xshift=0, yshift=0, axes="gca"): """ This will shift an image to a new location on x and y. """ if axes=="gca": axes = _pylab.gca() e = axes.images[0].get_extent() e[0] = e[0] + xshift e[1] = e[1] + xshift e[2] = e[2] + yshift e[3] = e[3] + yshift axes.images[0].set_extent(e) _pylab.draw()
python
def image_shift(xshift=0, yshift=0, axes="gca"): """ This will shift an image to a new location on x and y. """ if axes=="gca": axes = _pylab.gca() e = axes.images[0].get_extent() e[0] = e[0] + xshift e[1] = e[1] + xshift e[2] = e[2] + yshift e[3] = e[3] + yshift axes.images[0].set_extent(e) _pylab.draw()
[ "def", "image_shift", "(", "xshift", "=", "0", ",", "yshift", "=", "0", ",", "axes", "=", "\"gca\"", ")", ":", "if", "axes", "==", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "e", "=", "axes", ".", "images", "[", "0", "]", ".",...
This will shift an image to a new location on x and y.
[ "This", "will", "shift", "an", "image", "to", "a", "new", "location", "on", "x", "and", "y", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L651-L667
train
39,680
Spinmob/spinmob
_pylab_tweaks.py
_print_figures
def _print_figures(figures, arguments='', file_format='pdf', target_width=8.5, target_height=11.0, target_pad=0.5): """ figure printing loop designed to be launched in a separate thread. """ for fig in figures: # get the temp path temp_path = _os.path.join(_settings.path_home, "temp") # make the temp folder _settings.MakeDir(temp_path) # output the figure to postscript path = _os.path.join(temp_path, "graph."+file_format) # get the dimensions of the figure in inches w=fig.get_figwidth() h=fig.get_figheight() # we're printing to 8.5 x 11, so aim for 7.5 x 10 target_height = target_height-2*target_pad target_width = target_width -2*target_pad # depending on the aspect we scale by the vertical or horizontal value if 1.0*h/w > target_height/target_width: # scale down according to the vertical dimension new_h = target_height new_w = w*target_height/h else: # scale down according to the hozo dimension new_w = target_width new_h = h*target_width/w fig.set_figwidth(new_w) fig.set_figheight(new_h) # save it fig.savefig(path, bbox_inches=_pylab.matplotlib.transforms.Bbox( [[-target_pad, new_h-target_height-target_pad], [target_width-target_pad, target_height-target_pad]])) # set it back fig.set_figheight(h) fig.set_figwidth(w) if not arguments == '': c = _settings['instaprint'] + ' ' + arguments + ' "' + path + '"' else: c = _settings['instaprint'] + ' "' + path + '"' print(c) _os.system(c)
python
def _print_figures(figures, arguments='', file_format='pdf', target_width=8.5, target_height=11.0, target_pad=0.5): """ figure printing loop designed to be launched in a separate thread. """ for fig in figures: # get the temp path temp_path = _os.path.join(_settings.path_home, "temp") # make the temp folder _settings.MakeDir(temp_path) # output the figure to postscript path = _os.path.join(temp_path, "graph."+file_format) # get the dimensions of the figure in inches w=fig.get_figwidth() h=fig.get_figheight() # we're printing to 8.5 x 11, so aim for 7.5 x 10 target_height = target_height-2*target_pad target_width = target_width -2*target_pad # depending on the aspect we scale by the vertical or horizontal value if 1.0*h/w > target_height/target_width: # scale down according to the vertical dimension new_h = target_height new_w = w*target_height/h else: # scale down according to the hozo dimension new_w = target_width new_h = h*target_width/w fig.set_figwidth(new_w) fig.set_figheight(new_h) # save it fig.savefig(path, bbox_inches=_pylab.matplotlib.transforms.Bbox( [[-target_pad, new_h-target_height-target_pad], [target_width-target_pad, target_height-target_pad]])) # set it back fig.set_figheight(h) fig.set_figwidth(w) if not arguments == '': c = _settings['instaprint'] + ' ' + arguments + ' "' + path + '"' else: c = _settings['instaprint'] + ' "' + path + '"' print(c) _os.system(c)
[ "def", "_print_figures", "(", "figures", ",", "arguments", "=", "''", ",", "file_format", "=", "'pdf'", ",", "target_width", "=", "8.5", ",", "target_height", "=", "11.0", ",", "target_pad", "=", "0.5", ")", ":", "for", "fig", "in", "figures", ":", "# ge...
figure printing loop designed to be launched in a separate thread.
[ "figure", "printing", "loop", "designed", "to", "be", "launched", "in", "a", "separate", "thread", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L882-L935
train
39,681
Spinmob/spinmob
_pylab_tweaks.py
raise_figure_window
def raise_figure_window(f=0): """ Raises the supplied figure number or figure window. """ if _fun.is_a_number(f): f = _pylab.figure(f) f.canvas.manager.window.raise_()
python
def raise_figure_window(f=0): """ Raises the supplied figure number or figure window. """ if _fun.is_a_number(f): f = _pylab.figure(f) f.canvas.manager.window.raise_()
[ "def", "raise_figure_window", "(", "f", "=", "0", ")", ":", "if", "_fun", ".", "is_a_number", "(", "f", ")", ":", "f", "=", "_pylab", ".", "figure", "(", "f", ")", "f", ".", "canvas", ".", "manager", ".", "window", ".", "raise_", "(", ")" ]
Raises the supplied figure number or figure window.
[ "Raises", "the", "supplied", "figure", "number", "or", "figure", "window", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1028-L1033
train
39,682
Spinmob/spinmob
_pylab_tweaks.py
set_figure_window_geometry
def set_figure_window_geometry(fig='gcf', position=None, size=None): """ This will currently only work for Qt4Agg and WXAgg backends. postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object. """ if type(fig)==str: fig = _pylab.gcf() elif _fun.is_a_number(fig): fig = _pylab.figure(fig) # Qt4Agg backend. Probably would work for other Qt stuff if _pylab.get_backend().find('Qt') >= 0: w = fig.canvas.window() if not size == None: w.resize(size[0],size[1]) if not position == None: w.move(position[0], position[1]) # WXAgg backend. Probably would work for other Qt stuff. elif _pylab.get_backend().find('WX') >= 0: w = fig.canvas.Parent if not size == None: w.SetSize(size) if not position == None: w.SetPosition(position)
python
def set_figure_window_geometry(fig='gcf', position=None, size=None): """ This will currently only work for Qt4Agg and WXAgg backends. postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object. """ if type(fig)==str: fig = _pylab.gcf() elif _fun.is_a_number(fig): fig = _pylab.figure(fig) # Qt4Agg backend. Probably would work for other Qt stuff if _pylab.get_backend().find('Qt') >= 0: w = fig.canvas.window() if not size == None: w.resize(size[0],size[1]) if not position == None: w.move(position[0], position[1]) # WXAgg backend. Probably would work for other Qt stuff. elif _pylab.get_backend().find('WX') >= 0: w = fig.canvas.Parent if not size == None: w.SetSize(size) if not position == None: w.SetPosition(position)
[ "def", "set_figure_window_geometry", "(", "fig", "=", "'gcf'", ",", "position", "=", "None", ",", "size", "=", "None", ")", ":", "if", "type", "(", "fig", ")", "==", "str", ":", "fig", "=", "_pylab", ".", "gcf", "(", ")", "elif", "_fun", ".", "is_a...
This will currently only work for Qt4Agg and WXAgg backends. postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object.
[ "This", "will", "currently", "only", "work", "for", "Qt4Agg", "and", "WXAgg", "backends", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1158-L1189
train
39,683
Spinmob/spinmob
_pylab_tweaks.py
line_math
def line_math(fx=None, fy=None, axes='gca'): """ applies function fx to all xdata and fy to all ydata. """ if axes=='gca': axes = _pylab.gca() lines = axes.get_lines() for line in lines: if isinstance(line, _mpl.lines.Line2D): xdata, ydata = line.get_data() if not fx==None: xdata = fx(xdata) if not fy==None: ydata = fy(ydata) line.set_data(xdata,ydata) _pylab.draw()
python
def line_math(fx=None, fy=None, axes='gca'): """ applies function fx to all xdata and fy to all ydata. """ if axes=='gca': axes = _pylab.gca() lines = axes.get_lines() for line in lines: if isinstance(line, _mpl.lines.Line2D): xdata, ydata = line.get_data() if not fx==None: xdata = fx(xdata) if not fy==None: ydata = fy(ydata) line.set_data(xdata,ydata) _pylab.draw()
[ "def", "line_math", "(", "fx", "=", "None", ",", "fy", "=", "None", ",", "axes", "=", "'gca'", ")", ":", "if", "axes", "==", "'gca'", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "lines", "=", "axes", ".", "get_lines", "(", ")", "for", "li...
applies function fx to all xdata and fy to all ydata.
[ "applies", "function", "fx", "to", "all", "xdata", "and", "fy", "to", "all", "ydata", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1465-L1481
train
39,684
Spinmob/spinmob
_pylab_tweaks.py
export_figure
def export_figure(dpi=200, figure="gcf", path=None): """ Saves the actual postscript data for the figure. """ if figure=="gcf": figure = _pylab.gcf() if path==None: path = _s.dialogs.Save("*.*", default_directory="save_plot_default_directory") if path=="": print("aborted.") return figure.savefig(path, dpi=dpi)
python
def export_figure(dpi=200, figure="gcf", path=None): """ Saves the actual postscript data for the figure. """ if figure=="gcf": figure = _pylab.gcf() if path==None: path = _s.dialogs.Save("*.*", default_directory="save_plot_default_directory") if path=="": print("aborted.") return figure.savefig(path, dpi=dpi)
[ "def", "export_figure", "(", "dpi", "=", "200", ",", "figure", "=", "\"gcf\"", ",", "path", "=", "None", ")", ":", "if", "figure", "==", "\"gcf\"", ":", "figure", "=", "_pylab", ".", "gcf", "(", ")", "if", "path", "==", "None", ":", "path", "=", ...
Saves the actual postscript data for the figure.
[ "Saves", "the", "actual", "postscript", "data", "for", "the", "figure", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1720-L1732
train
39,685
Spinmob/spinmob
_pylab_tweaks.py
save_plot
def save_plot(axes="gca", path=None): """ Saves the figure in my own ascii format """ global line_attributes # choose a path to save to if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory") if path=="": print("aborted.") return if not path.split(".")[-1] == "plot": path = path+".plot" f = file(path, "w") # if no argument was given, get the current axes if axes=="gca": axes=_pylab.gca() # now loop over the available lines f.write("title=" +axes.title.get_text().replace('\n', '\\n')+'\n') f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n') f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n') for l in axes.lines: # write the data header f.write("trace=new\n") f.write("legend="+l.get_label().replace('\n', '\\n')+"\n") for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n") # get the data x = l.get_xdata() y = l.get_ydata() # loop over the data for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n") f.close()
python
def save_plot(axes="gca", path=None): """ Saves the figure in my own ascii format """ global line_attributes # choose a path to save to if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory") if path=="": print("aborted.") return if not path.split(".")[-1] == "plot": path = path+".plot" f = file(path, "w") # if no argument was given, get the current axes if axes=="gca": axes=_pylab.gca() # now loop over the available lines f.write("title=" +axes.title.get_text().replace('\n', '\\n')+'\n') f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n') f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n') for l in axes.lines: # write the data header f.write("trace=new\n") f.write("legend="+l.get_label().replace('\n', '\\n')+"\n") for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n") # get the data x = l.get_xdata() y = l.get_ydata() # loop over the data for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n") f.close()
[ "def", "save_plot", "(", "axes", "=", "\"gca\"", ",", "path", "=", "None", ")", ":", "global", "line_attributes", "# choose a path to save to", "if", "path", "==", "None", ":", "path", "=", "_s", ".", "dialogs", ".", "Save", "(", "\"*.plot\"", ",", "defaul...
Saves the figure in my own ascii format
[ "Saves", "the", "figure", "in", "my", "own", "ascii", "format" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1734-L1774
train
39,686
Spinmob/spinmob
_pylab_tweaks.py
save_figure_raw_data
def save_figure_raw_data(figure="gcf", **kwargs): """ This will just output an ascii file for each of the traces in the shown figure. **kwargs are sent to dialogs.Save() """ # choose a path to save to path = _s.dialogs.Save(**kwargs) if path=="": return "aborted." # if no argument was given, get the current axes if figure=="gcf": figure = _pylab.gcf() for n in range(len(figure.axes)): a = figure.axes[n] for m in range(len(a.lines)): l = a.lines[m] x = l.get_xdata() y = l.get_ydata() p = _os.path.split(path) p = _os.path.join(p[0], "axes" + str(n) + " line" + str(m) + " " + p[1]) print(p) # loop over the data f = open(p, 'w') for j in range(0, len(x)): f.write(str(x[j]) + "\t" + str(y[j]) + "\n") f.close()
python
def save_figure_raw_data(figure="gcf", **kwargs): """ This will just output an ascii file for each of the traces in the shown figure. **kwargs are sent to dialogs.Save() """ # choose a path to save to path = _s.dialogs.Save(**kwargs) if path=="": return "aborted." # if no argument was given, get the current axes if figure=="gcf": figure = _pylab.gcf() for n in range(len(figure.axes)): a = figure.axes[n] for m in range(len(a.lines)): l = a.lines[m] x = l.get_xdata() y = l.get_ydata() p = _os.path.split(path) p = _os.path.join(p[0], "axes" + str(n) + " line" + str(m) + " " + p[1]) print(p) # loop over the data f = open(p, 'w') for j in range(0, len(x)): f.write(str(x[j]) + "\t" + str(y[j]) + "\n") f.close()
[ "def", "save_figure_raw_data", "(", "figure", "=", "\"gcf\"", ",", "*", "*", "kwargs", ")", ":", "# choose a path to save to", "path", "=", "_s", ".", "dialogs", ".", "Save", "(", "*", "*", "kwargs", ")", "if", "path", "==", "\"\"", ":", "return", "\"abo...
This will just output an ascii file for each of the traces in the shown figure. **kwargs are sent to dialogs.Save()
[ "This", "will", "just", "output", "an", "ascii", "file", "for", "each", "of", "the", "traces", "in", "the", "shown", "figure", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1776-L1807
train
39,687
Spinmob/spinmob
_pylab_tweaks.py
style_cycle.get_line_color
def get_line_color(self, increment=1): """ Returns the current color, then increments the color by what's specified """ i = self.line_colors_index self.line_colors_index += increment if self.line_colors_index >= len(self.line_colors): self.line_colors_index = self.line_colors_index-len(self.line_colors) if self.line_colors_index >= len(self.line_colors): self.line_colors_index=0 # to be safe return self.line_colors[i]
python
def get_line_color(self, increment=1): """ Returns the current color, then increments the color by what's specified """ i = self.line_colors_index self.line_colors_index += increment if self.line_colors_index >= len(self.line_colors): self.line_colors_index = self.line_colors_index-len(self.line_colors) if self.line_colors_index >= len(self.line_colors): self.line_colors_index=0 # to be safe return self.line_colors[i]
[ "def", "get_line_color", "(", "self", ",", "increment", "=", "1", ")", ":", "i", "=", "self", ".", "line_colors_index", "self", ".", "line_colors_index", "+=", "increment", "if", "self", ".", "line_colors_index", ">=", "len", "(", "self", ".", "line_colors",...
Returns the current color, then increments the color by what's specified
[ "Returns", "the", "current", "color", "then", "increments", "the", "color", "by", "what", "s", "specified" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L1989-L2001
train
39,688
Spinmob/spinmob
_pylab_tweaks.py
style_cycle.apply
def apply(self, axes="gca"): """ Applies the style cycle to the lines in the axes specified """ if axes == "gca": axes = _pylab.gca() self.reset() lines = axes.get_lines() for l in lines: l.set_color(self.get_line_color(1)) l.set_mfc(self.get_face_color(1)) l.set_marker(self.get_marker(1)) l.set_mec(self.get_edge_color(1)) l.set_linestyle(self.get_linestyle(1)) _pylab.draw()
python
def apply(self, axes="gca"): """ Applies the style cycle to the lines in the axes specified """ if axes == "gca": axes = _pylab.gca() self.reset() lines = axes.get_lines() for l in lines: l.set_color(self.get_line_color(1)) l.set_mfc(self.get_face_color(1)) l.set_marker(self.get_marker(1)) l.set_mec(self.get_edge_color(1)) l.set_linestyle(self.get_linestyle(1)) _pylab.draw()
[ "def", "apply", "(", "self", ",", "axes", "=", "\"gca\"", ")", ":", "if", "axes", "==", "\"gca\"", ":", "axes", "=", "_pylab", ".", "gca", "(", ")", "self", ".", "reset", "(", ")", "lines", "=", "axes", ".", "get_lines", "(", ")", "for", "l", "...
Applies the style cycle to the lines in the axes specified
[ "Applies", "the", "style", "cycle", "to", "the", "lines", "in", "the", "axes", "specified" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L2082-L2098
train
39,689
Spinmob/spinmob
_spline.py
copy_spline_array
def copy_spline_array(a): """ This returns an instance of a new spline_array with all the fixins, and the data from a. """ b = spline_array() b.x_splines = a.x_splines b.y_splines = a.y_splines b.max_y_splines = a.max_y_splines b.xmin = a.xmin b.xmax = a.xmax b.ymin = a.ymin b.ymax = a.ymax b.xlabel = a.xlabel b.ylabel = a.ylabel b.zlabel = a.zlabel b.simple = a.simple b.generate_y_values() return b
python
def copy_spline_array(a): """ This returns an instance of a new spline_array with all the fixins, and the data from a. """ b = spline_array() b.x_splines = a.x_splines b.y_splines = a.y_splines b.max_y_splines = a.max_y_splines b.xmin = a.xmin b.xmax = a.xmax b.ymin = a.ymin b.ymax = a.ymax b.xlabel = a.xlabel b.ylabel = a.ylabel b.zlabel = a.zlabel b.simple = a.simple b.generate_y_values() return b
[ "def", "copy_spline_array", "(", "a", ")", ":", "b", "=", "spline_array", "(", ")", "b", ".", "x_splines", "=", "a", ".", "x_splines", "b", ".", "y_splines", "=", "a", ".", "y_splines", "b", ".", "max_y_splines", "=", "a", ".", "max_y_splines", "b", ...
This returns an instance of a new spline_array with all the fixins, and the data from a.
[ "This", "returns", "an", "instance", "of", "a", "new", "spline_array", "with", "all", "the", "fixins", "and", "the", "data", "from", "a", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L343-L365
train
39,690
Spinmob/spinmob
_spline.py
splot
def splot(axes="gca", smoothing=5000, degree=5, presmoothing=0, plot=True, spline_class=spline_single, interactive=True, show_derivative=1): """ gets the data from the plot and feeds it into splint returns an instance of spline_single axes="gca" which axes to get the data from. smoothing=5000 spline_single smoothing parameter presmoothing=0 spline_single data presmoothing factor (nearest neighbor) plot=True should we plot the result? spline_class=spline_single which data class to use? interactive=False should we spline fit interactively or just make a spline_single? """ if axes=="gca": axes = _pylab.gca() xlabel = axes.xaxis.label.get_text() ylabel = axes.yaxis.label.get_text() xdata = axes.get_lines()[0].get_xdata() ydata = axes.get_lines()[0].get_ydata() if interactive: return splinteractive(xdata, ydata, smoothing, degree, presmoothing, spline_class, xlabel, ylabel) else: return spline_class(xdata, ydata, smoothing, degree, presmoothing, plot, xlabel, ylabel)
python
def splot(axes="gca", smoothing=5000, degree=5, presmoothing=0, plot=True, spline_class=spline_single, interactive=True, show_derivative=1): """ gets the data from the plot and feeds it into splint returns an instance of spline_single axes="gca" which axes to get the data from. smoothing=5000 spline_single smoothing parameter presmoothing=0 spline_single data presmoothing factor (nearest neighbor) plot=True should we plot the result? spline_class=spline_single which data class to use? interactive=False should we spline fit interactively or just make a spline_single? """ if axes=="gca": axes = _pylab.gca() xlabel = axes.xaxis.label.get_text() ylabel = axes.yaxis.label.get_text() xdata = axes.get_lines()[0].get_xdata() ydata = axes.get_lines()[0].get_ydata() if interactive: return splinteractive(xdata, ydata, smoothing, degree, presmoothing, spline_class, xlabel, ylabel) else: return spline_class(xdata, ydata, smoothing, degree, presmoothing, plot, xlabel, ylabel)
[ "def", "splot", "(", "axes", "=", "\"gca\"", ",", "smoothing", "=", "5000", ",", "degree", "=", "5", ",", "presmoothing", "=", "0", ",", "plot", "=", "True", ",", "spline_class", "=", "spline_single", ",", "interactive", "=", "True", ",", "show_derivativ...
gets the data from the plot and feeds it into splint returns an instance of spline_single axes="gca" which axes to get the data from. smoothing=5000 spline_single smoothing parameter presmoothing=0 spline_single data presmoothing factor (nearest neighbor) plot=True should we plot the result? spline_class=spline_single which data class to use? interactive=False should we spline fit interactively or just make a spline_single?
[ "gets", "the", "data", "from", "the", "plot", "and", "feeds", "it", "into", "splint", "returns", "an", "instance", "of", "spline_single" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L532-L558
train
39,691
Spinmob/spinmob
_spline.py
spline_single.evaluate
def evaluate(self, x, derivative=0, smooth=0, simple='auto'): """ smooth=0 is how much to smooth the spline data simple='auto' is whether we should just use straight interpolation you may want smooth > 0 for this, when derivative=1 """ if simple=='auto': simple = self.simple # make it into an array if it isn't one, and remember that we did is_array = True if not type(x) == type(_pylab.array([])): x = _pylab.array([x]) is_array = False if simple: # loop over all supplied x data, and come up with a y for each y = [] for n in range(0, len(x)): # get a window of data around x if smooth: [xtemp, ytemp, etemp] = _fun.trim_data(self.xdata, self.ydata, None, [x[n]-smooth, x[n]+smooth]) else: i1 = _fun.index_nearest(x[n], self.xdata) # if the nearest data point is lower than x, use the next point to interpolate if self.xdata[i1] <= x[n] or i1 <= 0: i2 = i1+1 else: i2 = i1-1 # if we're at the max, extrapolate if i2 >= len(self.xdata): print(x[n], "is out of range. extrapolating") i2 = i1-1 x1 = self.xdata[i1] y1 = self.ydata[i1] x2 = self.xdata[i2] y2 = self.ydata[i2] slope = (y2-y1)/(x2-x1) xtemp = _numpy.array([x[n]]) ytemp = _numpy.array([y1 + (x[n]-x1)*slope]) # calculate the slope based on xtemp and ytemp (if smoothing) # or just use the raw slope if smoothing=0 if derivative == 1: if smooth: y.append((_numpy.average(xtemp*ytemp)-_numpy.average(xtemp)*_numpy.average(ytemp)) / (_numpy.average(xtemp*xtemp)-_numpy.average(xtemp)**2)) else: y.append(slope) # otherwise just average (even with one element) elif derivative==0: y.append(_numpy.average(ytemp)) if is_array: return _numpy.array(y) else: return y[0] if smooth: y = [] for n in range(0, len(x)): # take 20 data points from x+/-smooth xlow = max(self.xmin,x[n]-smooth) xhi = min(self.xmax,x[n]+smooth) xdata = _pylab.linspace(xlow, xhi, 20) ydata = _interpolate.splev(xdata, self.pfit, derivative) y.append(_numpy.average(ydata)) if is_array: return _numpy.array(y) else: return y[0] else: return _interpolate.splev(x, self.pfit, derivative)
python
def evaluate(self, x, derivative=0, smooth=0, simple='auto'): """ smooth=0 is how much to smooth the spline data simple='auto' is whether we should just use straight interpolation you may want smooth > 0 for this, when derivative=1 """ if simple=='auto': simple = self.simple # make it into an array if it isn't one, and remember that we did is_array = True if not type(x) == type(_pylab.array([])): x = _pylab.array([x]) is_array = False if simple: # loop over all supplied x data, and come up with a y for each y = [] for n in range(0, len(x)): # get a window of data around x if smooth: [xtemp, ytemp, etemp] = _fun.trim_data(self.xdata, self.ydata, None, [x[n]-smooth, x[n]+smooth]) else: i1 = _fun.index_nearest(x[n], self.xdata) # if the nearest data point is lower than x, use the next point to interpolate if self.xdata[i1] <= x[n] or i1 <= 0: i2 = i1+1 else: i2 = i1-1 # if we're at the max, extrapolate if i2 >= len(self.xdata): print(x[n], "is out of range. extrapolating") i2 = i1-1 x1 = self.xdata[i1] y1 = self.ydata[i1] x2 = self.xdata[i2] y2 = self.ydata[i2] slope = (y2-y1)/(x2-x1) xtemp = _numpy.array([x[n]]) ytemp = _numpy.array([y1 + (x[n]-x1)*slope]) # calculate the slope based on xtemp and ytemp (if smoothing) # or just use the raw slope if smoothing=0 if derivative == 1: if smooth: y.append((_numpy.average(xtemp*ytemp)-_numpy.average(xtemp)*_numpy.average(ytemp)) / (_numpy.average(xtemp*xtemp)-_numpy.average(xtemp)**2)) else: y.append(slope) # otherwise just average (even with one element) elif derivative==0: y.append(_numpy.average(ytemp)) if is_array: return _numpy.array(y) else: return y[0] if smooth: y = [] for n in range(0, len(x)): # take 20 data points from x+/-smooth xlow = max(self.xmin,x[n]-smooth) xhi = min(self.xmax,x[n]+smooth) xdata = _pylab.linspace(xlow, xhi, 20) ydata = _interpolate.splev(xdata, self.pfit, derivative) y.append(_numpy.average(ydata)) if is_array: return _numpy.array(y) else: return y[0] else: return _interpolate.splev(x, self.pfit, derivative)
[ "def", "evaluate", "(", "self", ",", "x", ",", "derivative", "=", "0", ",", "smooth", "=", "0", ",", "simple", "=", "'auto'", ")", ":", "if", "simple", "==", "'auto'", ":", "simple", "=", "self", ".", "simple", "# make it into an array if it isn't one, and...
smooth=0 is how much to smooth the spline data simple='auto' is whether we should just use straight interpolation you may want smooth > 0 for this, when derivative=1
[ "smooth", "=", "0", "is", "how", "much", "to", "smooth", "the", "spline", "data", "simple", "=", "auto", "is", "whether", "we", "should", "just", "use", "straight", "interpolation", "you", "may", "want", "smooth", ">", "0", "for", "this", "when", "deriva...
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L77-L151
train
39,692
Spinmob/spinmob
_spline.py
spline_array.evaluate
def evaluate(self, x, y, x_derivative=0, smooth=0, simple='auto'): """ this evaluates the 2-d spline by doing linear interpolation of the curves """ if simple=='auto': simple = self.simple # find which values y is in between for n in range(0, len(self.y_values)-1): # if it's in between, interpolate! if self.y_values[n] <= y and self.y_values[n+1] >= y: y1 = self.y_values[n] y2 = self.y_values[n+1] z1 = self.x_splines[y1].evaluate(x, x_derivative, smooth, simple) z2 = self.x_splines[y2].evaluate(x, x_derivative, smooth, simple) return z1 + (y-y1)*(z2-z1)/(y2-y1) print("YARG! The y value "+str(y)+" is out of interpolation range!") if y >= self.y_values[-1]: return self.x_splines[self.y_values[-1]].evaluate(x, x_derivative, smooth, simple) else : return self.x_splines[self.y_values[0]].evaluate(x, x_derivative, smooth, simple)
python
def evaluate(self, x, y, x_derivative=0, smooth=0, simple='auto'): """ this evaluates the 2-d spline by doing linear interpolation of the curves """ if simple=='auto': simple = self.simple # find which values y is in between for n in range(0, len(self.y_values)-1): # if it's in between, interpolate! if self.y_values[n] <= y and self.y_values[n+1] >= y: y1 = self.y_values[n] y2 = self.y_values[n+1] z1 = self.x_splines[y1].evaluate(x, x_derivative, smooth, simple) z2 = self.x_splines[y2].evaluate(x, x_derivative, smooth, simple) return z1 + (y-y1)*(z2-z1)/(y2-y1) print("YARG! The y value "+str(y)+" is out of interpolation range!") if y >= self.y_values[-1]: return self.x_splines[self.y_values[-1]].evaluate(x, x_derivative, smooth, simple) else : return self.x_splines[self.y_values[0]].evaluate(x, x_derivative, smooth, simple)
[ "def", "evaluate", "(", "self", ",", "x", ",", "y", ",", "x_derivative", "=", "0", ",", "smooth", "=", "0", ",", "simple", "=", "'auto'", ")", ":", "if", "simple", "==", "'auto'", ":", "simple", "=", "self", ".", "simple", "# find which values y is in ...
this evaluates the 2-d spline by doing linear interpolation of the curves
[ "this", "evaluates", "the", "2", "-", "d", "spline", "by", "doing", "linear", "interpolation", "of", "the", "curves" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L239-L258
train
39,693
Spinmob/spinmob
_spline.py
spline_array.plot_fixed_x
def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1): """ plots the data at fixed x-value, so z vs x """ if simple=='auto': simple=self.simple # get the min and max if ymin=="auto": ymin = self.ymin if ymax=="auto": ymax = self.ymax if clear: _pylab.gca().clear() if not type(x_values) in [type([]), type(_pylab.array([]))]: x_values = [x_values] for x in x_values: # define a new simple function to plot, then plot it def f(y): return self.evaluate(x, y, x_derivative, smooth, simple) _pylab_help.plot_function(f, ymin, ymax, steps, 0, False) # label it a = _pylab.gca() a.set_xlabel(self.ylabel) if x_derivative: a.set_ylabel(str(x_derivative)+" "+str(self.xlabel)+" derivative of "+self.zlabel) else: a.set_ylabel(self.zlabel) a.set_title(self._path+"\nSpline array plot at fixed x = "+self.xlabel) a.get_lines()[-1].set_label("x ("+self.xlabel+") = "+str(x)) if format: _s.format_figure() return a
python
def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1): """ plots the data at fixed x-value, so z vs x """ if simple=='auto': simple=self.simple # get the min and max if ymin=="auto": ymin = self.ymin if ymax=="auto": ymax = self.ymax if clear: _pylab.gca().clear() if not type(x_values) in [type([]), type(_pylab.array([]))]: x_values = [x_values] for x in x_values: # define a new simple function to plot, then plot it def f(y): return self.evaluate(x, y, x_derivative, smooth, simple) _pylab_help.plot_function(f, ymin, ymax, steps, 0, False) # label it a = _pylab.gca() a.set_xlabel(self.ylabel) if x_derivative: a.set_ylabel(str(x_derivative)+" "+str(self.xlabel)+" derivative of "+self.zlabel) else: a.set_ylabel(self.zlabel) a.set_title(self._path+"\nSpline array plot at fixed x = "+self.xlabel) a.get_lines()[-1].set_label("x ("+self.xlabel+") = "+str(x)) if format: _s.format_figure() return a
[ "def", "plot_fixed_x", "(", "self", ",", "x_values", ",", "x_derivative", "=", "0", ",", "steps", "=", "1000", ",", "smooth", "=", "0", ",", "simple", "=", "'auto'", ",", "ymin", "=", "\"auto\"", ",", "ymax", "=", "\"auto\"", ",", "format", "=", "Tru...
plots the data at fixed x-value, so z vs x
[ "plots", "the", "data", "at", "fixed", "x", "-", "value", "so", "z", "vs", "x" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L261-L289
train
39,694
Spinmob/spinmob
_spline.py
spline_array.plot_fixed_y
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1): """ plots the data at a fixed y-value, so z vs y """ if simple=='auto': simple=self.simple # get the min and max if xmin=="auto": xmin = self.xmin if xmax=="auto": xmax = self.xmax if clear: _pylab.gca().clear() if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values] for y in y_values: # define a new simple function to plot, then plot it def f(x): return self.evaluate(x, y, x_derivative, smooth, simple) _pylab_help.plot_function(f, xmin, xmax, steps, 0, True) # label it a = _pylab.gca() th = "th" if x_derivative == 1: th = "st" if x_derivative == 2: th = "nd" if x_derivative == 3: th = "rd" if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline") else: a.set_ylabel(self.zlabel) a.set_xlabel(self.xlabel) a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel) a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y)) if format: _s.format_figure() return a
python
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1): """ plots the data at a fixed y-value, so z vs y """ if simple=='auto': simple=self.simple # get the min and max if xmin=="auto": xmin = self.xmin if xmax=="auto": xmax = self.xmax if clear: _pylab.gca().clear() if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values] for y in y_values: # define a new simple function to plot, then plot it def f(x): return self.evaluate(x, y, x_derivative, smooth, simple) _pylab_help.plot_function(f, xmin, xmax, steps, 0, True) # label it a = _pylab.gca() th = "th" if x_derivative == 1: th = "st" if x_derivative == 2: th = "nd" if x_derivative == 3: th = "rd" if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline") else: a.set_ylabel(self.zlabel) a.set_xlabel(self.xlabel) a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel) a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y)) if format: _s.format_figure() return a
[ "def", "plot_fixed_y", "(", "self", ",", "y_values", ",", "x_derivative", "=", "0", ",", "steps", "=", "1000", ",", "smooth", "=", "0", ",", "simple", "=", "'auto'", ",", "xmin", "=", "\"auto\"", ",", "xmax", "=", "\"auto\"", ",", "format", "=", "Tru...
plots the data at a fixed y-value, so z vs y
[ "plots", "the", "data", "at", "a", "fixed", "y", "-", "value", "so", "z", "vs", "y" ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L298-L329
train
39,695
Spinmob/spinmob
egg/_gui.py
BaseObject.get_window
def get_window(self): """ Returns the object's parent window. Returns None if no window found. """ x = self while not x._parent == None and \ not isinstance(x._parent, Window): x = x._parent return x._parent
python
def get_window(self): """ Returns the object's parent window. Returns None if no window found. """ x = self while not x._parent == None and \ not isinstance(x._parent, Window): x = x._parent return x._parent
[ "def", "get_window", "(", "self", ")", ":", "x", "=", "self", "while", "not", "x", ".", "_parent", "==", "None", "and", "not", "isinstance", "(", "x", ".", "_parent", ",", "Window", ")", ":", "x", "=", "x", ".", "_parent", "return", "x", ".", "_p...
Returns the object's parent window. Returns None if no window found.
[ "Returns", "the", "object", "s", "parent", "window", ".", "Returns", "None", "if", "no", "window", "found", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L93-L101
train
39,696
Spinmob/spinmob
egg/_gui.py
BaseObject.block_events
def block_events(self): """ Prevents the widget from sending signals. """ self._widget.blockSignals(True) self._widget.setUpdatesEnabled(False)
python
def block_events(self): """ Prevents the widget from sending signals. """ self._widget.blockSignals(True) self._widget.setUpdatesEnabled(False)
[ "def", "block_events", "(", "self", ")", ":", "self", ".", "_widget", ".", "blockSignals", "(", "True", ")", "self", ".", "_widget", ".", "setUpdatesEnabled", "(", "False", ")" ]
Prevents the widget from sending signals.
[ "Prevents", "the", "widget", "from", "sending", "signals", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L132-L137
train
39,697
Spinmob/spinmob
egg/_gui.py
BaseObject.unblock_events
def unblock_events(self): """ Allows the widget to send signals. """ self._widget.blockSignals(False) self._widget.setUpdatesEnabled(True)
python
def unblock_events(self): """ Allows the widget to send signals. """ self._widget.blockSignals(False) self._widget.setUpdatesEnabled(True)
[ "def", "unblock_events", "(", "self", ")", ":", "self", ".", "_widget", ".", "blockSignals", "(", "False", ")", "self", ".", "_widget", ".", "setUpdatesEnabled", "(", "True", ")" ]
Allows the widget to send signals.
[ "Allows", "the", "widget", "to", "send", "signals", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L139-L144
train
39,698
Spinmob/spinmob
egg/_gui.py
BaseObject.print_message
def print_message(self, message="heya!"): """ If self.log is defined to be an instance of TextLog, it print the message there. Otherwise use the usual "print" to command line. """ if self.log == None: print(message) else: self.log.append_text(message)
python
def print_message(self, message="heya!"): """ If self.log is defined to be an instance of TextLog, it print the message there. Otherwise use the usual "print" to command line. """ if self.log == None: print(message) else: self.log.append_text(message)
[ "def", "print_message", "(", "self", ",", "message", "=", "\"heya!\"", ")", ":", "if", "self", ".", "log", "==", "None", ":", "print", "(", "message", ")", "else", ":", "self", ".", "log", ".", "append_text", "(", "message", ")" ]
If self.log is defined to be an instance of TextLog, it print the message there. Otherwise use the usual "print" to command line.
[ "If", "self", ".", "log", "is", "defined", "to", "be", "an", "instance", "of", "TextLog", "it", "print", "the", "message", "there", ".", "Otherwise", "use", "the", "usual", "print", "to", "command", "line", "." ]
f037f5df07f194bcd4a01f4d9916e57b9e8fb45a
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L170-L176
train
39,699