from marvin import config
from marvin.tools.query import Query
config.mode='remote'

"""
Explanation: DAP Zonal Queries (or Spaxel Queries)
Marvin allows you to perform queries on individual spaxels within and across the MaNGA dataset.
End of explanation
"""


config.setRelease('MPL-5')
f = 'emline_gflux_ha_6564 > 25'
q = Query(searchfilter=f)
print(q)

# let's run the query
r = q.run()

r.totalcount
r.results

"""
Explanation: Let's grab all spaxels with an Ha-flux > 25 from MPL-5.
End of explanation
"""


# get a list of the plate-ifus
plateifu = r.getListOf('plateifu')
# look at the unique values with Python set
print('unique galaxies', set(plateifu), len(set(plateifu)))

"""
Explanation: Spaxel queries are queries on individual spaxels, and thus will always return a spaxel x and y satisfying your input condition.  There is the potential of returning a large number of results that span only a few actual galaxies.  Let's see how many..
End of explanation
"""


f = 'emline_gflux_ha_6564 > 25 and bintype.name == SPX'
q = Query(searchfilter=f, returnparams=['template.name'])
print(q)

# run it
r = q.run()

r.results

"""
Explanation: Optimize your query
Unless specified, spaxel queries will query across all bintypes and stellar templates.  If you only want to search over a certain binning mode, this must be specified.  If your query is taking too long, or returning too many results, consider filtering on a specific bintype and template.
End of explanation
"""


f = 'nsa.sersic_logmass > 9.5 and nsa.z < 0.1 and emline_sew_ha_6564 > 3'
q = Query(searchfilter=f)
print(q)

r = q.run()

# Let's see how many spaxels we returned from how many galaxies
plateifu = r.getListOf('plateifu')
print('spaxels returned', r.totalcount)
print('from galaxies', len(set(plateifu)))

r.results[0:5]

"""
Explanation: Global+Local Queries
To combine global and local searches, simply combine them together in one filter condition.  Let's look for all spaxels that have an H-alpha EW > 3 in galaxies with NSA redshift < 0.1 and a log sersic_mass > 9.5
End of explanation
"""


config.mode='remote'
config.setRelease('MPL-4')
f = 'npergood(emline_gflux_ha_6564 > 5) >= 20'
q = Query(searchfilter=f)
r = q.run()

r.results

"""
Explanation: Query Functions
Marvin also contains more advanced queries in the form of predefined functions. 
For example, let's say you want to ask Marvin
"Give me all galaxies that have an H-alpha flux > 25 in more than 20% of their good spaxels"
you can do so using the query function npergood.  npergood accepts as input a standard filter expression condition. E.g., the syntax for the above query would be input as 
npergood(emline_gflux_ha_6564 > 25) >= 20
The syntax is 
FUNCTION(Conditional Expression) Operator Value
Let's try it...
End of explanation
"""


