Skip to content
Snippets Groups Projects
Commit 9c8ce75e authored by Christan Solis Calero's avatar Christan Solis Calero
Browse files

Actualización de la tarea 03

parent e6db4f73
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
 
## Alumno: Christian Solis Calero.¶
#### Universidad Nacional Mayor de San Marcos, Lima. Perú
 
%% Cell type:markdown id: tags:
 
# Ejercicio-03-01
Investigue sobre el diagrama de Hertzprung-Russell, una herramienta muy potente en astronomia, y describa un poco al respecto para darle contexto al resto de la tarea El objetivo es generar un diagrama HR lo más parecido al de esta referencia.
![image.png](attachment:image.png)
No lucirá idéntico por que no se usarán exactamente los mismos datos, y las unidades pueden ser ligeramente distinta. La idea sí es dejar su figura lo más parecida a la de referencia en el estilo: colores, escalas en los ejes, tamaño de los marcadores, leyendas, textos en el gráfico, etc.
Los datos para crear la figura están en la carpeta Data. Cada tabla contiene las informaciones sobre un tipo de estrellas según indican los nombres de archivo. La información viene en 3 columnas: luminosidad en luminosidades solares, Temperatura en Kelvin y Radio de la estrella en unidades arbitrarias La idea es que cada estrella en el gráfico tenga un color representativo
de su temperatura (que estrellas frías son rojas y estrellas calientes son azules) y que el tamaño del símbolo sea representativo del tamaño de cada estrella para diferenciar entre enanas, gigantes y estrellas de secuencia principal
Busque que su código sea semi automático; es indispensable leer los datos desde el propio programa, no copiarlos a mano, y hallar una forma de obtener los tamaños y colores sin declararlos uno a uno
 
%% Cell type:code id: tags:
 
``` python
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
 
%% Cell type:markdown id: tags:
 
### Subiendo la información a trabajar e integrandola en un solo array
 
%% Cell type:code id: tags:
 
``` python
stars = []
i=0
data1 = np.loadtxt("data/giants.txt", delimiter=" ", skiprows=1)
for x in range(len(data1)):
stars.append("Giants")
 
data2 = np.loadtxt("data/supergiants.txt", delimiter=" ", skiprows=1)
for x in range(len(data2)):
stars.append("Supergiants")
 
data3 = np.loadtxt("data/dwarfs.csv", delimiter=",", skiprows=1)
for x in range(len(data3)):
stars.append("Dwarfs")
 
data4 = np.loadtxt("data/ms.csv", delimiter=",", skiprows=1)
for x in range(len(data4)):
stars.append("Main sequence")
 
data= np.concatenate((data1,data2,data3,data4), axis=0)
```
 
%% Cell type:markdown id: tags:
 
### Realizando el Plot de los datos requeridos
 
%% Cell type:code id: tags:
 
``` python
T= data[:, 1] #Temperature
L= data[:, 0] #Luminosity
area= data[:, 2] #ratio
 
radius=20*(area) #multiplying by 20 the value of ratio
log_temp=np.log10(T) #Taking in account logaritmic value of T for colour parameter of plotting
 
fig = plt.figure(figsize=(12,8))
 
plt.scatter(T, L,
#c=colors,
c=log_temp,
#hue=log_temp,
s=radius,
marker='o',
#cmap='hsv',
cmap='Spectral',
lw=1,
edgecolors='gray',
alpha=0.9)
 
plt.title=('diagrama de Hertzprung-Russell')
 
plt.xlabel("Temperature (K)", fontsize=20, fontweight='bold')
plt.ylabel("Luminosity ($L_{sun}$)", fontsize=20, fontweight='bold')
plt.yscale('log')
plt.xscale('log')
idx = [4000,6000,8000,12000]
plt.xticks(idx, fontsize=10, fontweight='bold')
plt.yticks(fontsize=10, fontweight='bold')
plt.xlim(14000, 3000)
plt.ylim(0.00001, 10000000)
```
 
%% Cell type:markdown id: tags:
 
### Edición del plot
 
%% Cell type:code id: tags:
 
``` python
#Adding the Axes object ax: It is a container that holds the axes, the ticks, the labels, the plot, the legend, etc.
ax = plt.axes()
 
#Method for generate lines only in X and Y axis
#removing top and right borders
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
 
#Modifying ticks of X axis to eliminate scientific notation
from matplotlib.ticker import FuncFormatter
 
def Wscientific(x, pos):
return '%1i' % (x)
 
formatter = FuncFormatter(Wscientific)
ax.xaxis.set_major_formatter(formatter)
plt.setp(ax.get_xminorticklabels(), visible=False)
 
#Adding text to the plot describing the used data
ax.set_facecolor("white")
ax.text(7000,15000,'Giants', style='normal',color='black', fontsize=20, fontweight='bold')
ax.text(11000,0.5,'Main sequence', style='normal',color='black', fontsize=20, fontweight='bold')
ax.text(11000,0.0001,'Dwarfs', style='normal',color='black', fontsize=20, fontweight='bold')
 
plt.show()
```
 
%% Output
 
 
%% Cell type:markdown id: tags:
 
## Ejercicio-03-02
Después de tener un diseño de base para el ejercicio No. 1, en este ejercicio se pide generar una animación, en la cual se reproduzca el mismo gráfico de antes pero las estrellas vayan apareciendo progresivamente
 
%% Cell type:code id: tags:
 
``` python
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
```
%% Cell type:markdown id: tags:
### Generando una función que permita generar imagenes a medida que se adiciona progresivamente la información de cada estrella
%% Cell type:code id: tags:
 
``` python
def salvar_figura(x,y,co,z,n):
fig = plt.figure(figsize=(12,8))
scat = plt.scatter(x, y,
c=co,
s=z,
marker='o',
cmap='Spectral',
lw=1,
edgecolors='gray',
alpha=0.9)
plt.xlabel("Temperature (K)", fontsize=20, fontweight='bold')
plt.ylabel("Luminosity ($L_{sun}$)", fontsize=20, fontweight='bold')
plt.yscale('log')
plt.xscale('log')
idx = [4000,6000,8000,12000]
plt.xticks(idx, fontsize=10, fontweight='bold')
plt.yticks(fontsize=10, fontweight='bold')
plt.xlim(14000, 3000)
plt.ylim(0.00001, 10000000)
plt.ioff() #turning off Interactive Mode for generating figures
#Adding the Axes object ax: It is a container that holds the axes, the ticks, the labels, the plot, the legend, etc.
ax = plt.axes()
#Method for generate lines only in X and Y axis
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#Modifying ticks of X axis to eliminate scientific notation
from matplotlib.ticker import FuncFormatter
def Wscientific(x, pos):
return '%1i' % (x)
formatter = FuncFormatter(Wscientific)
ax.xaxis.set_major_formatter(formatter)
plt.setp(ax.get_xminorticklabels(), visible=False)
plt.savefig("Animation"+str(n)+".png", format="png")
```
%% Cell type:markdown id: tags:
### Introduciendo la data de las estrellas progresivamente para que se generen las imagenes
%% Cell type:code id: tags:
 
``` python
VectX=[]
VectY=[]
VectC=[]
VectZ=[]
n=0
for i in range(len(T)):
VectX.append(T[n])
VectY.append(L[n])
VectC.append(log_temp[n])
VectZ.append(radius[n])
salvar_figura(VectX,VectY,VectC,VectZ,n)
n=n+1
plt.show()
```
 
%% Cell type:markdown id: tags:
### Generando la animación a partir de la información de las imagenes
%% Cell type:code id: tags:
 
``` python
from PIL import Image
import glob
 
# Create the frames
frames = []
imgs = glob.glob("*.png")
for i in imgs:
new_frame = Image.open(i)
frames.append(new_frame)
 
#Save into a GIF file that loops forever
frames[0].save('Hertzprung-Russell.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=10)
 
 
```
 
%% Cell type:markdown id: tags:
 
<img src="Hertzprung-Russell.gif">
 
%% Cell type:code id: tags:
 
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment