code stringlengths 17 6.64M |
|---|
def planetMassType(mass):
" Returns the planet masstype given the mass and using planetAssumptions['massType']\n "
if (mass is np.nan):
return None
for (massLimit, massType) in planetAssumptions['massType']:
if (mass < massLimit):
return massType
|
def planetRadiusType(radius):
" Returns the planet radiustype given the mass and using planetAssumptions['radiusType']\n "
if (radius is np.nan):
return None
for (radiusLimit, radiusType) in planetAssumptions['radiusType']:
if (radius < radiusLimit):
return radiusType
|
def planetTempType(temperature):
" Returns the planet masstype given the temperature and using planetAssumptions['tempType']\n "
for (tempLimit, tempType) in planetAssumptions['tempType']:
if (temperature < tempLimit):
return tempType
|
def planetType(temperature, mass, radius):
" Returns the planet type as 'temperatureType massType'\n "
if (mass is not np.nan):
sizeType = planetMassType(mass)
elif (radius is not np.nan):
sizeType = planetRadiusType(radius)
else:
return None
return '{0} {1}'.format(planetTempType(temperature), sizeType)
|
def planetMu(sizeType):
return planetAssumptions['mu'][sizeType]
|
def planetAlbedo(tempType):
return planetAssumptions['albedo'][tempType]
|
def planetDensity(radiusType):
return planetAssumptions['density'][radiusType]
|
class OECDatabase(object):
' This Class Handles the OEC database including search functions.\n '
def __init__(self, databaseLocation, stream=False):
' Holds the Open Exoplanet Catalogue database in python\n\n :param databaseLocation: file path to the Open Exoplanet Catalogue systems folder ie\n ~/git/open-exoplanet-catalogue-atmospheres/systems/\n get the catalogue from https://github.com/hannorein/open_exoplanet_catalogue\n OR the stream object (used by load_db_from_url)\n :param stream: if true treats the databaseLocation as a stream object\n '
self._loadDatabase(databaseLocation, stream)
self._planetSearchDict = self._generatePlanetSearchDict()
self.systemDict = dict(((system.name, system) for system in self.systems))
self.binaryDict = dict(((binary.name, binary) for binary in self.binaries))
self.starDict = dict(((star.name, star) for star in self.stars))
self.planetDict = dict(((planet.name, planet) for planet in self.planets))
def __repr__(self):
return 'OECDatabase({} Systems, {} Binaries, {} Stars, {} Planets)'.format(len(self.systems), len(self.binaries), len(self.stars), len(self.planets))
def searchPlanet(self, name):
' Searches the database for a planet. Input can be complete ie GJ1214b, alternate name variations or even\n just 1214.\n\n :param name: the name of the planet to search\n :return: dictionary of results as planetname -> planet object\n '
searchName = compactString(name)
returnDict = {}
for (altname, planetObj) in self._planetSearchDict.iteritems():
if re.search(searchName, altname):
returnDict[planetObj.name] = planetObj
if returnDict:
if (len(returnDict) == 1):
return returnDict.values()[0]
else:
return returnDict.values()
else:
return False
@property
def transitingPlanets(self):
' Returns a list of transiting planet objects\n '
transitingPlanets = []
for planet in self.planets:
try:
if planet.isTransiting:
transitingPlanets.append(planet)
except KeyError:
pass
return transitingPlanets
def _generatePlanetSearchDict(self):
" Generates a search dictionary for planets by taking all names and 'flattening' them to the most compact form\n (lowercase, no spaces and dashes)\n "
planetNameDict = {}
for planet in self.planets:
name = planet.name
altnames = planet.params['altnames']
altnames.append(name)
for altname in altnames:
reducedname = compactString(altname)
planetNameDict[reducedname] = planet
return planetNameDict
def _loadDatabase(self, databaseLocation, stream=False):
' Loads the database from a given file path in the class\n\n :param databaseLocation: the location on disk or the stream object\n :param stream: if true treats the databaseLocation as a stream object\n '
self.systems = []
self.binaries = []
self.stars = []
self.planets = []
if stream:
tree = ET.parse(databaseLocation)
for system in tree.findall('.//system'):
self._loadSystem(system)
else:
databaseXML = glob.glob(os.path.join(databaseLocation, '*.xml'))
if (not len(databaseXML)):
raise LoadDataBaseError('could not find the database xml files. Have you given the correct location to the open exoplanet catalogues /systems folder?')
for filename in databaseXML:
try:
with open(filename, 'r') as f:
tree = ET.parse(f)
except ET.ParseError as e:
raise LoadDataBaseError(e)
root = tree.getroot()
if (not (root.tag == 'system')):
raise LoadDataBaseError('file {0} does not contain a valid system - could be an error with your version of the catalogue'.format(filename))
self._loadSystem(root)
def _loadSystem(self, root):
systemParams = Parameters()
for systemXML in root:
tag = systemXML.tag
text = systemXML.text
attrib = systemXML.attrib
systemParams.addParam(tag, text, attrib)
system = System(systemParams.params)
self.systems.append(system)
self._loadBinarys(root, system)
self._loadStars(root, system)
def _loadBinarys(self, parentXML, parent):
binarysXML = parentXML.findall('binary')
for binaryXML in binarysXML:
binaryParams = BinaryParameters()
for value in binaryXML:
tag = value.tag
text = value.text
attrib = value.attrib
binaryParams.addParam(tag, text, attrib)
binary = Binary(binaryParams.params)
binary.parent = parent
parent._addChild(binary)
self._loadBinarys(binaryXML, binary)
self._loadStars(binaryXML, binary)
self._loadPlanets(binaryXML, binary)
self.binaries.append(binary)
def _loadStars(self, parentXML, parent):
starsXML = parentXML.findall('star')
for starXML in starsXML:
starParams = StarParameters()
for value in starXML:
tag = value.tag
text = value.text
attrib = value.attrib
starParams.addParam(tag, text, attrib)
star = Star(starParams.params)
star.parent = parent
parent._addChild(star)
self._loadPlanets(starXML, star)
self.stars.append(star)
def _loadPlanets(self, parentXML, parent):
planetsXML = parentXML.findall('planet')
for planetXML in planetsXML:
planetParams = PlanetParameters()
for value in planetXML:
tag = value.tag
text = value.text
attrib = value.attrib
planetParams.addParam(tag, text, attrib)
planet = Planet(planetParams.params)
planet.parent = parent
parent._addChild(planet)
self.planets.append(planet)
|
def load_db_from_url(url='https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz'):
' Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo\n in the OpenExoplanetCatalogue GitHub group.\n\n The database is loaded from the url in memory\n\n :param url: url to load (must be gzipped version of systems folder)\n :return: OECDatabase objected initialised with latest OEC Version\n '
catalogue = gzip.GzipFile(fileobj=io.BytesIO(requests.get(url).content))
database = OECDatabase(catalogue, stream=True)
return database
|
class LoadDataBaseError(IOError):
pass
|
def genExampleSystem():
systemPar = Parameters()
systemPar.addParam('name', ('Example System ' + str(ac._ExampleSystemCount)))
systemPar.addParam('distance', 58)
systemPar.addParam('declination', '+04 05 06')
systemPar.addParam('rightascension', '01 02 03')
exampleSystem = System(systemPar.params)
exampleSystem.flags.addFlag('Fake')
ac._ExampleSystemCount += 1
return exampleSystem
|
def genExampleBinary():
binaryPar = BinaryParameters()
binaryPar.addParam('name', 'Example Binary {0}AB'.format(ac._ExampleSystemCount))
binaryPar.addParam('semimajoraxis', 10)
binaryPar.addParam('period', 10)
exampleBinary = Binary(binaryPar.params)
exampleBinary.flags.addFlag('Fake')
exampleStar2 = genExampleStar('B', False)
exampleStar2.parent = exampleBinary
exampleBinary._addChild(exampleStar2)
exampleSystem = genExampleSystem()
exampleSystem._addChild(exampleBinary)
exampleBinary.parent = exampleSystem
return exampleBinary
|
def genExampleStar(binaryLetter='', heirarchy=True):
' generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a\n system and link everything up\n '
starPar = StarParameters()
starPar.addParam('age', '7.6')
starPar.addParam('magB', '9.8')
starPar.addParam('magH', '7.4')
starPar.addParam('magI', '7.6')
starPar.addParam('magJ', '7.5')
starPar.addParam('magK', '7.3')
starPar.addParam('magV', '9.0')
starPar.addParam('mass', '0.98')
starPar.addParam('metallicity', '0.43')
starPar.addParam('name', 'Example Star {0}{1}'.format(ac._ExampleSystemCount, binaryLetter))
starPar.addParam('name', 'HD {0}{1}'.format(ac._ExampleSystemCount, binaryLetter))
starPar.addParam('radius', '0.95')
starPar.addParam('spectraltype', 'G5')
starPar.addParam('temperature', '5370')
exampleStar = Star(starPar.params)
exampleStar.flags.addFlag('Fake')
if heirarchy:
if binaryLetter:
exampleBinary = genExampleBinary()
exampleBinary._addChild(exampleStar)
exampleStar.parent = exampleBinary
else:
exampleSystem = genExampleSystem()
exampleSystem._addChild(exampleStar)
exampleStar.parent = exampleSystem
return exampleStar
|
def genExamplePlanet(binaryLetter=''):
' Creates a fake planet with some defaults\n :param `binaryLetter`: host star is part of a binary with letter binaryletter\n :return:\n '
planetPar = PlanetParameters()
planetPar.addParam('discoverymethod', 'transit')
planetPar.addParam('discoveryyear', '2001')
planetPar.addParam('eccentricity', '0.09')
planetPar.addParam('inclination', '89.2')
planetPar.addParam('lastupdate', '12/12/08')
planetPar.addParam('mass', '3.9')
planetPar.addParam('name', 'Example Star {0}{1} b'.format(ac._ExampleSystemCount, binaryLetter))
planetPar.addParam('period', '111.2')
planetPar.addParam('radius', '0.92')
planetPar.addParam('semimajoraxis', '0.449')
planetPar.addParam('temperature', '339.6')
planetPar.addParam('transittime', '2454876.344')
planetPar.addParam('separation', '330', {'unit': 'AU'})
examplePlanet = Planet(planetPar.params)
examplePlanet.flags.addFlag('Fake')
exampleStar = genExampleStar(binaryLetter=binaryLetter)
exampleStar._addChild(examplePlanet)
examplePlanet.parent = exampleStar
return examplePlanet
|
class Flags(object):
def __init__(self):
self.flags = set()
def addFlag(self, flag):
if (flag in allowedFlags):
self.flags.add(flag)
else:
raise InvalidFlag
def removeFlag(self, flag):
self.flags.remove(flag)
def __repr__(self):
return 'Flags({0})'.format(str(self.flags)[4:(- 1)])
def __iter__(self):
return iter(self.flags)
|
class InvalidFlag(BaseException):
pass
|
class ExoDataError(Exception):
pass
|
class _GlobalFigure(object):
' sets up the figure and subfigure object with all the global parameters.\n '
def __init__(self, size='small'):
self.setup_fig(size)
def setup_fig(self, size='small'):
self.set_size(size)
def set_size(self, size):
" choose a preset size for the plot\n :param size: 'small' for documents or 'large' for presentations\n "
if (size == 'small'):
self._set_size_small()
elif (size == 'large'):
self._set_size_large()
else:
raise ValueError('Size must be large or small')
def _set_size_small(self):
self.fig = plt.figure(figsize=(5, 4))
self.ax = self.fig.add_subplot(1, 1, 1)
self.set_title_size(10)
self.set_axis_label_size(12)
self.set_axis_tick_label_size(12)
def _set_size_large(self):
self.fig = plt.figure(figsize=(10, 7.5))
self.ax = self.fig.add_subplot(1, 1, 1)
self.set_title_size(20)
self.set_axis_label_size(20)
self.set_axis_tick_label_size(20)
def set_global_font_size(self, fontsize):
ax = self.ax
for item in (([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels()) + ax.get_yticklabels()):
item.set_fontsize(fontsize)
plt.draw()
def set_title_size(self, fontsize):
self.ax.title.set_fontsize(fontsize)
plt.draw()
def set_axis_label_size(self, fontsize):
for axis in (self.ax.xaxis.label, self.ax.yaxis.label):
axis.set_fontsize(fontsize)
plt.draw()
def set_axis_tick_label_size(self, fontsize):
for axis in (self.ax.get_xticklabels() + self.ax.get_yticklabels()):
axis.set_fontsize(fontsize)
plt.draw()
def set_foregroundcolor(self, color):
'For the specified axes, sets the color of the frame, major ticks,\n tick labels, axis labels, title and legend\n '
ax = self.ax
for tl in (ax.get_xticklines() + ax.get_yticklines()):
tl.set_color(color)
for spine in ax.spines:
ax.spines[spine].set_edgecolor(color)
for tick in ax.xaxis.get_major_ticks():
tick.label1.set_color(color)
for tick in ax.yaxis.get_major_ticks():
tick.label1.set_color(color)
ax.axes.xaxis.label.set_color(color)
ax.axes.yaxis.label.set_color(color)
ax.axes.xaxis.get_offset_text().set_color(color)
ax.axes.yaxis.get_offset_text().set_color(color)
ax.axes.title.set_color(color)
lh = ax.get_legend()
if (lh != None):
lh.get_title().set_color(color)
lh.legendPatch.set_edgecolor('none')
labels = lh.get_texts()
for lab in labels:
lab.set_color(color)
for tl in ax.get_xticklabels():
tl.set_color(color)
for tl in ax.get_yticklabels():
tl.set_color(color)
plt.draw()
def set_backgroundcolor(self, color):
'Sets the background color of the current axes (and legend).\n Use \'None\' (with quotes) for transparent. To get transparent\n background on saved figures, use:\n pp.savefig("fig1.svg", transparent=True)\n '
ax = self.ax
ax.patch.set_facecolor(color)
lh = ax.get_legend()
if (lh != None):
lh.legendPatch.set_facecolor(color)
plt.draw()
def set_y_axis_log(self, logscale=True):
if logscale:
self.ax.set_yscale('log')
else:
self.ax.set_yscale('linear')
def set_x_axis_log(self, logscale=True):
if logscale:
self.ax.set_xscale('log')
else:
self.ax.set_xscale('linear')
|
class _AstroObjectFigs(_GlobalFigure):
' contains extra functions for dealing with input of astro objects\n '
def __init__(self, objectList, size='small'):
_GlobalFigure.__init__(self, size)
self.objectList = objectList
self._objectType = self._getInputObjectTypes()
def _getInputObjectTypes(self):
firstObject = self.objectList[0]
firstObjectType = type(firstObject)
for astroObject in self.objectList:
if (not (firstObjectType == type(astroObject))):
raise TypeError('Input object list contains mixed types ({0} and {1})'.format(firstObjectType, type(astroObject)))
return firstObjectType
def _getParLabelAndUnit(self, param):
' checks param to see if it contains a parent link (ie star.) then returns the correct unit and label for the\n job from the parDicts\n :return:\n '
firstObject = self.objectList[0]
if isinstance(firstObject, ac.Planet):
if ('star.' in param):
return _starPars[param[5:]]
else:
return _planetPars[param]
elif isinstance(firstObject, ac.Star):
return _starPars[param]
else:
raise TypeError('Only Planets and Star object are currently supported, you gave {0}'.format(type(firstObject)))
def _gen_label(self, param, unit):
parValues = self._getParLabelAndUnit(param)
if (unit is None):
return parValues[0]
else:
unitsymbol = self._get_unit_symbol(unit)
return '{0} ({1})'.format(parValues[0], unitsymbol)
def _get_unit_symbol(self, unit):
' Every quantities object has a symbol, but i have added `latex_symbol` for some types. This first checks for\n a latex symbol and then if it fails will just use symbol\n :return:\n '
try:
return '${0}$'.format(unit.latex_symbol)
except AttributeError:
return unit.symbol
|
class _BaseDataPerClass(_AstroObjectFigs):
' Base class for plots counting the results by a attribute. Child classes must modify\n * _classVariables (self._allowedKeys, )\n * _getSortKey (take the planet, turn it into a key)\n '
def __init__(self, astroObjectList, unit=None, size='small'):
_AstroObjectFigs.__init__(self, astroObjectList, size)
self._classVariables()
self.unit = unit
self.resultsByClass = self._processResults()
def _set_size_small(self):
_AstroObjectFigs._set_size_small(self)
self.xticksize = 8
def _set_size_large(self):
_AstroObjectFigs._set_size_large(self)
self.xticksize = 15
def _classVariables(self):
' Variables to be loaded in init by child classes\n\n must set\n *self._allowedKeys = (tuple of keys)\n '
self._allowedKeys = 'Class'
def _getSortKey(self, planet):
' Takes a planet and turns it into a key to be sorted by\n :param planet:\n :return:\n '
return 'Class'
def _processResults(self):
' Checks each result can meet SNR requirments, adds to count\n :return:\n '
resultsByClass = self._genEmptyResults()
for astroObject in self.objectList:
sortKey = self._getSortKey(astroObject)
resultsByClass[sortKey] += 1
return resultsByClass
def _getPlotData(self):
' Turns the resultsByClass Dict into a list of bin groups skipping the uncertain group if empty\n\n return: (label list, ydata list)\n :rtype: tuple(list(str), list(float))\n '
resultsByClass = self.resultsByClass
try:
if (resultsByClass['Uncertain'] == 0):
resultsByClass.pop('Uncertain', None)
except KeyError:
pass
plotData = list(zip(*resultsByClass.items()))
return plotData
def plotBarChart(self, title='', xlabel=None, c='#3ea0e4', label_rotation=False):
ax = self.ax
(labels, ydata) = self._getPlotData()
numItems = float(len(ydata))
ind = np.arange(numItems)
ind /= numItems
spacePerBar = (1.0 / numItems)
gapratio = 0.5
width = (spacePerBar * gapratio)
gap = (spacePerBar - width)
ax.bar(ind, ydata, width, color=c)
ax.set_xticklabels(labels)
ax.set_xticks((ind + (width / 2.0)))
for axis in self.ax.get_xticklabels():
axis.set_fontsize(self.xticksize)
if (self.unit is None):
self.unit = self._getParLabelAndUnit(self._planetProperty)[1]
self._yaxis_unit = self.unit
if (xlabel is None):
plt.xlabel(self._gen_label(self._planetProperty, self.unit))
else:
plt.xlabel(xlabel)
if label_rotation:
plt.xticks(rotation=label_rotation)
plt.ylabel('Number of Planets')
plt.title(title)
plt.xlim([(min(ind) - gap), (max(ind) + (gap * 2))])
plt.draw()
def plotPieChart(self, title=None, cmap_name='Pastel2'):
if (sys.hexversion >= 40894464):
self.fig.set_tight_layout(True)
(labels, ydata) = self._getPlotData()
totalobjects = float(np.sum(ydata))
fracs = [(ynum / totalobjects) for ynum in ydata]
explode = np.zeros(len(fracs))
cmap = plt.cm.get_cmap(cmap_name)
colors = cmap(np.linspace(0.0, 0.9, len(fracs)))
plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=False, startangle=90, colors=colors)
for axis in self.ax.get_xticklabels():
axis.set_fontsize(self.xticksize)
if (self.unit is None):
self.unit = self._getParLabelAndUnit(self._planetProperty)[1]
self._yaxis_unit = self.unit
if (title is None):
title = 'Planet {0} Bins'.format(self._gen_label(self._planetProperty, self.unit))
plt.title(title)
plt.xlim((- 1.5), 1.5)
def saveAllBarChart(self, filepath, *args, **kwargs):
self.plotBarChart(*args, **kwargs)
plt.savefig(os.path.join(filepath))
def _genEmptyResults(self):
' Uses allowed keys to generate a empty dict to start counting from\n :return:\n '
allowedKeys = self._allowedKeys
keysDict = OrderedDict()
for k in allowedKeys:
keysDict[k] = 0
resultsByClass = keysDict
return resultsByClass
|
class DataPerParameterBin(_BaseDataPerClass):
' Generates Data for planets per parameter bin'
def __init__(self, results, planetProperty, binLimits, unit=None, size='small'):
"\n :param planetProperty: property of planet to bin. IE 'e' for eccentricity, 'star.magV' for magV\n :param binLimits: list of bin limits (lower limit, upper, upper, maximum) (note you can have maximum +)\n :param unit: unit to scale param to (see general plotter)\n :return:\n "
self._binlimits = binLimits
self._planetProperty = planetProperty
self._genKeysBins()
_BaseDataPerClass.__init__(self, results, unit, size)
def _getSortKey(self, planet):
' Takes a planet and turns it into a key to be sorted by\n :param planet:\n :return:\n '
value = eval(('planet.' + self._planetProperty))
if (self.unit is not None):
try:
value = value.rescale(self.unit)
except AttributeError:
pass
return _sortValueIntoGroup(self._allowedKeys[:(- 1)], self._binlimits, value)
def _classVariables(self):
pass
def _genKeysBins(self):
' Generates keys from bins, sets self._allowedKeys normally set in _classVariables\n '
binlimits = self._binlimits
allowedKeys = []
midbinlimits = binlimits
if (binlimits[0] == (- float('inf'))):
midbinlimits = binlimits[1:]
allowedKeys.append('<{0}'.format(midbinlimits[0]))
if (binlimits[(- 1)] == float('inf')):
midbinlimits = midbinlimits[:(- 1)]
lastbin = midbinlimits[0]
for binlimit in midbinlimits[1:]:
if (lastbin == binlimit):
allowedKeys.append('{0}'.format(binlimit))
else:
allowedKeys.append('{0} to {1}'.format(lastbin, binlimit))
lastbin = binlimit
if (binlimits[(- 1)] == float('inf')):
allowedKeys.append('{0}+'.format(binlimits[(- 2)]))
allowedKeys.append('Uncertain')
self._allowedKeys = allowedKeys
|
class GeneralPlotter(_AstroObjectFigs):
' This class should be able to create a plot with lots of options like the online visual plots. In future it\n should be turned into a GUI\n '
def __init__(self, objectList, xaxis=None, yaxis=None, xunit=None, yunit=None, xaxislog=False, yaxislog=False, size='small'):
"\n :param objectList: list of astro objects to use in plot ie planets, stars etc\n :param xaxis: value to use on the xaxis, should be a variable or function of the objects in objectList. ie 'R'\n for the radius variable and 'calcDensity()' for the calcDensity function\n :param yaxis: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'\n for the radius variable and 'calcDensity()' for the calcDensity function\n\n :type objectList: list, tuple\n :type xaxis: str\n :type yaxis: str\n "
_AstroObjectFigs.__init__(self, objectList, size)
self.set_marker_color()
self.set_marker_size()
self.marker = 'o'
self.xlabel = None
self.ylabel = None
if xaxis:
self.set_xaxis(xaxis, xunit)
else:
self._xaxis = None
if yaxis:
self.set_yaxis(yaxis, yunit)
else:
self._yaxis = None
self.set_x_axis_log(xaxislog)
self.set_y_axis_log(yaxislog)
def _set_size_large(self):
_AstroObjectFigs._set_size_large(self)
self.set_marker_size(60)
def plot(self):
xaxis = [float(x) for x in self._xaxis]
yaxis = [float(y) for y in self._yaxis]
assert (len(xaxis) == len(yaxis))
plt.scatter(xaxis, yaxis, marker=self.marker, facecolor=self._marker_color, edgecolor=self._edge_color, s=self._marker_size)
plt.xlabel(self.xlabel)
plt.ylabel(self.ylabel)
def set_xaxis(self, param, unit=None, label=None):
' Sets the value of use on the x axis\n :param param: value to use on the xaxis, should be a variable or function of the objects in objectList. ie \'R\'\n for the radius variable and \'calcDensity()\' for the calcDensity function\n\n :param unit: the unit to scale the values to, None will use the default\n :type unit: quantities unit or None\n\n :param label: axis label to use, if None "Parameter (Unit)" is generated here and used\n :type label: str\n '
if (unit is None):
unit = self._getParLabelAndUnit(param)[1]
self._xaxis_unit = unit
self._xaxis = self._set_axis(param, unit)
if (label is None):
self.xlabel = self._gen_label(param, unit)
else:
self.xlabel = label
def set_yaxis(self, param, unit=None, label=None):
' Sets the value of use on the yaxis\n :param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie \'R\'\n for the radius variable and \'calcDensity()\' for the calcDensity function\n\n :param unit: the unit to scale the values to\n :type unit: quantities unit or None\n\n :param label: axis label to use, if None "Parameter (Unit)" is generated here and used\n :type label: str\n '
if (unit is None):
unit = self._getParLabelAndUnit(param)[1]
self._yaxis_unit = unit
self._yaxis = self._set_axis(param, unit)
if (label is None):
self.ylabel = self._gen_label(param, unit)
else:
self.ylabel = label
def _set_axis(self, param, unit):
' this should take a variable or a function and turn it into a list by evaluating on each planet\n '
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except ac.HierarchyError:
value = np.nan
if (unit is None):
axisValues.append(value)
else:
try:
axisValues.append(value.rescale(unit))
except AttributeError:
axisValues.append(value)
return axisValues
def set_marker_color(self, color='#3ea0e4', edgecolor='k'):
" set the marker color used in the plot\n :param color: matplotlib color (ie 'r', '#000000')\n "
self._marker_color = color
self._edge_color = edgecolor
def set_marker_size(self, size=30):
' set the marker size used in the plot\n :param size: matplotlib size\n '
self._marker_size = size
|
class DiscoveryMethodByYear(object):
def __init__(self, planet_list, methods_to_plot=('RV', 'transit', 'Other'), skip_solar_system_planets=True):
" Produces a labelled stacked bar chart of planet discovery methods\n\n\n :param planet_list: list of planet objects\n :param methods_to_plot: list of discovery methods to plot (OEC syntax)\n , use 'other' to group non specified methods\n :param skip_solar_system_planets: don't include solar system planets\n (including them will really stretch the xscale)\n "
self.planet_list = planet_list
self.skip_solar_system_planets = skip_solar_system_planets
self.methods_to_plot = methods_to_plot
def setup_keys(self):
' Build the initial data dictionary to store the values\n '
discovery_methods = {}
discovery_years = {}
nan_list = []
for planet in self.planet_list:
if (('Solar System' in planet.params['list']) and self.skip_solar_system_planets):
continue
try:
discovery_methods[planet.discoveryMethod] += 1
except KeyError:
discovery_methods[planet.discoveryMethod] = 1
try:
discovery_years[planet.discoveryYear] += 1
except KeyError:
discovery_years[planet.discoveryYear] = 1
if (planet.discoveryMethod is np.nan):
nan_list.append(planet)
self.nan_list = nan_list
return discovery_years
def generate_data(self):
discovery_years = self.setup_keys()
_year_list = np.array([year for year in discovery_years.keys() if (year is not np.nan)])
year_list = range(_year_list.min(), (_year_list.max() + 1))
discovery_methods = {k: 0 for k in self.methods_to_plot}
plot_matrix = {k: discovery_methods.copy() for k in year_list}
for planet in self.planet_list:
if (('Solar System' in planet.params['list']) and self.skip_solar_system_planets):
continue
if (planet.discoveryMethod in self.methods_to_plot):
discovery_method = planet.discoveryMethod
else:
discovery_method = 'Other'
try:
plot_matrix[planet.discoveryYear][discovery_method] += 1
except KeyError:
pass
return (plot_matrix, year_list, discovery_years)
def plot(self, method_labels=None, exodata_credit=True):
"\n :param method_labels: list of legend labels for the methods, i.e. give\n 'Radial Velocity' rather than 'RV'\n\n :return:\n "
if (method_labels is None):
method_labels = self.methods_to_plot
(plot_matrix, year_list, discovery_years) = self.generate_data()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(len(year_list))
colors = [(0.8941176533699036, 0.10196078568696976, 0.10980392247438431), (0.2160246080043269, 0.49487120380588606, 0.7198769869757634), (0.30426760128900115, 0.6832910605505401, 0.29293349969620797), (0.6008304736193488, 0.30814303335021526, 0.6316955229815315), (1.0, 0.5059131104572147, 0.0031372549487095253), (0.9931564786854912, 0.9870049982678657, 0.19915417450315812), (0.6584544609574711, 0.34122261685483596, 0.1707958535236471), (0.9585082685246187, 0.5084660039228551, 0.7449288887136123)]
width = 0.9
bottom = np.zeros_like(year_list)
for (i, method) in enumerate(self.methods_to_plot):
bar_data = [plot_matrix[year][method] for year in year_list]
plt.bar(ind, bar_data, width, color=colors[i], bottom=bottom, label=method_labels[i], linewidth=0)
bottom += np.array(bar_data)
plt.ylabel('Number of planets', fontsize=14)
plt.xlabel('Year', fontsize=14)
plt.xticks((ind + (width / 2.0)), year_list, rotation=70, fontsize=13)
plt.xlim(0, (ind[(- 1)] + 1))
plt.legend(loc=2, fontsize=13)
if (exodata_credit is True):
ax.text(2, 420, 'Generated by ExoData on {}'.format(time.strftime('%d/%m/%Y')), fontsize=11)
for (i, year) in enumerate(year_list):
try:
total_planets = discovery_years[year]
except KeyError:
continue
y_pos = (bottom[i] + 10)
x_pos = i
ax.text(x_pos, y_pos, '{}'.format(total_planets), fontsize=9)
plt.grid(b=True, which='both', color='0.9', linestyle='-')
return fig
|
def _sortValueIntoGroup(groupKeys, groupLimits, value):
" returns the Key of the group a value belongs to\n :param groupKeys: a list/tuple of keys ie ['1-3', '3-5', '5-8', '8-10', '10+']\n :param groupLimits: a list of the limits for the group [1,3,5,8,10,float('inf')] note the first value is an absolute\n minimum and the last an absolute maximum. You can therefore use float('inf')\n :param value:\n :return:\n "
if (not (len(groupKeys) == (len(groupLimits) - 1))):
raise ValueError('len(groupKeys) must equal len(grouplimits)-1 got \nkeys:{0} \nlimits:{1}'.format(groupKeys, groupLimits))
if math.isnan(value):
return 'Uncertain'
keyIndex = None
if (value == groupLimits[0]):
keyIndex = 1
elif (value == groupLimits[(- 1)]):
keyIndex = (len(groupLimits) - 1)
else:
for (i, limit) in enumerate(groupLimits):
if (value < limit):
keyIndex = i
break
if (keyIndex == 0):
raise BelowLimitsError('Value {0} below limit {1}'.format(value, groupLimits[0]))
if (keyIndex is None):
raise AboveLimitsError('Value {0} above limit {1}'.format(value, groupLimits[(- 1)]))
return groupKeys[(keyIndex - 1)]
|
class OutOfLimitsError(Exception):
pass
|
class BelowLimitsError(Exception):
pass
|
class AboveLimitsError(Exception):
pass
|
def accept(f):
def test_works(self, T_eff=not_set, mu=not_set, g=not_set):
return f(self=self, T_eff=T_eff, mu=mu, g=g)
return test_works
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, R_p=not_set, R_s=not_set):
return f(self=self, R_p=R_p, R_s=R_s)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, T_eff=not_set, mu=not_set, g=not_set):
return f(self=self, T_eff=T_eff, mu=mu, g=g)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, A, T_s=not_set, R_s=not_set, a=not_set, epsilon=not_set):
return f(self=self, A=A, T_s=T_s, R_s=R_s, a=a, epsilon=epsilon)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, a=not_set, M_s=not_set, M_p=not_set):
return f(self=self, a=a, M_s=M_s, M_p=M_p)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, M=not_set, R=not_set):
return f(self=self, M=M, R=R)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, T=not_set, R=not_set):
return f(self=self, T=T, R=R)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_can_derive_other_vars_from_one_calculated(self, A=not_set, T_s=not_set, R_s=not_set, a=not_set, epsilon=not_set):
return f(self=self, A=A, T_s=T_s, R_s=R_s, a=a, epsilon=epsilon)
return test_can_derive_other_vars_from_one_calculated
|
def accept(f):
def test_works(self, T_eff=not_set, mu=not_set, g=not_set, H=not_set):
return f(self=self, T_eff=T_eff, mu=mu, g=g, H=H)
return test_works
|
class TestCase(unittest.TestCase):
' adds the assertItemsEqual back in python 3 by referencing assertCountEqual. This should by subclassed over\n unitest.Testcase by all test classes now\n '
def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
if (sys.hexversion < 50331648):
return unittest.TestCase.assertItemsEqual(self, expected_seq, actual_seq, msg)
else:
return unittest.TestCase.assertCountEqual(self, expected_seq, actual_seq, msg)
def assertItemsAlmostEqual(self, expected_seq, actual_seq, places, msg=None):
' checks the length of both sequences and then each item is almost equal in turn. Order matters\n '
self.assertEqual(len(expected_seq), len(actual_seq))
for (i, item) in enumerate(expected_seq):
self.assertAlmostEqual(item, actual_seq[i], places, msg)
|
class Test_planetAssumptions(TestCase):
def test_MassType(self):
pass
|
class TestListFiles(TestCase):
def create_Parameter_object(self):
params = {'RA': 111111, 'DEC': 222222, 'name': 'monty'}
paramObj = Parameters()
paramObj.params.update(params)
return paramObj
def test_addParam_works_no_duplicate(self):
paramObj = self.create_Parameter_object()
paramObj.addParam('radius', '12')
self.assertEqual(paramObj.params['radius'], '12')
def test_addParam_works_recognised_duplicate_name(self):
paramObj = self.create_Parameter_object()
paramObj.addParam('name', 'python')
self.assertEqual(paramObj.params['name'], 'monty')
self.assertEqual(paramObj.params['altnames'], ['python'])
def test_addParam_works_unrecognised_duplicate(self):
paramObj = self.create_Parameter_object()
paramObj.addParam('RA', 333333)
self.assertEqual(paramObj.params['RA'], 111111)
def test_addParam_name_type_pri_overwrites(self):
paramObj = self.create_Parameter_object()
paramObj.addParam('name', 'first')
paramObj.addParam('name', 'popular', {'type': 'pri'})
paramObj.addParam('name', 'last')
self.assertEqual(paramObj.params['name'], 'popular')
self.assertItemsEqual(paramObj.params['altnames'], ('first', 'last', 'monty'))
def test_empty_Planet_init(self):
Planet().__repr__()
def test_empty_Star_init(self):
Star().__repr__()
def test_empty_System_init(self):
System().__repr__()
def test_empty_Binary_init(self):
Binary().__repr__()
|
class TestAstroObject__eq__method(TestCase):
def setUp(self):
self.object1 = _BaseObject()
self.object1.params = {'name': 'name1', 'radius': (10 * aq.km), 'd': 1}
def test_astroObject_same_object_is_eq(self):
self.assertEqual(self.object1, self.object1)
def test_astroObject_is_eq_same_param_dict(self):
object2 = _BaseObject()
object2.params = self.object1.params
self.assertEqual(self.object1, object2)
def test_astroObject_is_neq_changed_param_dict(self):
object2 = _BaseObject()
object2.params = {'name': 'name1', 'radius': (10 * aq.km), 'd': 2}
self.assertNotEqual(self.object1, object2)
def test_astroObject_is_eq_different_param_dict_same_values(self):
object2 = _BaseObject()
object2.params = {'name': 'name1', 'radius': (10 * aq.km), 'd': 1}
self.assertEqual(self.object1, object2)
def test_planet_and_star_same_params_are_neq(self):
planet = Planet()
planet.params = {'name': 'name1', 'radius': (10 * aq.km), 'd': 1}
star = Star()
star.params = {'name': 'name1', 'radius': (10 * aq.km), 'd': 1}
self.assertNotEqual(planet, star)
|
class TestStarParameters(TestCase):
def test_getLimbdarkeningCoeff_works(self):
pass
def test_distance_estimation_fails_invalid_spectral_type(self):
' If theres no distance, will try to calculate based on spectral type\n '
planet = genExamplePlanet()
star = planet.star
star.params['spectraltype'] = 'C'
star.parent.params.pop('distance')
self.assertTrue((star.d is np.nan))
self.assertTrue((planet.d is np.nan))
def test_distance_estimation_works(self):
planet = genExamplePlanet()
star = planet.star
star.params['spectraltype'] = 'A4'
star.params['magV'] = 5
star.parent.params.pop('distance')
self.assertAlmostEqual(star.d, (45.19 * aq.pc), 2)
self.assertTrue(('Estimated Distance' in star.flags.flags))
def test_distance_estimation_not_called_if_d_present(self):
planet = genExamplePlanet()
star = planet.star
star.parent.params['distance'] = 10
self.assertEqual(star.d, (10 * aq.pc))
self.assertFalse(('Estimated Distance' in star.flags.flags))
def test_magV_when_present(self):
planet = genExamplePlanet()
star = planet.star
self.assertEqual(star.magV, 9.0)
self.assertFalse(('Estimated magV' in star.flags.flags))
def test_magV_when_absent_converts_k(self):
planet = genExamplePlanet()
star = planet.star
star.params.pop('magV')
self.assertAlmostEqual(star.magV, 9.14, 2)
self.assertTrue(('Estimated magV' in star.flags.flags))
|
class TestFindNearest(TestCase):
def setUp(self):
self.arr = np.array([1.2, 4, 6, 7.0, 9.5, 10, 11, 12])
def test_exact_value_returns_exact(self):
self.assertEqual(_findNearest(self.arr, 6), 6)
def test_below_first_value_works(self):
self.assertEqual(_findNearest(self.arr, 0.8), 1.2)
def test_above_last_value_works(self):
self.assertEqual(_findNearest(self.arr, 13), 12)
def test_mid_value_rounded_down(self):
self.assertEqual(_findNearest(self.arr, 10.5), 10)
def test_low_value_rounded_down(self):
self.assertEqual(_findNearest(self.arr, 10.4), 10)
def test_high_value_rounded_up(self):
self.assertEqual(_findNearest(self.arr, 10.6), 11)
|
class TestSpectralType(TestCase):
def test_classType_and_Type(self):
A8V = SpectralType('')
A8V.lumType = 'V'
A8V.classNumber = '8'
A8V.classLetter = 'A'
self.assertEqual(A8V.specClass, 'A8')
self.assertEqual(A8V.specType, 'A8V')
def test_works_normal_full_types(self):
A8V = SpectralType('A8V')
self.assertEqual(A8V.lumType, 'V')
self.assertEqual(A8V.classLetter, 'A')
self.assertEqual(A8V.classNumber, 8)
L0IV = SpectralType('L0IV')
self.assertEqual(L0IV.lumType, 'IV')
self.assertEqual(L0IV.classLetter, 'L')
self.assertEqual(L0IV.classNumber, 0)
def test_works_single_letter(self):
test1 = SpectralType('G')
self.assertEqual(test1.lumType, '')
self.assertEqual(test1.classLetter, 'G')
self.assertEqual(test1.classNumber, '')
def test_works_spec_class_only(self):
A8 = SpectralType('A8')
self.assertEqual(A8.lumType, '')
self.assertEqual(A8.classLetter, 'A')
self.assertEqual(A8.classNumber, 8)
L0 = SpectralType('L0')
self.assertEqual(L0.lumType, '')
self.assertEqual(L0.classLetter, 'L')
self.assertEqual(L0.classNumber, 0)
def test_works_multiple_classes(self):
test1 = SpectralType('K0/K1V')
self.assertEqual(test1.lumType, '')
self.assertEqual(test1.classLetter, 'K')
self.assertEqual(test1.classNumber, 0)
self.assertEqual(test1.roundedSpecType, 'K0')
test2 = SpectralType('GIV/V')
self.assertEqual(test2.lumType, 'IV')
self.assertEqual(test2.classLetter, 'G')
self.assertEqual(test2.classNumber, '')
self.assertEqual(test2.roundedSpecType, 'GIV')
test3 = SpectralType('F8-G0')
self.assertEqual(test3.lumType, '')
self.assertEqual(test3.classLetter, 'F')
self.assertEqual(test3.classNumber, 8)
self.assertEqual(test3.roundedSpecType, 'F8')
def test_works_spaces(self):
test1 = SpectralType('K1 III')
self.assertEqual(test1.lumType, 'III')
self.assertEqual(test1.classLetter, 'K')
self.assertEqual(test1.classNumber, 1)
self.assertEqual(test1.roundedSpecClass, 'K1')
self.assertEqual(test1.roundedSpecType, 'K1III')
def test_works_decimal(self):
test1 = SpectralType('K1.5III')
self.assertEqual(test1.classLetter, 'K')
self.assertEqual(test1.classNumber, 1.5)
self.assertEqual(test1.lumType, 'III')
self.assertEqual(test1.roundedSpecClass, 'K2')
self.assertEqual(test1.roundedSpecType, 'K2III')
def test_works_decmial_no_L_class(self):
test2 = SpectralType('M8.5')
self.assertEqual(test2.classLetter, 'M')
self.assertEqual(test2.classNumber, 8.5)
self.assertEqual(test2.lumType, '')
self.assertEqual(test2.roundedSpecClass, 'M8')
self.assertEqual(test2.roundedSpecType, 'M8')
def test_works_2_decimal_places(self):
test2 = SpectralType('A9.67V')
self.assertEqual(test2.classLetter, 'A')
self.assertEqual(test2.classNumber, 9.67)
self.assertEqual(test2.lumType, 'V')
def test_works_no_number_after_decimal(self):
test2 = SpectralType('B5.IV')
self.assertEqual(test2.classLetter, 'B')
self.assertEqual(test2.classNumber, 5)
self.assertEqual(test2.lumType, 'IV')
def test_works_2_letter_class(self):
test2 = SpectralType('DQ6')
self.assertEqual(test2.classLetter, 'DQ')
self.assertEqual(test2.classNumber, 6)
self.assertEqual(test2.lumType, '')
def test_works_3_letter_class(self):
test2 = SpectralType('DAV6')
self.assertEqual(test2.classLetter, 'DAV')
self.assertEqual(test2.classNumber, 6)
self.assertEqual(test2.lumType, '')
test3 = SpectralType('DA6')
self.assertEqual(test3.classLetter, 'DA')
self.assertEqual(test3.classNumber, 6)
self.assertEqual(test3.lumType, '')
def test_fake_3_letter_fails(self):
test2 = SpectralType('DAX6')
self.assertEqual(test2.classLetter, '')
self.assertEqual(test2.classNumber, '')
self.assertEqual(test2.lumType, '')
def test_works_unknown_lum_class(self):
test2 = SpectralType('G5D')
self.assertEqual(test2.classLetter, 'G')
self.assertEqual(test2.classNumber, 5)
self.assertEqual(test2.lumType, '')
def test_works_extra_info(self):
test1 = SpectralType('K2 IV a')
self.assertEqual(test1.lumType, 'IV')
self.assertEqual(test1.classLetter, 'K')
self.assertEqual(test1.classNumber, 2)
test2 = SpectralType('G8 V+')
self.assertEqual(test2.lumType, 'V')
self.assertEqual(test2.classLetter, 'G')
self.assertEqual(test2.classNumber, 8)
test3 = SpectralType('G0V pecul.')
self.assertEqual(test3.lumType, 'V')
self.assertEqual(test3.classLetter, 'G')
self.assertEqual(test3.classNumber, 0)
def test_rejects_non_standard(self):
testStrings = ('Catac. var.', 'AM Her', 'nan', np.nan)
for testStr in testStrings:
test1 = SpectralType(testStr)
self.assertEqual(test1.lumType, '', 'lumType null test for {0}'.format(testStr))
self.assertEqual(test1.classLetter, '', 'classLetter null test for {0}'.format(testStr))
self.assertEqual(test1.classNumber, '', 'classNumber null test for {0}'.format(testStr))
self.assertEqual(test1.specType, '', 'specType null test for {0}'.format(testStr))
|
class TestPlanetClass(TestCase):
def test_isTransiting_is_true_if_tag_present(self):
planet = genExamplePlanet()
planet.params['istransiting'] = '1'
self.assertTrue(planet.isTransiting)
def test_isTransiting_fails_with_missing_tag_or_incorrect_value(self):
planet = genExamplePlanet()
planet.params['istransiting'] = '0'
self.assertFalse(planet.isTransiting)
planet = genExamplePlanet()
planet.params['istransiting'] = '2'
self.assertFalse(planet.isTransiting)
planet = genExamplePlanet()
self.assertFalse(planet.isTransiting)
|
class Test_Planet_Parameter_Estimation(TestCase):
def test_sma_estimation(self):
planet = genExamplePlanet()
planet.params.pop('semimajoraxis')
self.assertAlmostEqual(planet.a, (0.449636494929 * aq.au), 5)
|
class Test_PlanetAndBinaryCommon(TestCase):
def setUp(self):
self.common_class = PlanetAndBinaryCommon()
def test_setting_of_sma(self):
initial_sma = self.common_class.a
new_sma = (1 * aq.m)
self.assertNotEqual(initial_sma, new_sma)
self.common_class.a = new_sma
self.assertEqual(self.common_class.a, new_sma)
|
class Test_Magnitude(TestCase):
def test_convert_works_magV_to_magK_auto(self):
mag = Magnitude('B6', magV=12.0)
self.assertEqual(mag.convert('K'), (12 + 0.43))
def test_convert_works_magK_to_magJ_auto(self):
mag = Magnitude('F5', magK=10.0)
self.assertEqual(mag.convert('J'), ((10 + 1.1) - 0.83))
def test_convert_works_magK_to_magB_explicit(self):
mag = Magnitude('B6', magH=19.0, magK=9.0)
self.assertEqual(mag.convert('B', 'K'), ((9.0 - 0.43) - 0.13))
self.assertEqual(mag.convert('B'), ((19.0 - 0.37) - 0.13))
def test_convert_works_magK_to_magB_auto(self):
mag = Magnitude('B6', magH=19.0, magK=9.0)
self.assertEqual(mag.convert('B'), ((19.0 - 0.37) - 0.13))
def test_convert_works_magK_to_magV_auto(self):
mag = Magnitude('B6', magH=19.0, magK=9.0)
self.assertEqual(mag.convert('V'), (19.0 - 0.37))
def test_convert_works_magK_to_magB_explicit_with_lumtype(self):
mag = Magnitude('B6V', magH=19.0, magK=9.0)
self.assertEqual(mag.convert('B', 'K'), ((9.0 - 0.43) - 0.13))
def test_convert_works_magK_to_magB_with_decimal_spec_type(self):
mag = Magnitude('M2.5', magH=19.0, magK=9.0)
self.assertAlmostEqual(mag.convert('B', 'K'), 14.63, 2)
def test_raises_ValueError_if_spectral_type_not_in_table(self):
mag = Magnitude('M9', magH=19.0, magK=9.0)
with self.assertRaises(ValueError):
mag.convert('B', 'K')
def test_raises_ValueError_if_null_spectral_type(self):
mag = Magnitude('', magH=19.0, magK=9.0)
with self.assertRaises(ValueError):
mag.convert('B', 'K')
|
class Test_isNanOrNone(TestCase):
def test_np_nan(self):
self.assertTrue(isNanOrNone(np.nan))
def test_math_nan(self):
self.assertTrue(isNanOrNone(float('nan')))
def test_float(self):
self.assertFalse(isNanOrNone((- 1.0)))
def test_int(self):
self.assertFalse(isNanOrNone(1))
def test_str(self):
self.assertFalse(isNanOrNone('nan'))
|
class TestCatalogue_Planet(TestCase):
def test_isTransiting(self):
x = [planet.isTransiting for planet in exocat.planets]
def test_calcTransitDuration(self):
x = [planet.calcTransitDuration() for planet in exocat.planets]
def test_calcTransitDuration_circular(self):
x = [planet.calcTransitDuration(circular=True) for planet in exocat.planets]
def test_a(self):
x = [planet.a for planet in exocat.planets]
def test_e(self):
x = [planet.e for planet in exocat.planets]
def test_i(self):
x = [planet.i for planet in exocat.planets]
def test_T(self):
x = [planet.T for planet in exocat.planets]
def test_albedo(self):
x = [planet.albedo for planet in exocat.planets]
|
class TestCatalogue_Star(TestCase):
def test_magV(self):
x = [star.magV for star in exocat.stars]
def test_T(self):
x = [star.T for star in exocat.stars]
def test_calcTemperature(self):
x = [star.calcTemperature() for star in exocat.stars]
|
class TestDataBaseLoading(TestCase):
def setUp(self):
self.tempDir = mkdtemp()
self._createFakeXML()
self.oecdb = OECDatabase((self.tempDir + '/'))
def _createFakeXML(self):
xmlCases = ['<system><name>System 1</name><star><name>Star 1</name></star></system>', '<system><name>System 2</name><star><name>Star 2</name><planet><name>Planet 2 b</name></planet></star></system>', '<system><name>System 3</name><star><name>Star 3</name><planet><name>Planet 3 b</name></planet><planet><name>Planet 3 c</name></planet></star></system>', '<system><name>System 4</name><binary><name>Binary 4AB</name><star><name>Star 4A</name><planet><name>Planet 4A b</name></planet></star><star><name>Star 4B</name></star></binary></system>', '<system><name>System 5</name><binary><name>Binary 5AB</name><star><name>Star 5A</name></star><binary><name>Binary 5B-AB</name><star><name>Star 5B-A</name><planet><name>Planet 5B-A b</name></planet></star><star><name>Star 5B-B</name></star></binary></binary></system>', '<system><name>System 6</name><binary><name>Binary 6AB</name><star><name>Star 6A</name></star><star><name>Star 6B</name></star><planet><name>Planet 6AB b</name></planet></binary></system>', '<system><name>System 7</name><star><name>Star 7</name><planet><name>Planet 7 b</name><separation unit="arcsec">2.2</separation><separation unit="AU">330</separation></planet></star></system>']
for systems in xmlCases:
with open(mkstemp('.xml', dir=self.tempDir)[1], 'w') as f:
f.write(systems)
def test_correct_system_number(self):
self.assertEqual(len(self.oecdb.systems), 7)
def test_correct_star_only_system(self):
system = self.oecdb.systemDict['System 1']
self.assertEqual(str(system.children), "[Star('Star 1')]")
self.assertEqual(system.children[0].children, [])
def test_correct_star_planet_system(self):
system = self.oecdb.systemDict['System 2']
self.assertEqual(str(system.children), "[Star('Star 2')]")
self.assertEqual(str(system.children[0].children), "[Planet('Planet 2 b')]")
def test_correct_star_double_planet_system(self):
system = self.oecdb.systemDict['System 3']
self.assertEqual(str(system.children), "[Star('Star 3')]")
self.assertEqual(str(system.children[0].children), "[Planet('Planet 3 b'), Planet('Planet 3 c')]")
def test_correct_binary_star_planet_system(self):
system = self.oecdb.systemDict['System 4']
self.assertEqual(str(system.children), "[Binary('Binary 4AB')]")
self.assertEqual(str(system.children[0].children), "[Star('Star 4A'), Star('Star 4B')]")
self.assertEqual(str(system.children[0].children[0].children), "[Planet('Planet 4A b')]")
self.assertEqual(system.children[0].children[1].children, [])
def test_correct_double_binary_star_planet_system(self):
system = self.oecdb.systemDict['System 5']
self.assertEqual(str(system.children), "[Binary('Binary 5AB')]")
self.assertEqual(str(system.children[0].children), "[Binary('Binary 5B-AB'), Star('Star 5A')]")
self.assertEqual(str(system.children[0].children[0].children), "[Star('Star 5B-A'), Star('Star 5B-B')]")
self.assertEqual(str(system.children[0].children[0].children[0].children), "[Planet('Planet 5B-A b')]")
self.assertEqual(system.children[0].children[1].children, [])
self.assertEqual(system.children[0].children[0].children[1].children, [])
def test_correct_binary_planet_star_system(self):
system = self.oecdb.systemDict['System 6']
self.assertEqual(str(system.children), "[Binary('Binary 6AB')]")
self.assertEqual(str(system.children[0].children), "[Star('Star 6A'), Star('Star 6B'), Planet('Planet 6AB b')]")
self.assertEqual(system.children[0].children[0].children, [])
self.assertEqual(system.children[0].children[1].children, [])
def test_seperation_tag_AU_imported_only(self):
system = self.oecdb.systemDict['System 7']
self.assertEqual(system.children[0].children[0].separation, (330 * aq.au))
def tearDown(self):
shutil.rmtree(self.tempDir)
|
class TestDataBaseFailing(TestCase):
def setUp(self):
self.tempDir = mkdtemp()
def test_raises_LoadDataBaseError_in_empty_folder(self):
with self.assertRaises(LoadDataBaseError):
OECDatabase(self.tempDir)
def test_raises_LoadDataBaseError_without_system_tag(self):
xmlCases = ['<name>System 1</name><star><name>Star 1</name></star>', '<star><name>Star 2</name><planet><name>Planet 2 b</name></planet></star>']
for systems in xmlCases:
with open(mkstemp('.xml', dir=self.tempDir)[1], 'w') as f:
f.write(systems)
with self.assertRaises(LoadDataBaseError):
OECDatabase(self.tempDir)
def tearDown(self):
shutil.rmtree(self.tempDir)
|
class Test_load_db_from_url(TestCase):
def test_autoload(self):
exocat = load_db_from_url()
self.assertTrue((len(exocat.planets) > 1000))
self.assertTrue((len(exocat.systems) > 1000))
self.assertTrue((len(exocat.stars) > 1000))
|
class Test__ExoDataEqn(TestCase):
def test__repr__(self):
eqn = _ExoDataEqn()
self.assertEqual(eqn.__repr__(), '_ExoDataEqn()')
|
class Test_ScaleHeight(TestCase):
def test__repr__works(self):
eqn = ScaleHeight((100 * aq.K), (1 * aq.atomic_mass_unit), ((9.81 * aq.m) / (aq.s ** 2)))
answer = 'ScaleHeight(H=None, T_eff=100.0 K, mu=1.0 u, g=9.81 m/s**2)'
self.assertEqual(eqn.__repr__(), answer)
def test_works_earth(self):
mu_p = (28.964 * aq.u)
T_eff_p = (290 * aq.degK)
g_p = ((9.81 * aq.m) / (aq.s ** 2))
answer = (8486.04 * aq.m)
result = ScaleHeight(T_eff_p, mu_p, g_p).H
self.assertAlmostEqual(answer, result, 2)
@given(floats(500, 20000), floats(0.001, 1), floats(0.1, 1000))
def test_can_derive_other_vars_from_one_calculated(self, T_eff, mu, g):
'We calculate H from a range of values given by hypothesis and then\n see if we can accurately calculate the other variables given this\n calculated value. This tests the rearrangements of the equation are\n correct.\n '
assume(((T_eff > 0) and (mu > 0) and (g > 0)))
inf = float('inf')
assume(((T_eff < inf) and (mu < inf) and (g < inf)))
T_eff *= aq.K
mu *= aq.atomic_mass_unit
g *= (aq.m / (aq.s ** 2))
H = ScaleHeight(T_eff, mu, g, None).H
self.assertAlmostEqual(ScaleHeight(T_eff, mu, None, H).g, g, 4)
self.assertAlmostEqual(ScaleHeight(T_eff, None, g, H).mu, mu, 4)
self.assertAlmostEqual(ScaleHeight(None, mu, g, H).T_eff, T_eff, 4)
|
class Test_MeanPlanetTemp(TestCase):
def test_works_mars(self):
a = (1.524 * aq.au)
A = 0.25
T_s = (5800 * aq.K)
R_s = (1 * aq.R_s)
answer = (231.1 * aq.K)
result = MeanPlanetTemp(A, T_s, R_s, a, 0.7).T_p
self.assertAlmostEqual(answer, result, 1)
@unittest.skip
def test_can_derive_other_vars_from_one_calculated(self, A, T_s, R_s, a, epsilon):
assume(((T_s > 0) and (R_s > 0) and (a > 0) and (epsilon > 0)))
inf = float('inf')
assume(((T_s < inf) and (R_s < inf) and (a < inf)))
T_s *= aq.K
R_s *= aq.R_s
a *= aq.au
T_p = MeanPlanetTemp(A, T_s, R_s, a, epsilon).T_p
self.assertAlmostEqual(MeanPlanetTemp(A, T_s, R_s, a, None, T_p).epsilon, epsilon, 4)
self.assertAlmostEqual(MeanPlanetTemp(A, T_s, R_s, None, epsilon, T_p).a, a, 4)
self.assertAlmostEqual(MeanPlanetTemp(A, T_s, None, a, epsilon, T_p).R_s, R_s, 4)
self.assertAlmostEqual(MeanPlanetTemp(A, None, R_s, a, epsilon, T_p).T_s, T_s, 4)
self.assertAlmostEqual(MeanPlanetTemp(None, T_s, R_s, a, epsilon, T_p).A, A, 4)
|
class Test_StellarLuminosity(TestCase):
def test_works_sun(self):
R_s = (1 * aq.R_s)
T_eff_s = (5780 * aq.degK)
answer = (3.89144e+26 * aq.W)
result = StellarLuminosity(R_s, T_eff_s).L
self.assertAlmostEqual(answer, result, delta=1e+23)
@given(T=floats(0.0001, 100000), R=floats(0.0001, 10000))
def test_can_derive_other_vars_from_one_calculated(self, T, R):
assume(((T > 0) and (R > 0)))
inf = float('inf')
assume(((T < inf) and (R < inf)))
T *= aq.K
R *= aq.R_s
L = StellarLuminosity(R, T).L
self.assertAlmostEqual(StellarLuminosity(R, None, L).T, T, 4)
self.assertAlmostEqual(StellarLuminosity(None, T, L).R, R, 4)
|
class Test_KeplersThirdLaw(TestCase):
def test_works_gj1214(self):
a = (0.014 * aq.au)
M_s = (0.153 * aq.M_s)
result = KeplersThirdLaw(a, M_s).P
answer = (1.546 * aq.day)
self.assertAlmostEqual(answer, result, 3)
@given(a=floats(0.0001, 1000), M_s=floats(0.0001, 10000), M_p=floats(0, 10000))
def test_can_derive_other_vars_from_one_calculated(self, a, M_s, M_p):
assume(((M_s > 0) and (a > 0)))
inf = float('inf')
assume(((a < inf) and (M_s < inf) and (M_p < inf)))
a *= aq.au
M_s *= aq.M_s
M_p *= aq.M_j
P = KeplersThirdLaw(a, M_s, None, M_p).P
self.assertAlmostEqual(KeplersThirdLaw(None, M_s, P, M_p).a, a, 4)
self.assertAlmostEqual(KeplersThirdLaw(a, None, P, M_p).M_s, M_s, 4)
self.assertAlmostEqual(KeplersThirdLaw(a, M_s, P, None).M_p, M_p, 4)
|
class Test_SurfaceGravity(TestCase):
def test_works_earth(self):
R = (1 * aq.R_e)
M = (1 * aq.M_e)
answer = ((9.823 * aq.m) / (aq.s ** 2))
result = SurfaceGravity(M, R).g
self.assertAlmostEqual(answer, result, 2)
@given(M=floats(0.0001, 10000), R=floats(0.0001, 10000))
def test_can_derive_other_vars_from_one_calculated(self, M, R):
assume(((M > 0) and (R > 0)))
inf = float('inf')
assume(((M < inf) and (R < inf)))
R *= aq.R_j
M *= aq.M_j
g = SurfaceGravity(M, R).g
self.assertAlmostEqual(SurfaceGravity(M, R, None).g, g, 4)
self.assertAlmostEqual(SurfaceGravity(M, None, g).R, R, 4)
self.assertAlmostEqual(SurfaceGravity(None, R, g).M, M, 4)
|
class Test_logg(TestCase):
def test_works_wasp10(self):
' Christian et al. 2009 values\n '
answer = 4.51
result = eq.Logg((0.703 * aq.M_s), (0.775 * aq.R_s)).logg
self.assertAlmostEqual(answer, result, 1)
@given(M=floats(0.0001, 10000), R=floats(0.0001, 10000))
def test_can_derive_other_vars_from_one_calculated(self, M, R):
assume(((M > 0) and (R > 0)))
inf = float('inf')
assume(((M < inf) and (R < inf)))
R *= aq.R_j
M *= aq.M_j
logg = eq.Logg(M, R).logg
self.assertAlmostEqual(eq.Logg(M, R, None).logg, logg, 3)
self.assertAlmostEqual(eq.Logg(M, None, logg).R, R, 3)
self.assertAlmostEqual(eq.Logg(None, R, logg).M, M, 3)
|
class Test_transitDepth(TestCase):
def test_works_gj1214(self):
'Charbonneau et. al. 2009 values'
answer = (0.1162 ** 2)
result = TransitDepth((0.211 * aq.R_s), (2.678 * aq.R_e)).depth
self.assertAlmostEqual(answer, result, 2)
@given(R_p=floats(0.0001, 10000), R_s=floats(0.0001, 10000))
def test_can_derive_other_vars_from_one_calculated(self, R_p, R_s):
assume(((R_p > 0) and (R_s > 0)))
inf = float('inf')
assume(((R_p < inf) and (R_s < inf)))
R_p *= aq.R_j
R_s *= aq.R_s
depth = TransitDepth(R_s, R_p).depth
self.assertAlmostEqual(TransitDepth(R_s, R_p).depth, depth, 4)
self.assertAlmostEqual(TransitDepth(R_s, None, depth).R_p, R_p, 4)
self.assertAlmostEqual(TransitDepth(None, R_p, depth).R_s, R_s, 4)
|
class Test_density(TestCase):
def test_works_water(self):
M = (1 * aq.kg)
R = (1 * aq.m)
answer = ((0.2387 * aq.kg) / (aq.m ** 3))
result = Density(M, R).density.rescale((aq.kg / (aq.m ** 3)))
self.assertAlmostEqual(answer, result, 3)
def test_works_hd189(self):
M = (1.144 * aq.M_j)
R = (1.138 * aq.R_j)
answer = ((1.0296 * aq.g) / (aq.cm ** 3))
result = Density(M, R).density
self.assertAlmostEqual(answer, result, 3)
def test_works_jupiter(self):
R = ((6.9911 * (10 ** 7)) * aq.m)
d = ((1.326 * aq.g) / (aq.cm ** 3))
result = Density(None, R, d).M.rescale(aq.kg)
answer = ((1.898 * (10 ** 27)) * aq.kg)
self.assertAlmostEqual(answer, result, delta=1e+24)
@given(M=floats(0.0001, 10000), R=floats(0.0001, 10000))
def test_can_derive_other_vars_from_one_calculated(self, M, R):
assume(((R > 0) and (M > 0)))
inf = float('inf')
assume(((R < inf) and (M < inf)))
M *= aq.kg
R *= aq.m
density = Density(M, R).density
self.assertAlmostEqual(Density(M, None, density).R, R, 4)
self.assertAlmostEqual(Density(None, R, density).M, M, 4)
|
class Test_ratioTerminatorToStar(TestCase):
def test_works_earth(self):
H_p = (8500 * aq.m)
R_p = (1 * aq.R_e)
R_s = (1 * aq.R_s)
answer = (1.12264e-06 * aq.dimensionless)
result = ratioTerminatorToStar(H_p, R_p, R_s)
self.assertTrue(((answer - result) < 0.001))
|
class Test_SNRPlanet(TestCase):
def test_works(self):
params = {'SNRStar': 400, 'starPlanetFlux': 1.12e-06, 'Nobs': 200, 'pixPerbin': 5, 'NVisits': 1}
answer = 0.01417
result = SNRPlanet(**params)
self.assertAlmostEqual(answer, result, 5)
|
class Test_transitDurationCircular(TestCase):
def test_works_gj1214(self):
R_p = (0.02 * aq.R_j)
R_s = (0.21 * aq.R_s)
i = (88.17 * aq.deg)
a = (0.014 * aq.au)
P = (1.58040482 * aq.day)
answer = (45.8329 * aq.min)
result = transitDurationCircular(P, R_s, R_p, a, i)
self.assertAlmostEqual(answer, result, 3)
|
class Test_transitDuration(TestCase):
def test_works_gj1214(self):
R_p = (0.02 * aq.R_j)
R_s = (0.21 * aq.R_s)
i = (88.17 * aq.deg)
a = (0.014 * aq.au)
P = (1.58040482 * aq.day)
answer = (45.8329 * aq.min)
result = TransitDuration(P, a, R_p, R_s, i, 0.0, 0.0).Td
self.assertAlmostEqual(answer, result, 3)
@given(Rp=floats(0.0001, 10000), Rs=floats(0.0001, 10000), i=floats(85, 95), a=floats(0.0001, 1000), P=floats(0.0001, 10000))
def test_matches_circular(self, Rp, Rs, i, a, P):
Rp *= aq.R_j
Rs *= aq.R_s
i *= aq.deg
a *= aq.au
P *= aq.day
result = TransitDuration(P, a, Rp, Rs, i, 0.0, 0.0).Td
resultCirc = transitDurationCircular(P, Rs, Rp, a, i)
if (math.isnan(result) or (result == 0)):
self.assertTrue(math.isnan(resultCirc))
else:
self.assertAlmostEqual(result, resultCirc, 5)
@unittest.skip
def test_works_eccentric(self):
assert False
|
class Test_starTemperature(TestCase):
def test_works_sun(self):
answer = (5800 * aq.K)
result = eq.estimateStellarTemperature((1 * aq.M_s))
self.assertAlmostEqual(answer, result, 0)
def test_works_hd189(self):
answer = (4939 * aq.K)
result = eq.estimateStellarTemperature((0.846 * aq.M_s))
self.assertTrue(((result - answer) < 300))
|
@unittest.skip('Not written')
class Test_estimateStellarMass(TestCase):
def test_works_gj1214(self):
assert False
|
class Test_impactParameter(TestCase):
def test_works_wasp10b(self):
' Christian et al. 2009 values\n '
result = eq.ImpactParameter((0.0369 * aq.au), (0.775 * aq.R_s), (86.9 * aq.deg)).b
answer = 0.568
self.assertAlmostEqual(result, answer, 1)
@given(floats(0.001, 10000), floats(0.001, 10000), floats(0, 180))
def test_can_derive_other_vars_from_one_calculated(self, a, R_s, i):
assume(((a > 0) and (R_s > 0)))
a *= aq.au
R_s *= aq.R_s
i *= aq.deg
b = eq.ImpactParameter(a, R_s, i).b
if (not (math.isinf(b) or math.isnan(b) or (b == 0))):
self.assertAlmostEqual(eq.ImpactParameter(a, None, i, b).R_s, R_s, 3)
self.assertAlmostEqual(eq.ImpactParameter(None, R_s, i, b).a, a, 3)
|
class Test_estimateDistance(TestCase):
def test_works_online_example(self):
m = 14
M = 0
result = estimateDistance(m, M, 0)
answer = (6309.6 * aq.pc)
self.assertAlmostEqual(answer, result, 1)
|
class Test_createAbsMagEstimationDict(TestCase):
def test_works(self):
(magTable, LClassRef) = eq._createAbsMagEstimationDict()
self.assertEqual(magTable['O'][8][LClassRef['V']], (- 4.9))
self.assertEqual(magTable['A'][1][LClassRef['III']], 0.2)
self.assertTrue(math.isnan(magTable['A'][7][LClassRef['Iab']]))
|
class Test_estimateAbsoluteMagnitude(TestCase):
def test_works_no_interp(self):
self.assertEqual(estimateAbsoluteMagnitude('O9'), (- 4.5))
self.assertEqual(estimateAbsoluteMagnitude('B5'), (- 1.2))
self.assertEqual(estimateAbsoluteMagnitude('A5'), 1.95)
def test_works_no_classnum(self):
self.assertEqual(estimateAbsoluteMagnitude('G'), 5.1)
self.assertEqual(estimateAbsoluteMagnitude('A'), 1.95)
def test_works_interp(self):
self.assertEqual(estimateAbsoluteMagnitude('A6'), 2.075)
self.assertEqual(estimateAbsoluteMagnitude('A0.5Iab'), (- 6.35))
def test_nan_on_invalid_types(self):
self.assertTrue(math.isnan(estimateAbsoluteMagnitude('L1')))
def test_works_on_other_L_types(self):
self.assertEqual(estimateAbsoluteMagnitude('O9V'), (- 4.5))
self.assertEqual(estimateAbsoluteMagnitude('B5III'), (- 2.2))
self.assertEqual(estimateAbsoluteMagnitude('F2Ia'), (- 8.0))
|
class Test_createMagConversionDict(TestCase):
def test_works(self):
magTable = eq._createMagConversionDict()
self.assertEqual(magTable['A6'][10], '0.44')
self.assertEqual(magTable['B0'][0], '30000')
self.assertEqual(magTable['M6'][14], 'nan')
|
class TestExampleInstances(TestCase):
def setUp(self):
ac._ExampleSystemCount = 1
self.examplePlanet = examplePlanet
self.exampleStar = exampleStar
self.exampleSystem = exampleSystem
def test_system_object(self):
exampleSystem = self.exampleSystem
self.assertEqual(exampleSystem.name, 'Example System 1')
self.assertEqual(exampleSystem.d, (58 * aq.pc))
self.assertEqual(exampleSystem.dec.to_string(unit=u.degree), '4d05m06s')
self.assertEqual(exampleSystem.ra.to_string(unit=u.degree), '15d30m45s')
def test_star_object(self):
exampleStar = self.exampleStar
self.assertEqual(exampleStar.params['altnames'], ['HD 1'])
self.assertEqual(exampleStar.age, (7.6 * aq.Gyear))
self.assertEqual(exampleStar.magB, 9.8)
self.assertEqual(exampleStar.magH, 7.4)
self.assertEqual(exampleStar.magI, 7.6)
self.assertEqual(exampleStar.magJ, 7.5)
self.assertEqual(exampleStar.magK, 7.3)
self.assertEqual(exampleStar.magV, 9.0)
self.assertEqual(exampleStar.M, (0.98 * aq.M_s))
self.assertEqual(exampleStar.Z, 0.43)
self.assertEqual(exampleStar.name, 'Example Star 1')
self.assertEqual(exampleStar.R, (0.95 * aq.R_s))
self.assertEqual(exampleStar.spectralType, 'G5')
self.assertEqual(exampleStar.T, (5370 * aq.K))
self.assertEqual(exampleStar.getLimbdarkeningCoeff(1.22), (0.3531, 0.2822))
def test_planet_object(self):
examplePlanet = self.examplePlanet
self.assertEqual(examplePlanet.discoveryMethod, 'transit')
self.assertEqual(examplePlanet.discoveryYear, 2001)
self.assertEqual(examplePlanet.e, 0.09)
self.assertEqual(examplePlanet.i, (89.2 * aq.deg))
self.assertEqual(examplePlanet.lastUpdate, '12/12/08')
self.assertEqual(examplePlanet.M, (3.9 * aq.M_j))
self.assertEqual(examplePlanet.name, 'Example Star 1 b')
self.assertEqual(examplePlanet.P, (111.2 * aq.d))
self.assertEqual(examplePlanet.R, (0.92 * aq.R_j))
self.assertEqual(examplePlanet.a, (0.449 * aq.au))
self.assertEqual(examplePlanet.T, (339.6 * aq.K))
self.assertEqual(examplePlanet.transittime, (2454876.344 * aq.JD))
self.assertEqual(examplePlanet.separation, (330 * aq.au))
def test_hierarchy_for_planet(self):
self.assertEqual(self.examplePlanet.star, self.exampleStar)
self.assertEqual(self.examplePlanet.parent, self.exampleStar)
self.assertEqual(self.examplePlanet.system, self.exampleSystem)
def test_hierarchy_for_star(self):
self.assertEqual(self.exampleStar.planets[0], self.examplePlanet)
self.assertEqual(self.exampleStar.system, self.exampleSystem)
self.assertEqual(self.exampleStar.parent, self.exampleSystem)
def test_hierarchy_for_system(self):
self.assertEqual(self.exampleSystem.stars[0], self.exampleStar)
def test_raises_HeirarchyError_on_planet_binary_call_with_no_binary(self):
with self.assertRaises(ac.HierarchyError):
planetBinary = self.examplePlanet.binary
def test_raises_HeirarchyError_on_star_binary_call_with_no_binary(self):
with self.assertRaises(ac.HierarchyError):
starBinary = self.exampleStar.binary
def test_second_generation_is_number_2(self):
examplePlanet = secondExamplePlanet
exampleStar = examplePlanet.parent
exampleSystem = exampleStar.parent
self.assertEqual(examplePlanet.name, 'Example Star 2 b')
self.assertEqual(exampleStar.name, 'Example Star 2')
self.assertEqual(exampleStar.params['altnames'], ['HD 2'])
self.assertEqual(exampleSystem.name, 'Example System 2')
def test_second_generation_is_unique(self):
planet1 = self.examplePlanet
planet2 = secondExamplePlanet
planet2.params['radius'] = 12345
self.assertTrue(planet2.R, 12345)
self.assertEqual(planet1.R, (0.92 * aq.R_j))
def test_fake_flags_raised(self):
self.assertTrue(('Fake' in self.examplePlanet.flags))
self.assertTrue(('Fake' in self.exampleStar.flags))
self.assertTrue(('Fake' in self.exampleSystem.flags))
|
class TestExampleInstancesWithBinary(TestCase):
def setUp(self):
ac._ExampleSystemCount = 2
self.examplePlanet = genExamplePlanet(binaryLetter='A')
self.exampleStarA = self.examplePlanet.star
self.exampleBinary = self.examplePlanet.binary
self.exampleStarB = self.exampleBinary.stars[0]
self.exampleSystem = self.examplePlanet.system
def test_binary_object(self):
exampleBinary = self.exampleBinary
self.assertEqual(exampleBinary.name, 'Example Binary 2AB')
def test_hierarchy_for_planet(self):
self.assertIsInstance(self.examplePlanet, ac.Planet)
self.assertEqual(self.examplePlanet.name, 'Example Star 2A b')
self.assertEqual(self.examplePlanet.system, self.exampleSystem)
self.assertEqual(self.examplePlanet.star, self.exampleStarA)
def test_hierarchy_for_starA(self):
self.assertIsInstance(self.exampleStarA, ac.Star)
self.assertEqual(self.exampleStarA.name, 'Example Star 2A')
self.assertEqual(self.exampleStarA.system, self.exampleSystem)
self.assertEqual(self.exampleStarA.planets[0], self.examplePlanet)
def test_hierarchy_for_starB(self):
self.assertIsInstance(self.exampleStarB, ac.Star)
self.assertEqual(self.exampleStarB.name, 'Example Star 2B')
self.assertEqual(self.exampleStarB.system, self.exampleSystem)
self.assertFalse(self.exampleStarB.planets)
def test_hierarchy_for_Binary(self):
self.assertIsInstance(self.exampleBinary, ac.Binary)
self.assertEqual(self.exampleBinary.name, 'Example Binary 2AB')
self.assertEqual(self.exampleBinary.system, self.exampleSystem)
self.assertItemsEqual(self.exampleBinary.stars, [self.exampleStarA, self.exampleStarB])
def test_hierarchy_for_System(self):
self.assertIsInstance(self.exampleSystem, ac.System)
self.assertEqual(self.exampleSystem.name, 'Example System 2')
self.assertItemsEqual(self.exampleSystem.stars, [self.exampleBinary])
def test_fake_flags_raised(self):
self.assertTrue(('Fake' in self.examplePlanet.flags))
self.assertTrue(('Fake' in self.exampleStarA.flags))
self.assertTrue(('Fake' in self.exampleStarB.flags))
self.assertTrue(('Fake' in self.exampleBinary.flags))
self.assertTrue(('Fake' in self.exampleSystem.flags))
|
class Test_Flag(TestCase):
def test_flag__iter__(self):
flagobj = flags.Flags()
flagobj.addFlag('Calculated Temperature')
flagobj.addFlag('Estimated Mass')
self.assertTrue(('Calculated Temperature' in flagobj))
self.assertTrue(('Estimated Mass' in flagobj))
self.assertTrue(('Calculated Period' not in flagobj))
|
class estimateMissingValues(TestCase):
def tearDown(self):
' reset back to default after\n '
params.estimateMissingValues = True
|
class estimateMissingValuesPlanet(estimateMissingValues):
def setUp(self):
self.planet = ex.genExamplePlanet()
def testSMAEstimatedWhenTrue(self):
del self.planet.params['semimajoraxis']
self.assertAlmostEqual(self.planet.a, (0.4496365 * aq.au), 7)
self.assertTrue(('Calculated SMA' in self.planet.flags.flags))
def testSMANotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.planet.params['semimajoraxis']
self.assertTrue((self.planet.a is np.nan))
self.assertTrue(('Calculated SMA' not in self.planet.flags.flags))
def testPeriodEstimatedWhenTrue(self):
del self.planet.params['period']
self.assertAlmostEqual(self.planet.P, (110.96397 * aq.day), 4)
self.assertTrue(('Calculated Period' in self.planet.flags.flags))
def testPeriodNotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.planet.params['period']
self.assertTrue((self.planet.P is np.nan))
self.assertTrue(('Calculated Period' not in self.planet.flags.flags))
def testTempEstimatedWhenTrue(self):
del self.planet.params['temperature']
self.assertAlmostEqual(self.planet.T, (402.175111 * aq.K), 4)
self.assertTrue(('Calculated Temperature' in self.planet.flags.flags))
def testTempNotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.planet.params['temperature']
self.assertTrue((self.planet.T is np.nan))
self.assertTrue(('Calculated Temperature' not in self.planet.flags.flags))
|
class estimateMissingValuesStar(estimateMissingValues):
def setUp(self):
self.star = ex.genExampleStar()
def test_magVEstimatedWhenTrue(self):
del self.star.params['magV']
self.assertAlmostEqual(self.star.magV, 9.14, 3)
self.assertTrue(('Estimated magV' in self.star.flags.flags))
def test_magVNotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.star.params['magV']
self.assertTrue((self.star.magV is np.nan))
self.assertTrue(('Estimated magV' not in self.star.flags.flags))
def testDistanceEstimatedWhenTrue(self):
del self.star.system.params['distance']
self.assertAlmostEqual(self.star.d, (60.256 * aq.pc), 3)
self.assertTrue(('Estimated Distance' in self.star.flags.flags))
def testDistanceNotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.star.system.params['distance']
self.assertTrue((self.star.d is np.nan))
self.assertTrue(('Estimated Distance' not in self.star.flags.flags))
|
class estimateMissingValuesBinary(estimateMissingValues):
def setUp(self):
self.binary = ex.genExampleBinary()
@unittest.skip('Currently the calculation is not implemented')
def testSMAEstimatedWhenTrue(self):
del self.binary.params['semimajoraxis']
self.assertAlmostEqual(self.binary.a, (0.4496365 * aq.au), 7)
self.assertTrue(('Calculated SMA' in self.binary.flags.flags))
def testSMANotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.binary.params['semimajoraxis']
self.assertTrue((self.binary.a is np.nan))
self.assertTrue(('Calculated SMA' not in self.binary.flags.flags))
@unittest.skip('Currently the calculation is not implemented')
def testPeriodEstimatedWhenTrue(self):
del self.binary.params['period']
self.assertAlmostEqual(self.binary.P, (110.96397 * aq.day), 4)
self.assertTrue(('Calculated Period' in self.binary.flags.flags))
def testPeriodNotEstimatedWhenFalse(self):
params.estimateMissingValues = False
del self.binary.params['period']
self.assertTrue((self.binary.P is np.nan))
self.assertTrue(('Calculated Period' not in self.binary.flags.flags))
|
class Test_GlobalFigure(TestCase):
def test_set_y_axis_log(self):
fig = _GlobalFigure()
fig.set_y_axis_log()
def test_set_x_axis_log(self):
fig = _GlobalFigure()
fig.set_x_axis_log()
|
class Test_AstroObjectFigs(TestCase):
@unittest.skip('Tested through others but should probably be done here aswell')
def test_getInputObjectTypes(self):
assert False
@unittest.skip('Tested through others but should probably be done here aswell')
def test_getParLabelAndUnit(self):
assert False
def test_gen_label(self):
fig = _AstroObjectFigs([genExamplePlanet()])
self.assertEqual(fig._gen_label('R', None), 'Planet Radius')
self.assertEqual(fig._gen_label('R', aq.m), 'Planet Radius (m)')
self.assertEqual(fig._gen_label('R', aq.R_j), 'Planet Radius ($R_J$)')
def test_get_unit_symbol(self):
fig = _AstroObjectFigs([genExamplePlanet()])
self.assertEqual(fig._get_unit_symbol(aq.m), 'm')
self.assertEqual(fig._get_unit_symbol(aq.R_j), '$R_J$')
def test_get_unit_symbol_with_no_unit_raises_error(self):
fig = _AstroObjectFigs([genExamplePlanet()])
with self.assertRaises(AttributeError):
fig._get_unit_symbol(None)
|
class Test_DataPerParameterBin(TestCase):
def testDataGeneratesCorrectly(self):
planets = []
planetInfoList = (0, 0.1, 0.2, 0.3, 0.45, 0.5, 0.6, np.nan)
for planetInfo in planetInfoList:
planet = genExamplePlanet()
planet.params['eccentricity'] = planetInfo
planets.append(planet)
data = DataPerParameterBin(planets, 'e', (0, 0.2, 0.4, 0.6))
answer = {'0 to 0.2': 2, '0.2 to 0.4': 2, '0.4 to 0.6': 3, 'Uncertain': 1}
self.assertDictEqual(answer, data._processResults())
def test_limits_generated_correctly(self):
planets = []
planetInfoList = ((- 10), (- 4), (- 1), 1, 3, 5, 6, 7, 8, np.nan)
for planetInfo in planetInfoList:
planet = genExamplePlanet()
planet.params['eccentricity'] = planetInfo
planets.append(planet)
data = DataPerParameterBin(planets, 'e', ((- float('inf')), 0, 5, float('inf')))
answer = {'<0': 3, '0 to 5': 2, '5+': 4, 'Uncertain': 1}
self.assertDictEqual(answer, data._processResults())
def testDataGeneratesCorrectlyWithUnitScaling(self):
planets = []
planetInfoList = ((0 * aq.R_j), (0.1 * aq.R_j), (0.2 * aq.R_j), (0.3 * aq.R_j), (0.45 * aq.R_j), (0.5 * aq.R_j), (0.6 * aq.R_j), np.nan)
for planetInfo in planetInfoList:
planet = genExamplePlanet()
planet.params['radius'] = planetInfo
planets.append(planet)
data = DataPerParameterBin(planets, 'R', (0, 5, 15, 30), aq.R_e)
answer = {'0 to 5': 5, '5 to 15': 2, '15 to 30': 0, 'Uncertain': 1}
self.assertDictEqual(answer, data._processResults())
def testStarRadiusGeneratesCorrectly(self):
starInfoList = ((0 * aq.R_s), (1 * aq.R_s), (2 * aq.R_s), (3 * aq.R_s), (4.5 * aq.R_s), (5 * aq.R_s), (6 * aq.R_s), np.nan)
planets = generate_list_of_planets(len(starInfoList))
starlist = [planet.star for planet in planets]
for (i, star) in enumerate(starlist):
star.params['radius'] = starInfoList[i]
data = DataPerParameterBin(starlist, 'R', (0, 5, 15, 30), aq.R_s)
answer = {'0 to 5': 5, '5 to 15': 2, '15 to 30': 0, 'Uncertain': 1}
self.assertDictEqual(answer, data._processResults())
def test_plotbarchart_for_all_planet_params_generate_without_exception(self):
planetlist = generate_list_of_planets(3)
for param in _planetPars:
DataPerParameterBin(planetlist, param, ((- float('inf')), 0, 5, float('inf'))).plotBarChart()
def test_plotbarchart_for_all_stellar_params_generate_without_exception(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
for param in _starPars:
DataPerParameterBin(starlist, param, ((- float('inf')), 0, 5, float('inf'))).plotBarChart()
def test_plotbarchart_for_all_planet_and_star_classes_on_input_raises_TypeError(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
with self.assertRaises(TypeError):
fig = DataPerParameterBin((starlist + planetlist), 'R', ((- float('inf')), 0, 5, float('inf'))).plotBarChart()
def test_plotpiechart_for_all_planet_params_generate_without_exception(self):
planetlist = generate_list_of_planets(3)
for param in _planetPars:
DataPerParameterBin(planetlist, param, ((- float('inf')), 0, 5, float('inf'))).plotPieChart()
def test_plotpiechart_for_all_stellar_params_generate_without_exception(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
for param in _starPars:
DataPerParameterBin(starlist, param, ((- float('inf')), 0, 5, float('inf'))).plotPieChart()
|
def generate_list_of_planets(number):
planetList = []
for i in range(number):
planetList.append(genExamplePlanet())
return planetList
|
class Test_GeneralPlotter(TestCase):
def test__init__(self):
x = GeneralPlotter(generate_list_of_planets(3))
def test_set_axis_with_variables(self):
planetlist = generate_list_of_planets(3)
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
for (i, radius) in enumerate(radiusValues):
planetlist[i].params['radius'] = radius
fig = GeneralPlotter(planetlist)
self.assertItemsEqual(fig._set_axis('R', None), radiusValues)
def test_set_axis_with_variables_star(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
radiusValues = ((5 * aq.R_s), (10 * aq.R_s), (15 * aq.R_s))
for (i, radius) in enumerate(radiusValues):
starlist[i].params['radius'] = radius
fig = GeneralPlotter(starlist)
self.assertItemsEqual(fig._set_axis('R', None), radiusValues)
def test_set_axis_with_variables_planet_and_star(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
magVValues = (1, 2, 3)
for (i, radius) in enumerate(radiusValues):
planetlist[i].params['radius'] = radius
starlist[i].params['magV'] = magVValues[i]
fig = GeneralPlotter(planetlist)
fig.set_xaxis('R', None)
fig.set_yaxis('star.magV', None)
self.assertItemsAlmostEqual(fig._xaxis, radiusValues, 1)
self.assertItemsAlmostEqual(fig._yaxis, magVValues, 1)
fig.plot()
def test_set_axis_with_functions(self):
planetlist = generate_list_of_planets(3)
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
for (i, radius) in enumerate(radiusValues):
planetlist[i].params['radius'] = radius
fig = GeneralPlotter(planetlist)
results = fig._set_axis('calcDensity()', None)
answer = (((0.04138 * aq.g) / (aq.cm ** 3)), ((0.00517 * aq.g) / (aq.cm ** 3)), ((0.00153 * aq.g) / (aq.cm ** 3)))
self.assertItemsAlmostEqual(answer, results, 4)
def test_set_axis_with_unit_scaling(self):
planetlist = generate_list_of_planets(3)
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
for (i, radius) in enumerate(radiusValues):
planetlist[i].params['radius'] = radius
fig = GeneralPlotter(planetlist)
self.assertItemsAlmostEqual(fig._set_axis('R', aq.m), [x.rescale(aq.m) for x in radiusValues], 4)
def test_set_axis_with_unitless_stellar_quantity(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
magVValues = (5, 10, 15)
for (i, magV) in enumerate(magVValues):
starlist[i].params['magV'] = magV
fig = GeneralPlotter(starlist)
self.assertItemsEqual(fig._set_axis('magV', None), magVValues)
def test_plotting_on_all_planet_params_generate_without_exception(self):
planetlist = generate_list_of_planets(3)
for param in _planetPars:
fig = GeneralPlotter(planetlist, param, 'R').plot()
def test_plotting_on_all_stellar_params_generate_without_exception(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
for param in _starPars:
fig = GeneralPlotter(starlist, param, 'R').plot()
def test_mix_of_planet_and_star_classes_on_input_raises_TypeError(self):
planetlist = generate_list_of_planets(3)
starlist = [planet.star for planet in planetlist]
with self.assertRaises(TypeError):
fig = GeneralPlotter((planetlist + starlist))
fig._set_axis('R', None)
def test_set_axis_with_multi_unit_compound_unit_scaling(self):
planetlist = generate_list_of_planets(3)
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
for (i, radius) in enumerate(radiusValues):
planetlist[i].params['radius'] = radius
kmhr = aq.CompoundUnit('km / hr**2')
fig = GeneralPlotter(planetlist)
self.assertItemsAlmostEqual(fig._set_axis('calcSurfaceGravity()', kmhr), ((52417.5200676341 * kmhr), (13104.380016908524 * kmhr), (5824.1688964037885 * kmhr)), 4)
def test_set_axis_with_multi_unit_non_compound_unit_scaling(self):
planetlist = generate_list_of_planets(3)
radiusValues = ((5 * aq.R_j), (10 * aq.R_j), (15 * aq.R_j))
for (i, radius) in enumerate(radiusValues):
planetlist[i].params['radius'] = radius
fig = GeneralPlotter(planetlist)
self.assertItemsAlmostEqual(fig._set_axis('calcSurfaceGravity()', (aq.km / (aq.hr ** 2))), (((52417.5200676341 * aq.km) / (aq.h ** 2)), ((13104.380016908524 * aq.km) / (aq.h ** 2)), ((5824.1688964037885 * aq.km) / (aq.h ** 2))), 4)
|
def find_version(*file_paths):
with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:
version_file = f.read()
version_match = re.search('^__version__ = [\'\\"]([^\'\\"]*)[\'\\"]', version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.')
|
def g(x, a):
'\n TBSS kernel applicable to the rBergomi variance process.\n '
return (x ** a)
|
def b(k, a):
'\n Optimal discretisation of TBSS process for minimising hybrid scheme error.\n '
return ((((k ** (a + 1)) - ((k - 1) ** (a + 1))) / (a + 1)) ** (1 / a))
|
def cov(a, n):
'\n Covariance matrix for given alpha and n, assuming kappa = 1 for\n tractability.\n '
cov = np.array([[0.0, 0.0], [0.0, 0.0]])
cov[(0, 0)] = (1.0 / n)
cov[(0, 1)] = (1.0 / (((1.0 * a) + 1) * (n ** ((1.0 * a) + 1))))
cov[(1, 1)] = (1.0 / (((2.0 * a) + 1) * (n ** ((2.0 * a) + 1))))
cov[(1, 0)] = cov[(0, 1)]
return cov
|
def bs(F, K, V, o='call'):
'\n Returns the Black call price for given forward, strike and integrated\n variance.\n '
w = 1
if (o == 'put'):
w = (- 1)
elif (o == 'otm'):
w = ((2 * (K > 1.0)) - 1)
sv = np.sqrt(V)
d1 = ((np.log((F / K)) / sv) + (0.5 * sv))
d2 = (d1 - sv)
P = (((w * F) * norm.cdf((w * d1))) - ((w * K) * norm.cdf((w * d2))))
return P
|
def bsinv(P, F, K, t, o='call'):
'\n Returns implied Black vol from given call price, forward, strike and time\n to maturity.\n '
w = 1
if (o == 'put'):
w = (- 1)
elif (o == 'otm'):
w = ((2 * (K > 1.0)) - 1)
P = np.maximum(P, np.maximum((w * (F - K)), 0))
def error(s):
return (bs(F, K, ((s ** 2) * t), o) - P)
s = brentq(error, 1e-09, 1000000000.0)
return s
|
def compute_masked_mses(templates, masks, imgs):
mses = np.zeros((len(imgs), len(templates)))
for (imgi, img) in enumerate(imgs):
for (ti, (t, m)) in enumerate(zip(templates, masks)):
mse = ((((t * m) - (img * m)) ** 2).sum() / m.mean())
mses[(imgi, ti)] = mse.item()
return mses
|
def compute_pairwise_mses(imgs1, imgs2):
mses = np.zeros((len(imgs1), len(imgs2)))
for (imgi, img1) in enumerate(imgs1):
for (ti, img2) in enumerate(imgs2):
mse = ((img1 - img2) ** 2).sum()
mses[(imgi, ti)] = mse.item()
return mses
|
def get_templates_and_masks(template_folder='templates/'):
template_parquet = pd.read_parquet(f'{template_folder}metadata.parquet')
t_urls = np.array(template_parquet['url'])
mask_files = list(template_parquet['mask_file'])
template_files = list(template_parquet['img_file'])
(template_imgs, mask_imgs) = ([], [])
for (imgf, maskf) in zip(template_files, mask_files):
(img, mask) = [processing_utils.pil_img_to_torch(Image.open(file).resize((256, 256))) for file in (imgf, maskf)]
template_imgs += [img]
mask_imgs += [mask]
return (template_imgs, mask_imgs, t_urls)
|
def get_retrieved_imgs_and_urls(ret_folder='retrieved/'):
md_ret = pd.read_parquet('retrieved/metadata.parquet')
ret_imgs = []
ret_urls = []
for (imgf, imgu) in zip(md_ret['img_file'], md_ret['url']):
ret_imgs += [processing_utils.pil_img_to_torch(Image.open(imgf).resize((256, 256)))]
ret_urls += [imgu]
return (ret_imgs, np.array(ret_urls))
|
def get_files_from_path(folder_path, prefix, postfix):
files = []
for (root, _, filenames) in os.walk(folder_path):
for filename in filenames:
if (filename.startswith(prefix) and filename.endswith(postfix)):
files.append(os.path.join(root, filename))
files = sorted(files)
return files
|
def prompt_to_folder(prompt, ml=200):
return prompt.replace('/', '_')[:min(len(prompt), ml)]
|
def gather_groundtruths(parquet_file='sdv1_wb_groundtruth.parquet', out_parquet_file='test.parquet', gen_folder='memb_top500_synthall/', matching_real_folder='matched_and_real_images/matched/', recompute_real_img_mse=True, N_imgs_gen=(- 1), n_imgs_template_thresh=0, download_templates=True, download_reals=True):
if download_templates:
print('downloading templates...')
p = snapshot_download(repo_id='fraisdufour/templates-verbs', repo_type='dataset', local_dir='.')
d = pd.read_parquet(parquet_file)
if download_reals:
print('downloading matching...')
urls = list(d['url'])
real_out = (parquet_file[:((- 1) * len('.parquet'))] + '/')
dl_utils.dl_urls_concurrent(urls, real_out, nthreads=16)
(ret_imgs, ret_urls) = get_retrieved_imgs_and_urls()
(templates, masks, t_urls) = get_templates_and_masks()
real_files = sorted(glob.glob((real_out + '/*.jpg')))
overfit_types = []
retrieved_urls = []
gen_seeds = []
i = 0
verb_thresh = float(2500.0)
real_mses = []
template_indices = [[] for _ in range(len(d['caption']))]
for (ci, c) in enumerate(list(d['caption'])):
pf = prompt_to_folder(c)
folder = f'{gen_folder}/{pf}/'
real_file = real_files[ci]
real_img = processing_utils.pil_img_to_torch(Image.open(real_file).resize((256, 256)))
files = get_files_from_path((gen_folder + prompt_to_folder(c)), '', '.jpg')
if (N_imgs_gen > 0):
files = files[:N_imgs_gen]
imgs = [processing_utils.pil_img_to_torch(Image.open(file).resize((256, 256))) for file in files]
real_mse = min([((img - real_img) ** 2).sum() for img in imgs])
real_mses += [real_mse]
mses = compute_masked_mses(templates, masks, imgs)
(rd, cd) = np.nonzero((mses < float(2500.0)))
if (len(rd) > n_imgs_template_thresh):
t_inds = np.unique(cd.ravel())
seeds = np.unique(rd.ravel())
print(f'{c} found {len(t_inds)} templates with {len(seeds)} generating seeds...')
print(seeds[:2].ravel())
gen_seeds += [seeds.tolist()]
retrieved_urls += [t_urls[t_inds].tolist()]
template_indices[ci] = [t_inds.tolist()]
overfit_types += ['TV']
elif (real_mse < float(2500.0)):
print(c, 'is verb')
overfit_types += ['MV']
retrieved_urls += [[]]
gen_seeds += [[]]
else:
mses = compute_pairwise_mses(imgs, ret_imgs)
all_seeds = np.arange(len(imgs))
(rd, cd) = np.nonzero((mses < float(3000.0)))
if len(rd):
t_inds = np.unique(cd.ravel()).ravel()
seeds = all_seeds[np.unique(rd.ravel())]
urls_verb = ret_urls[t_inds]
print(f'{c} found {len(t_inds)} retrieved images with {len(seeds)} generating seeds...')
gen_seeds += [seeds.tolist()]
retrieved_urls += [urls_verb.tolist()]
overfit_types += ['RV']
else:
print(f'{c} none')
overfit_types += ['N']
retrieved_urls += [[]]
gen_seeds += [[]]
real_mses = np.array(real_mses)
new_dict = {'overfit_type': overfit_types, 'gen_seeds': gen_seeds, 'retrieved_urls': retrieved_urls}
d['overfit_type'] = overfit_types
d['gen_seeds'] = gen_seeds
d['retrieved_urls'] = retrieved_urls
d['mse_real_gen'] = real_mses
d['template_indices'] = template_indices
d.to_parquet(out_parquet_file)
|
@torch.no_grad()
def run_bb_attack(out_parquet_file, parquet_file=None, n_seeds=4, seed_offset=0, make_grid_every=0, outfolder='bb_attack_vis/', caption_offset=0, n_captions=(- 1), model='runwayml/stable-diffusion-v1-5', dl_parquet_repo='fraisdufour/sd-stuff', dl_parquet_name='membership_attack_top30k.parquet', compute_images=False, local_dir='.', verb=True):
'\n Runs the blackbox attack against stable diffusion models. Exploits the fact that verbatim copies have strong edges when synthesizing with few timesteps versus non copied images which appear blurry.\n \n For more details see "A Reproducible Extraction of Training Images from Diffusion Models" https://arxiv.org/abs/2305.08694\n \n Parameters:\n - out_parquet_file (str): Output file path for saving the attack\'s scores.\n - parquet_file (str, optional): Input parquet containing captions for attack, if it is a local file. Captions should be within field \'caption\' in the pandas dataframe.\n - n_seeds (int, optional): Number of random seeds per caption. Default is 4.\n - seed_offset (int, optional): Starting offset for random seed generation. Default is 0.\n - outfolder (str, optional): Output folder path for visualizing attack. Default is disabled.\n - caption_offset (int, optional): Start at a specified offset caption in parquet_file. Useful if you want to divide work amongst several gpus/nodes.\n - n_captions (int, optional): Number of captions to be used from the input parquet. If set to -1, all available captions will be used. Default is -1.\n - model (str, optional): Pre-trained stable diffusion model to be used for generating synthetic data. Default is \'runwayml/stable-diffusion-v1-5\'. Use stabilityai/stable-diffusion-2-base for sdv2 models.\n - dl_parquet_repo (str, optional): Huggingface base repo for input parquet.\n - dl_parquet_name (str, optional): Name of parquet within huggingface repo. Default is \'membership_attack_top30k.parquet\'.\n - compute_images (bool, optional): Whether to compute and save the generated images (for visualization). Default false.\n - local_dir (str, optional): Local directory path for temporary file storage. Default is \'.\'.\n - verb: Print current caption being synthesized.\n Returns:\n None\n \n Saves blackbox scores to out_parquet_file.\n '
if (parquet_file is not None):
d = pd.read_parquet(parquet_file)
else:
print(f'downloading parquet from hub {dl_parquet_repo}/{dl_parquet_name}')
hf_hub_download(repo_id=dl_parquet_repo, filename=dl_parquet_name, repo_type='dataset', local_dir='.')
d = pd.read_parquet(dl_parquet_name)
from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler
from custom_ksampler import StableDiffusionKDiffusionPipeline
pipe = StableDiffusionKDiffusionPipeline.from_pretrained(model, torch_dtype=torch.float16)
pipe.set_scheduler('sample_heun')
pipe = pipe.to('cuda')
if (n_captions > 0):
last_caption = min(len(d['caption']), (caption_offset + n_captions))
else:
last_caption = len(d['caption'])
captions = np.array(d['caption'])[caption_offset:last_caption]
edge_overlap_scores = np.zeros((len(captions),))
d = d.iloc[list(range(caption_offset, last_caption))]
for (ci, c) in enumerate(captions):
if verb:
print(f'synthing caption {ci},{c}...')
prompt = c
outfolder_prompt = prompt.replace('/', '_')[:min(len(prompt), 200)]
os.makedirs(f'{outfolder}{outfolder_prompt}', exist_ok=True)
imgs_out = []
img_group = []
for seed in range(seed_offset, (seed_offset + n_seeds)):
generator = torch.Generator('cuda').manual_seed(seed)
image = pipe(prompt, num_inference_steps=1, generator=generator, use_karras_sigmas=True).images[0]
fn = f'{outfolder}{outfolder_prompt}/{seed:04d}.jpg'
image.save(fn)
tmp_img = np.array(image.resize((256, 256), resample=Image.LANCZOS)).astype('float32')
img_group += [tmp_img]
score = processing_utils.get_edge_intersection_score(img_group)
edge_overlap_scores[ci] = score
d['edge_scores'] = edge_overlap_scores
d.to_parquet(out_parquet_file)
|
@torch.no_grad()
def run_wb_attack(out_parquet_file, parquet_file=None, n_seeds=1, seed_offset=0, outfolder='gen_synthall/', caption_offset=0, n_captions=(- 1), model='runwayml/stable-diffusion-v1-5', dl_parquet_repo='fraisdufour/sd-stuff', dl_parquet_name='membership_attack_top30k.parquet', compute_images=False, local_dir='.'):
'\n Runs the whitebox attack against a stable diffusion model run on captions in parquet_file, with a single timestep. Attack score function is the MSE between a one time step generated latent (for LDMs) and the initial noise. By default, we provide a list of 30K captions with the highest whitebox score on SDV1 found at fraisdufour/sd-stuff/membership_attack_top30k.parquet on huggingface, and 2M captions selected by duplication rates (and not by an attack) can be found at fraisdufour/sd-stuff/most_duplicated_metadata.parquet.\n For more details see "A Reproducible Extraction of Training Images from Diffusion Models" https://arxiv.org/abs/2305.08694\n \n Parameters:\n - out_parquet_file (str): Output file path for saving the attack\'s scores.\n - parquet_file (str, optional): Input parquet containing captions for attack, if it is a local file. Captions should be within field \'caption\' in the dataframe.\n - n_seeds (int, optional): Number of random seeds per caption. Default is 1.\n - seed_offset (int, optional): Starting offset for random seed generation. Default is 0.\n - outfolder (str, optional): Output folder path for visualizing attack. Default is disabled.\n - caption_offset (int, optional): Start at a specified offset caption in parquet_file. Useful if you want to divide work amongst several gpus/nodes.\n - n_captions (int, optional): Number of captions to be used from the input parquet. If set to -1, all available captions will be used. Default is -1.\n - model (str, optional): Pre-trained stable diffusion model to be used for generating synthetic data. Default is \'runwayml/stable-diffusion-v1-5\'. Use stabilityai/stable-diffusion-2-base for sdv2 models.\n - dl_parquet_repo (str, optional): Huggingface base repo for input parquet.\n - dl_parquet_name (str, optional): Name of parquet within huggingface repo. Default is \'membership_attack_top30k.parquet\'.\n - compute_images (bool, optional): Whether to compute and save the generated images (for visualization). Default false.\n - local_dir (str, optional): Local directory path for temporary file storage. Default is \'.\'.\n\n Returns:\n None\n \n Saves whitebox scores to out_parquet_file.\n '
if (parquet_file is not None):
d = pd.read_parquet(parquet_file)
else:
print(f'downloading from hub {dl_parquet_repo}/{dl_parquet_name}')
hf_hub_download(repo_id=dl_parquet_repo, filename=dl_parquet_name, repo_type='dataset', local_dir='.')
d = pd.read_parquet(dl_parquet_name)
steps = 1
from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler
from custom_ksampler_wb_attack import StableDiffusionWBAttack
pipe = StableDiffusionWBAttack.from_pretrained(model, torch_dtype=torch.float16)
pipe.set_scheduler('sample_heun')
pipe = pipe.to('cuda')
if (n_captions > 0):
last_caption = min(len(d['caption']), (caption_offset + n_captions))
else:
last_caption = len(d['caption'])
d = d.iloc[list(range(caption_offset, last_caption))]
captions = np.array(d['caption'])[caption_offset:last_caption]
scores = np.zeros((len(captions),))
for (ci, c) in enumerate(captions):
print(f'synthing caption {ci},{c}...')
prompt = c
outfolder_prompt = prompt.replace('/', '_')[:min(len(prompt), 200)]
os.makedirs(f'{outfolder}{outfolder_prompt}', exist_ok=True)
imgs_out = []
img_group = []
for seed in range(seed_offset, (seed_offset + n_seeds)):
generator = torch.Generator('cuda').manual_seed(seed)
(image, z0, latents, score) = pipe(prompt, num_inference_steps=1, generator=generator, use_karras_sigmas=True, compute_images=compute_images)
if compute_images:
fn = f'{outfolder}{outfolder_prompt}/{seed:04d}.jpg'
image[0].save(fn)
scores[ci] = score
d['scores'] = scores
d.to_parquet(out_parquet_file)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.