Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kris's Fitting Infrastructure #56

Closed
wants to merge 0 commits into from
Closed

Conversation

KriSun95
Copy link
Collaborator

@KriSun95 KriSun95 commented Apr 1, 2022

PR Description

Includes fitting infrastructure code.

PR Checklist

  • I have followed the guidelines in the Contributing document
  • Changes follow the coding style of this project
  • Changes have been formatted and linted
  • Changes pass pytest style unit tests (and pytest passes).
  • Changes include any required corresponding changes to the documentation
  • Changes have been rebased and squashed to the minimal number (typically 1) of relevant commits
  • Changes have a descriptive commit message with a short title
  • I have added a Fixes #XXXX - or Closes #XXXX - comment to auto-close the issue that your PR addresses

@codecov-commenter
Copy link

codecov-commenter commented Apr 1, 2022

Codecov Report

Merging #56 (c6f394e) into master (c6b5127) will decrease coverage by 63.85%.
The diff coverage is 24.31%.

@@             Coverage Diff             @@
##           master      #56       +/-   ##
===========================================
- Coverage   93.45%   29.59%   -63.86%     
===========================================
  Files           5       18       +13     
  Lines         626     3284     +2658     
===========================================
+ Hits          585      972      +387     
- Misses         41     2312     +2271     
Impacted Files Coverage Δ
sunxspex/sunxspex_fitting/fitter.py 13.26% <ø> (ø)
sunxspex/thermal.py 96.04% <ø> (ø)
sunxspex/sunxspex_fitting/rainbow_text.py 11.76% <11.76%> (ø)
sunxspex/sunxspex_fitting/data_loader.py 12.73% <12.73%> (ø)
sunxspex/sunxspex_fitting/rhes_spec_code.py 14.54% <14.54%> (ø)
sunxspex/sunxspex_fitting/instruments.py 18.24% <18.24%> (ø)
sunxspex/sunxspex_fitting/parameter_handler.py 19.29% <19.29%> (ø)
sunxspex/sunxspex_fitting/nu_spec_code.py 21.87% <21.87%> (ø)
sunxspex/sun_xspec.py 22.22% <22.22%> (ø)
sunxspex/sunxspex_fitting/stix_spec_code.py 23.80% <23.80%> (ø)
... and 7 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update c6b5127...c6f394e. Read the comment docs.

@DanRyanIrish
Copy link
Member

Thanks so much for this PR @KriSun95! A huge effort!

Returns
-------
The channel numbers, counts, and the livetime for the observation.
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work on your docstrings!

@DanRyanIrish
Copy link
Member

@KriSun95 the new dependencies you've introduced need to be added here for the tests to run

@DanRyanIrish
Copy link
Member

@KriSun95 the new dependencies you've introduced need to be added here for the tests to run

These were the dependencies I had to add locally:
orthopy
ndim
matplotlib
emcee
corner
nestle
numdifftools

Copy link
Member

@DanRyanIrish DanRyanIrish left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a preliminary review. Haven't made it through all the code yet.

@@ -1,4 +1,5 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from .version import __version__
#from .version import __version__
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#from .version import __version__


# Max number of points
maxfcn = 2048

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

"""
import numpy as np
import pandas as pd
#from scipy.special import lpmv
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#from scipy.special import lpmv

Comment on lines 20 to 21
#import astropy.constants as c
#from quadpy.c1 import gauss_legendre
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#import astropy.constants as c
#from quadpy.c1 import gauss_legendre

logging.basicConfig(filename='xspec.log', level=logging.DEBUG) #for now this helps catch Python errors that are not printed to the terminal by XSPEC

# Central constant management
global const #whyyyyyy there has got to be a better way to do this
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is global being used here?

sunxspex/sunxspex_fitting/data_loader.py Outdated Show resolved Hide resolved
sunxspex/sunxspex_fitting/data_loader.py Outdated Show resolved Hide resolved
sunxspex/sunxspex_fitting/data_loader.py Outdated Show resolved Hide resolved
sunxspex/sunxspex_fitting/data_loader.py Outdated Show resolved Hide resolved
sunxspex/sunxspex_fitting/fitter.py Outdated Show resolved Hide resolved
@DanRyanIrish
Copy link
Member

@KriSun95 I think it would be educational to read the Python style guide, PEP8. Most code in the sunpy ecosystem, as well as the broader scientific Python stack follows this guide. If you fold these guidelines into your own writing style, it will make reading other people code easier and more enjoyable as it will be close to your own style.

We should also try running a codestyle test locally that will automatically improve the readability of your code. Let's discuss that on a call.

Copy link
Collaborator

@samaloney samaloney left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First thing amazing work @KriSun95 and also @elastufka.

I've done a quick initial review of most of the code and have left a few specific comments and questions and I have some more general points below. Please note you are not expected to fixed/address these issues and you can also disagree this should all be a discussion.

  • codes style and formatting looks very good probably just need to enable some more checks e.g. large files and isort, maybe black code formatter?
  • doc strings all look good but we need to add to the built docs and check how the look in html
  • tests we need tests for all code ideally, initially could focus on everything excluding plotting and then later take care of plotting too.
  • As discussed during the meeting I think we need to review the use cases and maybe improve the API maybe separate Spectrum, Fitter and Error classes which are compose into a parent objects SpectrumModel and SpectrumModelCollection but this needs to be fleshed out much more carefully
  • Some of the classes are very big it shouldn't be to hard to move some of the functionality to new file to keep them a bit more manageable

@@ -0,0 +1,30 @@
1.00E+00
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minimal header with units would be idea but if this file is taken from somewhere else then it ok

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file can be removed, no need for it now that it's an option in XSPEC

@@ -1,4 +1,5 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from .version import __version__
#from .version import __version__
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what was the reason for this?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't know about Kris but this raised an error for me on import sunxspex

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This caused the same error for me too

"""
import numpy as np
import pandas as pd
#from scipy.special import lpmv
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So few general code style things here remove unused import and short by python, then external lib and then sunxspec we should probably just set up isort as part of our ci

So e.g.

import logging
from datetime import datetime as dt

import numpy as np
import pandas as pd
from astropy import units as u

from sunxspex import thermal
from sunxspex import constants
from sunxspex.emission import split_and_integrate,  split_and_integrate0  

flux[:]=[internal_flux[j] if j in i and j!=i[-1] else prev for j,prev in enumerate(flux)]
#logging.info(f"{flux[:20]}")

class ThickTargetModel(XspecModel):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doc string on the class

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw I will make a new PR, this code does not integrate over energy bins and is therefore incorrect

no guarantee that I will write a legible docstring anytime soon though 😈

raise NotImplementedError


class ThickTargetModel0(XspecModel): #original integration for comparison
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doc string on the class

# Get a default class for the instrument specfic loaders
# Once the instrument specific loaders inherit from this then all they really have to do is get the spectral
# data they want to fit in the correct dictionary form and assigned to `self._loaded_spec_data`.
class InstrumentBlueprint:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe an abstract class?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely need some restructuring here from the previous discussions.

bounds = dict(zip(self.param_names, param_bounds))
errors = dict(zip(self.param_names, param_errors))
# create table
self.parameter_info = pd.DataFrame(dict(zip(self.states, [status, values, bounds, errors])))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we do go units would astropy.table.QTable be worth it?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if I have ever used a QTable so I'm not sure. Depending on where units are implemented, more work would need done one handling these in the fitting code and how the model functions are to be created. Definitely worth a serious discussion.

Comment on lines 206 to 214
if _for=="frozen":
return ["frozen", "freeze", "chill", "fix", "fixed", "secure", "stick", "glue", "preserve", "restrain", "restrained", "cannot_move", "cant_move", "canny_move", "married"]
elif _for=="free":
return ["free", "thaw", "loose", "unrestrained", "release", "released", "can_move", "single"]
elif _for=="tie":
return ["tie", "tied", "bind", "tether", "join", "joined", "in_a_relationship_with"]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if less is more here in only supporting a few keywords?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably less. This mainly came from my inability to remember to type "freeze" and "thaw" when I was testing out the code (to be consistent with XSPEC) where I kept writing "fix" or "free". A single method for each status might even be more useful (I think Dan suggested this)? Just need to decide on which word to be consistent with for each status value.

### Issue when using np.float64 numbers for the parameters as it ends up returning all nans and infs but rounding to 15 decimal places fixes this??????

# The defined models shouldn't have duplicate parameter input names
defined_photon_models = {"f_vth":["T", "EM"],
Copy link
Collaborator

@samaloney samaloney Apr 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we can put some of this in to the models, so can be called without these wrappers?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely happy to do that. These wrappers are here for a few reasons but mainly to have the inputs in the form I chose for the fitting code and to get them in one place but they can obviously be changed and made better.

# from scipy.interpolate import interp1d
# # load in everything for the chianti_kev_cont code of "mine". This only needs done once so do it here.

# def chianti_kev_units(spectrum, funits, wedg, kev=False, earth=False, date=None):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pick, merge etc so only have one or both if they do different things?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My aim was to try and get this to work and then I have clearly forgot about it. I think this is something Dan and I might look at to combine both versions of this but I can remove it for this PR and update the continuum calculation further down the road.

This was referenced Apr 22, 2022
@samaloney
Copy link
Collaborator

pre-commit.ci autofix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants