Skip to content

Commit

Permalink
Merge pull request #13 from elliesch/master
Browse files Browse the repository at this point in the history
Added License, Requirements.txt and Updated ReadMe file
  • Loading branch information
kelle authored Aug 8, 2017
2 parents 68adeb8 + e573034 commit 9de75f3
Show file tree
Hide file tree
Showing 8 changed files with 193 additions and 41 deletions.
29 changes: 29 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2017, Ellianna Schwab, Kelle Cruz
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
92 changes: 66 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,72 @@
# UltracoolTypingKit
Home for qualitative spectral typing GUI that follows the Cruz Method as proposed in <Cruz et al. (2017)>.
Currently this GUI spectral types L field, L beta and L gamma brown dwarfs.
This code is written in Python 3.6, and does not yet have functionality for Python 2.
This code is written in Python 3.6, and does not yet have functionality for Python 2 and works with
input fits files of NIR spectra.


## Usage
## Installation

To install clone this repository:

```bash
$ git clone https://github.com/BDNYC/UltracoolTypingKit
$ cd UltracoolTypingKit/
$ mkdir new_types

```

UltracoolTypingKit (UTK) requires Python 3.5 to run properly. We recommend running in an environment to ensure usage of the correct version of Python and all the necessary modules.

```bash
$ conda create --name UTK python=3.5 ipython
$ source activate UTK
$ pip install -r requirements.txt

```

This code currently requires this directory tree to run properly:

```
UltracoolTypingKit/
├── TypeFinder.py
├── new_types/
│   └── saves selected spectral type image here
├── spectra/
├── spectra/
│   ├── store T0 and M9 spectral standards here
│   └── nir/
│   ├── store NIR spectra here
│   └── store NIR spectral standards (Table 9, Cruz et al. 2017) here
└── templates/
   └── store Cruz2017_Templates.hdf5 here
```


## Usage


### 1. Running UTK

If you aren't already in the UTK environment, activate UTK.
```bash
$ source activate UTK
```

UTK relies on an interactive backend and works best with `TkAgg`. ipython pylab uses this as its default.

```bash
$ ipython --pylab

```

To run UTK on one spectrum, use the following input.

```python
from TypeFinder import *
typing_kit("spectra/nir/spectra_file.fits")

```

To run many spectra consecutively, the following wrapper can be helpful.
It will print out the file name and wait for the user to press enter before continuing.

Expand All @@ -34,25 +81,9 @@ for file in range(len(lines)):
...: input("Press Enter to continue...")

```

If you have the Cruz 2017 templates in ascii format, you can [download](.../blob/master/templates/Cruz2017_Templates.hdf5) the hdf5 file from this repository.
You can also save an hdf5 file the first time you run Ultracool Typing Kit.

```python
from TypeFinder import*
typing_kit("spectra/nir/somespectra", make_templates=True)

```

By default make_templates is false, and this input will raise an exception if Cruz2017_Templates.hdf5 already exists.


---


### 1. Running the Program
On running, this initial window will pop up, after about 10 seconds:
<img src="https://raw.githubusercontent.com/elliesch/UltracoolTypingKit/master/opengrid.png" width="750">
After about 10 seconds, this initial window will pop up:
<img src="https://raw.githubusercontent.com/elliesch/UltracoolTypingKit/master/resources/opengrid.png" width="750">

Your input spectra will be shown in black, over the Cruz et al. (2017) J-H-K band templates shown in red.
The initial grid shows each spectral type band-by-band.
Expand Down Expand Up @@ -80,22 +111,31 @@ For example for an L2-gamma press:
<kbd>alt</kbd> + <kbd>1</kbd>

After keying in your selection, a window centered on your spectral type will pop up:
![Grid of Spectral Type Selection](https://raw.githubusercontent.com/elliesch/UltracoolTypingKit/master/L3.png)
![Grid of Spectral Type Selection](https://raw.githubusercontent.com/elliesch/UltracoolTypingKit/master/resources/L3.png)

This grid shows your selected spectral type bracketed by it's neighboring types, both band-by-band and across
the entire NIR spectrum at once in the right-hand column, following the same color scheme as the initial grid.
The templates used in for the entire NIR spectrum follow the templates specified in Cruz et al. (2017).



### 3. Viewing Alternate Spectral Types
If you keyed in a spectral type and you want to see a different one, press <kbd>q</kbd> to close the window containing your initial selection and to return to the initial grid window.




### 4. Saving a Spectral Type
Once you have settled on a spectral type, you can save the image of the selected type by pressing <kbd>w</kbd>. This will create a csv file in the folder new_types/ that will save your input file name in column 1 and your selected spectral type in column 2. The csv file is named XX-XX-XXXX_SpecTypes.csv, XX represents today's date in day-month-year format. As you spectral type more objects, they will append as new rows to the csv file.

Pressing <kbd>w</kbd> will also save an image of the current plot view as a .png to the new_types/ folder with the name of your input spectrum file and your selected spectral type appended after an underscore, for example, like this for an L0: InputFileName_L0.png

You can then close the selection window by pressing <kbd>q</kbd> and then the grid window by again pressing <kbd>q</kbd>.

### 3. Saving Selected Spectral Type
Currently the code automatically saves an image of your selection into the new_types folder. We are in the process
of updating it so that you can select whether you would prefer to save or see another type.



## Citation
Copyright 2017 Ellianna Schwab and collaborators
Copyright 2017 Ellianna Schwab, Kelle Cruz

If you make use of this code, please cite Cruz et al. (2017) and the zenodo DOI for the code, coming soon!
109 changes: 94 additions & 15 deletions TypeFinder.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
import numpy as np
import matplotlib.pyplot as plt
# from pylab import *
from collections import defaultdict
from astropy.io import fits
from astropy.io import ascii
from astropy.table import Table, Column
import os
import time

plt.rcParams['keymap.save'] = ''

'''
Ellianna Schwab, Kelle Cruz
TypeFinder.py contains typing_kit, which provides plots to qualitatively spectral type L-type brown dwarfs in NIR regime.
Typing methods are taken from Cruz et al. 2017 and offer comparison to NIR spectral standards.
To use input path to file_name in a string. A band-by-band grid of Cruz et al 2017 templates
will be overplotted with the target spectrum. To compare to the NIR spectral standards as well,
key in the spectral type number, '0' - '8'.
Cruz et al. 2017 templates are shown band-by-band followed by a comparison to the overall NIR spectrum of NIR
spectral standards as defined in Table 9 of Cruz et al 2017.
'''

class Data:

Expand Down Expand Up @@ -136,6 +152,7 @@ def __init__(self, file_name, type_number, NIR_standards): #This defines often r
#Define the other variables
self.type_number = type_number
self.NIR_standards = NIR_standards
self.file_name = file_name


def bracketed_plot(self, gravity_type): #This is for bracketed plots that are not first or last
Expand Down Expand Up @@ -189,7 +206,7 @@ def bracketed_plot(self, gravity_type): #This is for bracketed plots that are no
axes2[jj, 2].axis('off')


#All Together Now! This is where the Kirkpatrick 10 one comes in.
#All Together Now! This is where the spectral standard comes in.
temp_hdulist = fits.open(self.NIR_standards[ii])
temp_spectrum = temp_hdulist[0]
temp_wavelength = temp_spectrum.data[0]
Expand All @@ -210,7 +227,16 @@ def bracketed_plot(self, gravity_type): #This is for bracketed plots that are no
axes2[jj, 3].plot(self.wavelength, self.norm_flux, c='k')
axes2[jj, 3].axis('off')

# fig2.savefig('new_types/' + self.file_name[12:-5] + r'_L{}'.format(self.type_number))
save_name = 'new_types/' + self.file_name[12:-5] + r'_L{}{}'.format(self.type_number, gravity_type)

def save_figure(event):
if event.key == 'w':
plt.savefig(save_name)
save_types(self.file_name, self.type_number, gravity_type)

fig2.canvas.mpl_connect('key_press_event', manipulate_figure)
fig2.canvas.mpl_connect('key_press_event', save_figure)


def first_bracketed_plot(self, gravity_type):

Expand Down Expand Up @@ -287,7 +313,7 @@ def first_bracketed_plot(self, gravity_type):
axes2[jj, 2].axis('off')


#All Together Now! This is where the Kirkpatrick 10 one comes in.
#All Together Now! This is where the spectral standard comes in.
temp_hdulist = fits.open(self.NIR_standards[ii])
temp_spectrum = temp_hdulist[0]
temp_wavelength = temp_spectrum.data[0]
Expand All @@ -308,7 +334,16 @@ def first_bracketed_plot(self, gravity_type):
axes2[jj, 3].plot(self.wavelength, self.norm_flux, c='k')
axes2[jj, 3].axis('off')

# fig2.savefig('new_types/' + self.file_name[12:-5] + r'_L{}'.format(self.type_number))
save_name = 'new_types/' + self.file_name[12:-5] + r'_L{}{}'.format(self.type_number, gravity_type)

def save_figure(event):
if event.key == 'w':
plt.savefig(save_name)
save_types(self.file_name, self.type_number, gravity_type)

fig2.canvas.mpl_connect('key_press_event', manipulate_figure)
fig2.canvas.mpl_connect('key_press_event', save_figure)


def last_bracketed_plot(self, gravity_type):

Expand Down Expand Up @@ -362,7 +397,7 @@ def last_bracketed_plot(self, gravity_type):
axes2[jj, 2].axis('off')


#All Together Now! This is where the Kirkpatrick 10 one comes in.
#All Together Now! This is where the spectral standard comes in.
temp_hdulist = fits.open(self.NIR_standards[jj])
temp_spectrum = temp_hdulist[0]
temp_wavelength = temp_spectrum.data[0]
Expand Down Expand Up @@ -405,10 +440,47 @@ def last_bracketed_plot(self, gravity_type):
axes2[2, 3].plot(temp_wavelength, temp_norm_flux, c='red')
axes2[2, 3].plot(self.wavelength, self.norm_flux, c='k')
axes2[2, 3].axis('off')

# fig2.savefig('new_types/' + self.file_name[12:-5] + r'_L{}'.format(self.type_number))

save_name = 'new_types/' + self.file_name[12:-5] + r'_L{}{}'.format(self.type_number, gravity_type)

def save_figure(event):
if event.key == 'w':
plt.savefig(save_name)
save_types(self.file_name, self.type_number, gravity_type)

fig2.canvas.mpl_connect('key_press_event', manipulate_figure)
fig2.canvas.mpl_connect('key_press_event', save_figure)


def save_types(file_name, type_number, gravity_type):

'''
saves output csv file with filename in column 1, and spectral type in column 2
'''

now_date = time.strftime("%d-%m-%Y")

if os.path.isfile(r'new_types/{}_SpecTypes.csv'.format(now_date)) == True :
f = open(r'new_types/{}_SpecTypes.csv'.format(now_date), 'a')
f.write(r'{}, L{}{}'.format(file_name[12:], type_number, gravity_type))
f.write('\n')
f.close()

else :
f = open(r'new_types/{}_SpecTypes.csv'.format(now_date), 'w')
f.write(r'{}, L{}{}'.format(file_name[12:], type_number, gravity_type))
f.write('\n')
f.close()


def manipulate_figure(event):

'''
closes selected plot window when q is pressed on the keyboard
'''

if event.key == 'q':
plt.close(event.canvas.figure)

### Function definition
def typing_kit(file_name, make_templates=False) :
Expand All @@ -417,17 +489,18 @@ def typing_kit(file_name, make_templates=False) :
Ellianna Schwab, Kelle Cruz
typing_kit provides plots to qualitatively spectral type L-type brown dwarfs in NIR regime.
Typing methods are taken from Cruz et al. 2017 and offer comparison to Kirkpatrick 2010 typing templates.
Typing methods are taken from Cruz et al. 2017 and offer comparison to NIR spectral standards.
To use input path to file_name in a string. A band-by-band grid of Cruz et al 2017 templates
will be overplotted with the target spectrum. To compare to Kirkpatrick 2010, key in the spectral type
number, '0' - '8'. Cruz et al. 2017 templates are shown band-by-band followed by Kirkpatrick 2010
templates of the overall NIR spectrum.
will be overplotted with the target spectrum. To compare to the NIR spectral standards as well,
key in the spectral type number, '0' - '8'.
Cruz et al. 2017 templates are shown band-by-band followed by a comparison to the overall NIR spectrum of NIR
spectral standards as defined in Table 9 of Cruz et al 2017.
'''


##===============
#Optional Section to Translate Templates to HDF5
#If Necessary, Convert Ascii templates to HDF5
##===============

if make_templates == True:
Expand Down Expand Up @@ -698,7 +771,7 @@ def on_key_press(event):


#Raise an error message if any other key is pressed
elif event.key in 'abcdefghijklmnopqrstuvwxyz`-=[];,.':
elif event.key in 'abcdefghijklmnoprstuvxyz`-=[];,.':
raise Exception('Invalid Key. Try any int in range(10) for field, ctrl + int in range(1) for beta, or alt + int in range(4) for gamma.')


Expand All @@ -709,4 +782,10 @@ def on_key_press(event):
fig1.canvas.draw()

fig1.canvas.mpl_disconnect(fig1.canvas.manager.key_press_handler_id)
fig1.canvas.mpl_connect('key_press_event', on_key_press) #This leaves it open to a second try
fig1.canvas.mpl_connect('key_press_event', on_key_press) #This leaves it open to a second try

##==============
#Close the plot via the keyboard
##==============

fig1.canvas.mpl_connect('key_press_event', manipulate_figure)
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
numpy==1.11.1
matplotlib==1.5.3
astropy==1.2.1
h5py
File renamed without changes
File renamed without changes
Binary file added spectra/M9V_LHS2924.fits
Binary file not shown.
Binary file added spectra/T0_2M0423_T0.fits
Binary file not shown.

0 comments on commit 9de75f3

Please sign in to comment.