metadata
dict
text
stringlengths
0
40.6M
id
stringlengths
14
255
{ "filename": "crossing_orbits.py", "repo_name": "j-faria/kima", "repo_path": "kima_extracted/kima-master/pykima/crossing_orbits.py", "type": "Python" }
# -*- coding: utf-8 -*- # original author Matthew Standing mxs1263@student.bham.ac.uk # https://github.com/j-faria/kima/pull/57 import os import numpy as np from .results import KimaResults # from astropy.constants G = 6.67408e-11 # m3/(kg s2) Msun = 1.9884754153381438e+30 # kg Rsun = 695700000.0 # m RHOsun = 1.4098263 # g/cm3 = 3*Msun / 4*pi*Rsun**3 def rem_crossing_orbits(results=None): """ Removes crossing orbits from the posterior samples. This function assumes that the posterior samples are "sorted" so that the first planet in the system is the most "likely". Then, crossing orbit checks are done starting from the final entry in a row (system) end ending in the first entry. Parameters: results_path : Str Path to 'posterior_sample.txt' Kima output file no_p : Float Max number of planets set for Kima to explore no_files : Float Number of data files input into Kima Returns ------- mod_results : KimaResults Modified `KimaResults` instance with parameters of crossing orbits replaced with NaN, an unmodified `posterior_sample_original` array, and the `removed_crossing` attribute set to True. """ if results is None: if not os.path.exists('posterior_sample.txt'): raise FileNotFoundError('Cannot find file "posterior_sample.txt"') results = KimaResults('') res = results # for shorts samples = res.posterior_sample[:, res.index_component+1:-2].copy() samples[samples==0] = np.nan if res.log_period: samples[:,:res.max_components] = np.exp(samples[:,:res.max_components]) P = samples[:, :res.max_components] # all periods E = samples[:, 3*res.max_components:4*res.max_components] # all eccentricities # calculate periastrons r_peri = ((P**2)**(1/3)) * (1 - E) #days^2/3 # calculate apoastrons r_apast = ((P**2)**(1/3)) * (1 + E) #days^2/3 total = np.count_nonzero(~np.isnan(r_peri)) count = 0 with np.errstate(invalid='ignore'): for j in range(r_peri.shape[0]): for i in range(r_peri.shape[1] - 1, -1, -1): #Check if crosses interior periastrons if (r_apast[j, i] > r_peri[j, np.where(r_peri[j, i] < r_peri[j, :i])]).any(): r_peri[j, i] = np.nan r_apast[j, i] = np.nan count += 1 #Check if crosses exterior apastrons if (r_apast[j, i] > r_apast[j, np.where(r_peri[j, i] < r_apast[j, :i])]).any(): r_peri[j, i] = np.nan r_apast[j, i] = np.nan count += 1 #Check if a lower indexed orbit crosses if np.logical_and((r_apast[j, i] < r_apast[j, :i]), (r_peri[j, i] > r_peri[j, :i])).any(): r_peri[j, i] = np.nan r_apast[j, i] = np.nan count += 1 print("Number of crossing orbits removed = %d (out of %d)" % (count, total)) crossing = np.isnan(r_peri) mc = res.max_components for i in range(res.n_dimensions): samples[:,i*mc:(i+1)*mc][crossing] = np.nan if res.log_period: samples[:,:res.max_components] = np.log(samples[:,:res.max_components]) res.posterior_sample_original = res.posterior_sample.copy() res.posterior_sample[:, res.index_component+1:-2] = samples res.removed_crossing = True res.get_marginals() return res def rem_roche(results=None, RHOplanet=7.8, Mstar=Msun, Rstar=Rsun, RHOstar=RHOsun): """ Remove orbits that cross the Roche lobe of the star. By default, assume a solid iron planet orbiting a Sun-like star. Will save a new version of posterior_sample.txt (remroche_posterior_sample.txt) in results_path given Parameters ---------- results : KimaResults, optional An instance of `KimaResults`. If None, try to get it from a file with posterior samples in the current directory. RHOplanet : float, optional Density of planet used in roche limit equation. Default is 7.8 g/cm^3 corresponding to a solid iron planet. Mstar : float, optional Stellar mass used in roche limit equation. Default is mass of the Sun. Rstar : float, optional Stellar radius used in roche limit equation. Default is radius of the Sun. RHOstar : float, optional Stellar density used in roche limit equation. Default is mean solar density, approximately 1.41 g/cm^3. Returns ------- mod_results : KimaResults Modified `KimaResults` instance with parameters of Roche crossing orbits replaced with NaN and `removed_roche_crossing` attribute set to True. """ if results is None: if not os.path.exists('posterior_sample.txt'): raise FileNotFoundError('Cannot find file "posterior_sample.txt"') results = KimaResults('') P = np.exp(results.T) if results.log_period else results.T E = results.E r_peri = ((P**2.)**(1. / 3.)) * (1 - E) #days^2/3 #Calculate apastrons r_apast = ((P**2.)**(1. / 3.)) * (1 + E) #days^2/3 #Calculating roche radius roche_lim = Rstar * 2.44 * (RHOstar / RHOplanet)**(1. / 3.) #metres roche_P = np.sqrt(((4. * np.pi**2.) * roche_lim**3.) / (G * Mstar)) roche_P = roche_P / (60. * 60. * 24.) #convert into days roche_a = (roche_P**2.)**(1. / 3.) #days^2/3 #Remove any orbits closer than the roche limit roche_crossing = np.where(r_peri < roche_a)[0] count = roche_crossing.size results.T[roche_crossing] = np.nan results.removed_roche_crossing = True print("Number of roche crossing orbits removed =", count) return results # #Update results dataframe with removed values # results[periods] = allP # results[eccentricities] = alle # results[phis] = allphi # results[semiamps] = allK # results[omegas] = allomega # #Save as new results .txt file # new_header = ' '.join(header) # np.savetxt(r'{0}/remroche_posterior_sample.txt'.format(results_path),\ # results.values, header=new_header) # return results, allP, alle, allphi, allK, allomega
j-fariaREPO_NAMEkimaPATH_START.@kima_extracted@kima-master@pykima@crossing_orbits.py@.PATH_END.py
{ "filename": "mw.py", "repo_name": "astro-informatics/s2let", "repo_path": "s2let_extracted/s2let-main/src/test/python/mw.py", "type": "Python" }
import healpy as hp from pys2let import * import math import matplotlib.pyplot as plt import os import numpy as np L = 32 spin = 0 # fname = '/Users/bl/Dropbox/Astrodata/SDSS/Fields/Planck_EBV_256rQ.fits' fname = os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "data", "somecmbsimu_hpx_128.fits", ) # Read healpix map and compute alms. # f_lm has size L*(L+1)/2 f_hpx = hp.read_map(fname) # Initial map f_lm = hp.map2alm(f_hpx, lmax=L - 1) # Its alms # Convert to MW sampling from spherical harmonics f_mw = alm2map_mw(f_lm, L, spin) f_lm_rec = map2alm_mw(f_mw, L, spin) f_mw_rec = alm2map_mw(f_lm, L, spin) Lpix = 3 * L f_mw = alm2map_mw(f_lm, L, spin) f_lm_rec = map2alm_mw(f_mw, L, spin) f_mw_rec = alm2map_mw(f_lm, L, spin) def zeropad(flm, Lin, Lout): f_lm_out = np.zeros( [ int(Lout * (Lout + 1) / 2), ], dtype=complex, ) for el in range(Lin): for em in range(el + 1): f_lm_out[healpy_lm(el, em, Lout)] = f_lm[healpy_lm(el, em, Lin)] return f_lm_out f_lm_ext = zeropad(f_lm, L, Lpix) f_mw_ext = alm2map_mw(f_lm_ext, Lpix, spin) # f_mw_ext2 = alm2map_mw_bl(f_lm, 0, L, Lpix, spin) # f_lm_ext2 = map2alm_mw_bl(f_mw_ext2, 0, L, Lpix, spin) # f_mw_rec2 = alm2map_mw(f_lm_ext2, L, spin) # Home made plotting routine! inputs : function f (1D array of MW signal), bandlimit L, plot axis ax, and title def myplot(f, L, ax, title=""): # Compute the theta and phi values of the MW equiangular grid. thetas, phis = mw_sampling(L) ntheta = len(thetas) nphi = len(phis) arr = f.reshape((ntheta, nphi)) ax.imshow(arr.real, vmin=0, vmax=1) if L > 10: step_phi = int(L / 4) step_theta = int(L / 4) else: step_phi = 3 step_theta = 3 selec = np.arange(0, nphi, step_phi) # subset of phi tick labels ax.set_xticks(selec) ax.set_xticklabels(["%.1f" % x for x in phis[selec]]) ax.set_xlabel(r"$\phi$") selec = np.arange(0, ntheta, step_theta) # subset of theta tick labels ax.set_yticks(selec) ax.set_yticklabels(["%.1f" % x for x in thetas[selec]]) ax.set_ylabel(r"$\theta$") ax.set_title(title) # Plot equiangular map fig, axs = plt.subplots(1, 2) axs = axs.ravel() myplot(f_mw, L, axs[0], "L") myplot(f_mw_ext, Lpix, axs[1], "Lpix") # myplot(f_mw_ext2, Lpix, axs[2], 'Lpix') # myplot(f_mw_rec2, L, axs[3], 'L') plt.show()
astro-informaticsREPO_NAMEs2letPATH_START.@s2let_extracted@s2let-main@src@test@python@mw.py@.PATH_END.py
{ "filename": "figure.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/codegen/figure.py", "type": "Python" }
from io import StringIO from os import path as opath from codegen.datatypes import ( reindent_validator_description, add_constructor_params, add_docstring, ) from codegen.utils import write_source_py import inflect from plotly.basedatatypes import BaseFigure def build_figure_py( trace_node, base_package, base_classname, fig_classname, data_validator, layout_validator, frame_validator, subplot_nodes, layout_array_nodes, ): """ Parameters ---------- trace_node : PlotlyNode Root trace node (the node that is the parent of all of the individual trace nodes like bar, scatter, etc.) base_package : str Package that the figure's superclass resides in base_classname : str Name of the figure's superclass fig_classname : str Name of the Figure class to be generated data_validator : BaseDataValidator DataValidator instance layout_validator : CompoundValidator LayoutValidator instance frame_validator : CompoundArrayValidator FrameValidator instance subplot_nodes: list of str List of names of all of the layout subplot properties layout_array_nodes: list of PlotlyNode List of array nodes under layout that can be positioned using xref/yref Returns ------- str Source code for figure class definition """ # Initialize source code buffer # ----------------------------- buffer = StringIO() # Get list of trace type nodes # ---------------------------- trace_nodes = trace_node.child_compound_datatypes # Write imports # ------------- # ### Import base class ### buffer.write(f"from plotly.{base_package} import {base_classname}\n") # Write class definition # ---------------------- buffer.write( f""" class {fig_classname}({base_classname}):\n""" ) # ### Constructor ### # Build constructor description strings data_description = reindent_validator_description(data_validator, 8) layout_description = reindent_validator_description(layout_validator, 8) frames_description = reindent_validator_description(frame_validator, 8) buffer.write( f""" def __init__(self, data=None, layout=None, frames=None, skip_invalid=False, **kwargs): \"\"\" Create a new :class:{fig_classname} instance Parameters ---------- data {data_description} layout {layout_description} frames {frames_description} skip_invalid: bool If True, invalid properties in the figure specification will be skipped silently. If False (default) invalid properties in the figure specification will result in a ValueError Raises ------ ValueError if a property in the specification of data, layout, or frames is invalid AND skip_invalid is False \"\"\" super({fig_classname} ,self).__init__(data, layout, frames, skip_invalid, **kwargs) """ ) def add_wrapper(wrapped_name, full_params, param_list): buffer.write( f""" def {wrapped_name}(self, {full_params}) -> "{fig_classname}": ''' {getattr(BaseFigure, wrapped_name).__doc__} ''' return super({fig_classname}, self).{wrapped_name}({param_list}) """ ) add_wrapper( "update", "dict1=None, overwrite=False, **kwargs", "dict1, overwrite, **kwargs", ) add_wrapper( "update_traces", "patch=None, selector=None, row=None, col=None, secondary_y=None, overwrite=False, **kwargs", "patch, selector, row, col, secondary_y, overwrite, **kwargs", ) add_wrapper( "update_layout", "dict1=None, overwrite=False, **kwargs", "dict1, overwrite, **kwargs", ) add_wrapper( "for_each_trace", "fn, selector=None, row=None, col=None, secondary_y=None", "fn, selector, row, col, secondary_y", ) add_wrapper( "add_trace", "trace, row=None, col=None, secondary_y=None, exclude_empty_subplots=False", "trace, row, col, secondary_y, exclude_empty_subplots", ) add_wrapper( "add_traces", "data,rows=None,cols=None,secondary_ys=None,exclude_empty_subplots=False", "data,rows,cols,secondary_ys,exclude_empty_subplots", ) add_wrapper( "add_vline", 'x,row="all",col="all",exclude_empty_subplots=True,annotation=None,**kwargs', "x,row,col,exclude_empty_subplots,annotation,**kwargs", ) add_wrapper( "add_hline", 'y,row="all",col="all",exclude_empty_subplots=True,annotation=None,**kwargs', "y,row,col,exclude_empty_subplots,annotation,**kwargs", ) add_wrapper( "add_vrect", 'x0,x1,row="all",col="all",exclude_empty_subplots=True,annotation=None,**kwargs', "x0,x1,row,col,exclude_empty_subplots,annotation,**kwargs", ) add_wrapper( "add_hrect", 'y0,y1,row="all",col="all",exclude_empty_subplots=True,annotation=None,**kwargs', "y0,y1,row,col,exclude_empty_subplots,annotation,**kwargs", ) add_wrapper( "set_subplots", "rows=None, cols=None, **make_subplots_args", "rows, cols, **make_subplots_args", ) # ### add_trace methods for each trace type ### for trace_node in trace_nodes: include_secondary_y = bool( [d for d in trace_node.child_datatypes if d.name_property == "yaxis"] ) # #### Function signature #### buffer.write( f""" def add_{trace_node.plotly_name}(self""" ) # #### Function params#### param_extras = ["row", "col"] if include_secondary_y: param_extras.append("secondary_y") add_constructor_params( buffer, trace_node.child_datatypes, append_extras=param_extras, output_type=fig_classname, ) # #### Docstring #### header = f"Add a new {trace_node.name_datatype_class} trace" doc_extras = [ ( "row : 'all', int or None (default)", "Subplot row index (starting from 1) for the trace to be " "added. Only valid if figure was created using " "`plotly.tools.make_subplots`." "If 'all', addresses all rows in the specified column(s).", ), ( "col : 'all', int or None (default)", "Subplot col index (starting from 1) for the trace to be " "added. Only valid if figure was created using " "`plotly.tools.make_subplots`." "If 'all', addresses all columns in the specified row(s).", ), ] if include_secondary_y: doc_extras.append( ( "secondary_y: boolean or None (default None)", """\ If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info.\ """, ) ) add_docstring( buffer, trace_node, header, append_extras=doc_extras, return_type=fig_classname, ) # #### Function body #### buffer.write( f""" from plotly.graph_objs import {trace_node.name_datatype_class} new_trace = {trace_node.name_datatype_class}( """ ) for _, subtype_node in enumerate(trace_node.child_datatypes): subtype_prop_name = subtype_node.name_property buffer.write( f""" {subtype_prop_name}={subtype_prop_name},""" ) buffer.write( """ **kwargs)""" ) if include_secondary_y: secondary_y_kwarg = ", secondary_y=secondary_y" else: secondary_y_kwarg = "" buffer.write( f""" return self.add_trace( new_trace, row=row, col=col{secondary_y_kwarg})""" ) # update layout subplots # ---------------------- inflect_eng = inflect.engine() for subplot_node in subplot_nodes: singular_name = subplot_node.name_property plural_name = inflect_eng.plural_noun(singular_name) if singular_name == "yaxis": secondary_y_1 = ", secondary_y=None" secondary_y_2 = ", secondary_y=secondary_y" secondary_y_docstring = """ secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes.""" else: secondary_y_1 = "" secondary_y_2 = "" secondary_y_docstring = "" buffer.write( f""" def select_{plural_name}( self, selector=None, row=None, col=None{secondary_y_1}): \"\"\" Select {singular_name} subplot objects from a particular subplot cell and/or {singular_name} subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. {singular_name} objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all {singular_name} objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each {singular_name} and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of {singular_name} objects to select. To select {singular_name} objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all {singular_name} objects are selected.\ {secondary_y_docstring} Returns ------- generator Generator that iterates through all of the {singular_name} objects that satisfy all of the specified selection criteria \"\"\" return self._select_layout_subplots_by_prefix( '{singular_name}', selector, row, col{secondary_y_2}) def for_each_{singular_name}( self, fn, selector=None, row=None, col=None{secondary_y_1}) -> '{fig_classname}': \"\"\" Apply a function to all {singular_name} objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single {singular_name} object. selector: dict, function, or None (default None) Dict to use as selection criteria. {singular_name} objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all {singular_name} objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each {singular_name} and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of {singular_name} objects to select. To select {singular_name} objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all {singular_name} objects are selected.\ {secondary_y_docstring} Returns ------- self Returns the {fig_classname} object that the method was called on \"\"\" for obj in self.select_{plural_name}( selector=selector, row=row, col=col{secondary_y_2}): fn(obj) return self def update_{plural_name}( self, patch=None, selector=None, overwrite=False, row=None, col=None{secondary_y_1}, **kwargs) -> '{fig_classname}': \"\"\" Perform a property update operation on all {singular_name} objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all {singular_name} objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. {singular_name} objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all {singular_name} objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each {singular_name} and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of {singular_name} objects to select. To select {singular_name} objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all {singular_name} objects are selected.\ {secondary_y_docstring} **kwargs Additional property updates to apply to each selected {singular_name} object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the {fig_classname} object that the method was called on \"\"\" for obj in self.select_{plural_name}( selector=selector, row=row, col=col{secondary_y_2}): obj.update(patch, overwrite=overwrite, **kwargs) return self""" ) # update annotations/shapes/images # -------------------------------- for node in layout_array_nodes: singular_name = node.plotly_name plural_name = node.name_property if singular_name == "image": # Rename image to layout_image to avoid conflict with an image trace method_prefix = "layout_" else: method_prefix = "" buffer.write( f""" def select_{method_prefix}{plural_name}( self, selector=None, row=None, col=None, secondary_y=None ): \"\"\" Select {plural_name} from a particular subplot cell and/or {plural_name} that satisfy custom selection criteria. Parameters ---------- selector: dict, function, int, str, or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all {plural_name} are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each {singular_name} and those for which the function returned True will be in the selection. If an int N, the Nth {singular_name} matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of {plural_name} to select. To select {plural_name} by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those {singular_name} that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all {plural_name} are selected. secondary_y: boolean or None (default None) * If True, only select {plural_name} associated with the secondary y-axis of the subplot. * If False, only select {plural_name} associated with the primary y-axis of the subplot. * If None (the default), do not filter {plural_name} based on secondary y-axis. To select {plural_name} by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the {plural_name} that satisfy all of the specified selection criteria \"\"\" return self._select_annotations_like( "{plural_name}", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_{method_prefix}{singular_name}( self, fn, selector=None, row=None, col=None, secondary_y=None ): \"\"\" Apply a function to all {plural_name} that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single {singular_name} object. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all {plural_name} are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each {singular_name} and those for which the function returned True will be in the selection. If an int N, the Nth {singular_name} matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of {plural_name} to select. To select {plural_name} by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those {plural_name} that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all {plural_name} are selected. secondary_y: boolean or None (default None) * If True, only select {plural_name} associated with the secondary y-axis of the subplot. * If False, only select {plural_name} associated with the primary y-axis of the subplot. * If None (the default), do not filter {plural_name} based on secondary y-axis. To select {plural_name} by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the {fig_classname} object that the method was called on \"\"\" for obj in self._select_annotations_like( prop='{plural_name}', selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_{method_prefix}{plural_name}( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ) -> '{fig_classname}': \"\"\" Perform a property update operation on all {plural_name} that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all {plural_name} that satisfy the selection criteria. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all {plural_name} are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each {singular_name} and those for which the function returned True will be in the selection. If an int N, the Nth {singular_name} matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of {plural_name} to select. To select {plural_name} by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those {singular_name} that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all {plural_name} are selected. secondary_y: boolean or None (default None) * If True, only select {plural_name} associated with the secondary y-axis of the subplot. * If False, only select {plural_name} associated with the primary y-axis of the subplot. * If None (the default), do not filter {plural_name} based on secondary y-axis. To select {plural_name} by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected {singular_name}. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the {fig_classname} object that the method was called on \"\"\" for obj in self._select_annotations_like( prop='{plural_name}', selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self """ ) # Add layout array items buffer.write( f""" def add_{method_prefix}{singular_name}(self""" ) add_constructor_params( buffer, node.child_datatypes, prepend_extras=["arg"], append_extras=["row", "col", "secondary_y", "exclude_empty_subplots"], output_type=fig_classname, ) prepend_extras = [ ( "arg", f"instance of {node.name_datatype_class} or dict with " "compatible properties", ) ] append_extras = [ ( "row", f"Subplot row for {singular_name}. If 'all', addresses all rows in the specified column(s).", ), ( "col", f"Subplot column for {singular_name}. If 'all', addresses all columns in the specified row(s).", ), ("secondary_y", f"Whether to add {singular_name} to secondary y-axis"), ( "exclude_empty_subplots", f"If True, {singular_name} will not be added to subplots without traces.", ), ] add_docstring( buffer, node, header=f"Create and add a new {singular_name} to the figure's layout", prepend_extras=prepend_extras, append_extras=append_extras, return_type=fig_classname, ) # #### Function body #### buffer.write( f""" from plotly.graph_objs import layout as _layout new_obj = _layout.{node.name_datatype_class}(arg, """ ) for _, subtype_node in enumerate(node.child_datatypes): subtype_prop_name = subtype_node.name_property buffer.write( f""" {subtype_prop_name}={subtype_prop_name},""" ) buffer.write("""**kwargs)""") buffer.write( f""" return self._add_annotation_like( '{singular_name}', '{plural_name}', new_obj, row=row, col=col, secondary_y=secondary_y, exclude_empty_subplots=exclude_empty_subplots, )""" ) # Return source string # -------------------- buffer.write("\n") return buffer.getvalue() def write_figure_classes( outdir, trace_node, data_validator, layout_validator, frame_validator, subplot_nodes, layout_array_nodes, ): """ Construct source code for the Figure and FigureWidget classes and write to graph_objs/_figure.py and graph_objs/_figurewidget.py respectively Parameters ---------- outdir : str Root outdir in which the graph_objs package should reside trace_node : PlotlyNode Root trace node (the node that is the parent of all of the individual trace nodes like bar, scatter, etc.) data_validator : BaseDataValidator DataValidator instance layout_validator : CompoundValidator LayoutValidator instance frame_validator : CompoundArrayValidator FrameValidator instance subplot_nodes: list of PlotlyNode List of names of all of the layout subplot properties layout_array_nodes: list of PlotlyNode List of array nodes under layout that can be positioned using xref/yref Returns ------- None """ # Validate inputs # --------------- if trace_node.node_path: raise ValueError( f"Expected root trace node.\n" f'Received node with path "{trace_node.path_str}"' ) # Loop over figure types # ---------------------- base_figures = [ ("basewidget", "BaseFigureWidget", "FigureWidget"), ("basedatatypes", "BaseFigure", "Figure"), ] for base_package, base_classname, fig_classname in base_figures: # ### Build figure source code string ### figure_source = build_figure_py( trace_node, base_package, base_classname, fig_classname, data_validator, layout_validator, frame_validator, subplot_nodes, layout_array_nodes, ) # ### Format and write to file### filepath = opath.join(outdir, "graph_objs", f"_{fig_classname.lower()}.py") write_source_py(figure_source, filepath)
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@codegen@figure.py@.PATH_END.py
{ "filename": "srd_batch.py", "repo_name": "lsst/rubin_sim", "repo_path": "rubin_sim_extracted/rubin_sim-main/rubin_sim/maf/batches/srd_batch.py", "type": "Python" }
"""Metrics to investigate quantities related to SRD. Potentially could diverge from versions in scienceRadar. """ __all__ = ("fOBatch", "astrometryBatch", "rapidRevisitBatch") import warnings import healpy as hp import numpy as np import rubin_sim.maf.metric_bundles as mb import rubin_sim.maf.metrics as metrics import rubin_sim.maf.plots as plots import rubin_sim.maf.slicers as slicers import rubin_sim.maf.stackers as stackers from .col_map_dict import col_map_dict from .common import standard_summary def fOBatch( colmap=None, run_name="run_name", extra_sql=None, extra_info=None, slicer=None, benchmark_area=18000, benchmark_n_visits=825, min_n_visits=750, ): """Metrics for calculating fO. Parameters ---------- colmap : `dict` or None, opt A dictionary with a mapping of column names. run_name : `str`, opt The name of the simulated survey. extra_sql : `str` or None, opt Additional sql constraint to apply to all metrics. extra_Info : `str` or None, opt Additional info_label to apply to all results. slicer : `rubin_sim.maf.slicer.HealpixSlicer` or None, opt This must be a HealpixSlicer or some kind, although could be a HealpixSubsetSlicer. None will default to HealpixSlicer with nside=64. benchmark_area : `float`, opt Area to use when calculating fO_Nvis, for design. benchmark_n_visits : `float`, opt Nvisits minimum to use when calculating fO_Area, for design. min_n_visits : `float`, opt Nvisits minimum to use when calculating fO_Area, for minimum. Returns ------- metric_bundleDict : `dict` of `maf.MetricBundle` """ if colmap is None: colmap = col_map_dict() bundleList = [] sql = "" info_label = "All visits" # Add additional sql constraint (such as wfdWhere) and info_label if (extra_sql is not None) and (len(extra_sql) > 0): sql = extra_sql if extra_info is None: info_label = extra_sql.replace("filter =", "").replace("filter=", "") info_label = info_label.replace('"', "").replace("'", "") if extra_info is not None: info_label = extra_info subgroup = info_label raCol = colmap["ra"] decCol = colmap["dec"] degrees = colmap["raDecDeg"] # Set up fO metric. if slicer is None: nside = 64 slicer = slicers.HealpixSlicer(nside=nside, lat_col=decCol, lon_col=raCol, lat_lon_deg=degrees) else: try: nside = slicer.nside except AttributeError: warnings.warn("Must use a healpix slicer. Swapping to the default.") nside = 64 slicer = slicers.HealpixSlicer(nside=nside, lat_col=decCol, lon_col=raCol, lat_lon_deg=degrees) displayDict = {"group": "SRD FO metrics", "subgroup": subgroup, "order": 0} # Configure the count metric which is what is used for f0 slicer. metric = metrics.CountExplimMetric(metric_name="fO", exp_col=colmap["exptime"]) plotDict = { "xlabel": "Number of Visits", "asky": benchmark_area, "n_visits": min_n_visits, "x_min": 0, "x_max": 1500, } summaryMetrics = [ metrics.FOArea( nside=nside, norm=False, metric_name="fOArea", asky=benchmark_area, n_visit=benchmark_n_visits, ), metrics.FOArea( nside=nside, norm=True, metric_name="fOArea/benchmark", asky=benchmark_area, n_visit=benchmark_n_visits, ), metrics.FONv( nside=nside, norm=False, metric_name="fONv", asky=benchmark_area, n_visit=benchmark_n_visits, ), metrics.FONv( nside=nside, norm=True, metric_name="fONv/benchmark", asky=benchmark_area, n_visit=benchmark_n_visits, ), metrics.FOArea( nside=nside, norm=False, metric_name=f"fOArea_{min_n_visits}", asky=benchmark_area, n_visit=min_n_visits, ), ] caption = "The FO metric evaluates the overall efficiency of observing. " caption += ( "foNv: out of %.2f sq degrees, the area receives at least X and a median of Y visits " "(out of %d, if compared to benchmark). " % (benchmark_area, benchmark_n_visits) ) caption += ( "fOArea: this many sq deg (out of %.2f sq deg if compared " "to benchmark) receives at least %d visits. " % (benchmark_area, benchmark_n_visits) ) displayDict["caption"] = caption bundle = mb.MetricBundle( metric, slicer, sql, plot_dict=plotDict, display_dict=displayDict, summary_metrics=summaryMetrics, plot_funcs=[plots.FOPlot()], info_label=info_label, ) bundleList.append(bundle) # Set the run_name for all bundles and return the bundleDict. for b in bundleList: b.set_run_name(run_name) return mb.make_bundles_dict_from_list(bundleList) def astrometryBatch( colmap=None, run_name="opsim", extra_sql=None, extra_info=None, slicer=None, ): """Metrics for evaluating proper motion and parallax. Parameters ---------- colmap : `dict` or None, optional A dictionary with a mapping of column names. run_name : `str`, optional The name of the simulated survey. extra_sql : `str` or None, optional Additional sql constraint to apply to all metrics. extra_info : `str` or None, optional Additional info_label to apply to all results. slicer : `rubin_sim.maf.slicer` or None, optional Optionally, specify something other than an nside=64 healpix slicer. Returns ------- metric_bundleDict : `dict` of `maf.MetricBundle` """ if colmap is None: colmap = col_map_dict() bundleList = [] sql = "" info_label = "All visits" # Add additional sql constraint (such as wfdWhere) and info_label if (extra_sql is not None) and (len(extra_sql) > 0): sql = extra_sql if extra_info is None: info_label = extra_sql.replace("filter =", "").replace("filter=", "") info_label = info_label.replace('"', "").replace("'", "") if extra_info is not None: info_label = extra_info subgroup = info_label raCol = colmap["ra"] decCol = colmap["dec"] degrees = colmap["raDecDeg"] rmags_para = [22.4, 24.0] rmags_pm = [20.5, 24.0] # Set up parallax/dcr stackers. parallaxStacker = stackers.ParallaxFactorStacker( ra_col=raCol, dec_col=decCol, date_col=colmap["mjd"], degrees=degrees ) dcrStacker = stackers.DcrStacker( filter_col=colmap["filter"], alt_col=colmap["alt"], degrees=degrees, ra_col=raCol, dec_col=decCol, lst_col=colmap["lst"], site="LSST", mjd_col=colmap["mjd"], ) # Set up parallax metrics. if slicer is None: slicer = slicers.HealpixSlicer(nside=64, lon_col=raCol, lat_col=decCol, lat_lon_deg=degrees) subsetPlots = [plots.HealpixSkyMap(), plots.HealpixHistogram()] displayDict = { "group": "SRD Parallax", "subgroup": subgroup, "order": 0, "caption": None, } # Expected error on parallax at 10 AU. plotmaxVals = (5.0, 18.0) good_parallax_limit = 11.5 summary = [ metrics.AreaSummaryMetric( area=18000, reduce_func=np.median, decreasing=False, metric_name="Median Parallax Uncert (18k)", ), metrics.AreaThresholdMetric( upper_threshold=good_parallax_limit, metric_name="Area better than %.1f mas uncertainty" % good_parallax_limit, ), ] summary.append(metrics.PercentileMetric(percentile=95, metric_name="95th Percentile Parallax Uncert")) summary.extend(standard_summary()) for rmag, plotmax in zip(rmags_para, plotmaxVals): plotDict = {"x_min": 0, "x_max": plotmax, "color_min": 0, "color_max": plotmax} metric = metrics.ParallaxMetric( metric_name="Parallax Uncert @ %.1f" % (rmag), rmag=rmag, seeing_col=colmap["seeingGeom"], filter_col=colmap["filter"], m5_col=colmap["fiveSigmaDepth"], normalize=False, ) bundle = mb.MetricBundle( metric, slicer, sql, info_label=info_label, stacker_list=[parallaxStacker], display_dict=displayDict, plot_dict=plotDict, summary_metrics=summary, plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Parallax normalized to 'best possible' # This separates the effect of cadence from depth. for rmag in rmags_para: metric = metrics.ParallaxMetric( metric_name="Normalized Parallax Uncert @ %.1f" % (rmag), rmag=rmag, seeing_col=colmap["seeingGeom"], filter_col=colmap["filter"], m5_col=colmap["fiveSigmaDepth"], normalize=True, ) bundle = mb.MetricBundle( metric, slicer, sql, info_label=info_label, stacker_list=[parallaxStacker], display_dict=displayDict, summary_metrics=standard_summary(), plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Parallax factor coverage. for rmag in rmags_para: metric = metrics.ParallaxCoverageMetric( metric_name="Parallax Coverage @ %.1f" % (rmag), rmag=rmag, m5_col=colmap["fiveSigmaDepth"], mjd_col=colmap["mjd"], filter_col=colmap["filter"], seeing_col=colmap["seeingGeom"], ) bundle = mb.MetricBundle( metric, slicer, sql, info_label=info_label, stacker_list=[parallaxStacker], display_dict=displayDict, summary_metrics=standard_summary(), plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Parallax problems can be caused by HA and DCR degeneracies. # Check their correlation. for rmag in rmags_para: metric = metrics.ParallaxDcrDegenMetric( metric_name="Parallax-DCR degeneracy @ %.1f" % (rmag), rmag=rmag, seeing_col=colmap["seeingEff"], filter_col=colmap["filter"], m5_col=colmap["fiveSigmaDepth"], ) caption = "Correlation between parallax offset magnitude and hour angle for a r=%.1f star." % (rmag) caption += " (0 is good, near -1 or 1 is bad)." bundle = mb.MetricBundle( metric, slicer, sql, info_label=info_label, stacker_list=[dcrStacker, parallaxStacker], display_dict=displayDict, summary_metrics=standard_summary(), plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Evaluate y-band-only parallax uncertainty # Approximate "10sigma sources" as y=21.33 ymag = 21.33 if info_label == "All visits": yinfo = "y band visits" else: yinfo = f"{info_label} y band only" if len(sql) == 0: ysql = "filter == 'y'" else: ysql = f"{sql} and filter == 'y'" plotDict = {"x_min": 0, "x_max": 15, "color_min": 0, "color_max": 15} metric = metrics.ParallaxMetric( metric_name="Parallax Uncert @ %.1f" % (ymag), rmag=ymag, seeing_col=colmap["seeingGeom"], filter_col=colmap["filter"], m5_col=colmap["fiveSigmaDepth"], normalize=False, ) bundle = mb.MetricBundle( metric, slicer, ysql, info_label=yinfo, stacker_list=[parallaxStacker], display_dict=displayDict, plot_dict=plotDict, summary_metrics=summary, plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 metric = metrics.ParallaxMetric( metric_name="Normalized Parallax Uncert @ %.1f" % (ymag), rmag=ymag, seeing_col=colmap["seeingGeom"], filter_col=colmap["filter"], m5_col=colmap["fiveSigmaDepth"], normalize=True, ) bundle = mb.MetricBundle( metric, slicer, ysql, info_label=yinfo, stacker_list=[parallaxStacker], display_dict=displayDict, summary_metrics=summary, plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Proper Motion metrics. displayDict = { "group": "SRD Proper Motion", "subgroup": subgroup, "order": 0, "caption": None, } # Proper motion errors. plotmaxVals = (1.0, 5.0) summary = [ metrics.AreaSummaryMetric( area=18000, reduce_func=np.median, decreasing=False, metric_name="Median Proper Motion Uncert (18k)", ) ] summary.append(metrics.PercentileMetric(metric_name="95th Percentile Proper Motion Uncert")) summary.extend(standard_summary()) for rmag, plotmax in zip(rmags_pm, plotmaxVals): plotDict = {"x_min": 0, "x_max": plotmax, "color_min": 0, "color_max": plotmax} metric = metrics.ProperMotionMetric( metric_name="Proper Motion Uncert @ %.1f" % rmag, rmag=rmag, m5_col=colmap["fiveSigmaDepth"], mjd_col=colmap["mjd"], filter_col=colmap["filter"], seeing_col=colmap["seeingGeom"], normalize=False, ) bundle = mb.MetricBundle( metric, slicer, sql, info_label=info_label, display_dict=displayDict, plot_dict=plotDict, summary_metrics=summary, plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Normalized proper motion. for rmag in rmags_pm: metric = metrics.ProperMotionMetric( metric_name="Normalized Proper Motion Uncert @ %.1f" % rmag, rmag=rmag, m5_col=colmap["fiveSigmaDepth"], mjd_col=colmap["mjd"], filter_col=colmap["filter"], seeing_col=colmap["seeingGeom"], normalize=True, ) bundle = mb.MetricBundle( metric, slicer, sql, info_label=info_label, display_dict=displayDict, summary_metrics=standard_summary(), plot_funcs=subsetPlots, ) bundleList.append(bundle) displayDict["order"] += 1 # Set the run_name for all bundles and return the bundleDict. for b in bundleList: b.set_run_name(run_name) return mb.make_bundles_dict_from_list(bundleList) def rapidRevisitBatch( colmap=None, run_name="opsim", extra_sql=None, extra_info=None, slicer=None, ): """Metrics for evaluating proper motion and parallax. Parameters ---------- colmap : `dict` or None, optional A dictionary with a mapping of column names. run_name : `str`, optional The name of the simulated survey. extra_sql : `str` or None, optional Additional sql constraint to apply to all metrics. extra_info : `str` or None, optional Additional info_label to apply to all results. slicer : `rubin_sim_maf.slicers.HealpixSlicer` or None, optional Optionally, specify something other than an nside=64 healpix slicer. (must be a healpix slicer) Returns ------- metric_bundleDict : `dict` of `maf.MetricBundle` """ if colmap is None: colmap = col_map_dict() bundleList = [] sql = "" info_label = "All visits" # Add additional sql constraint (such as wfdWhere) and info_label. if (extra_sql is not None) and (len(extra_sql) > 0): sql = extra_sql if extra_info is None: info_label = extra_sql.replace("filter =", "").replace("filter=", "") info_label = info_label.replace('"', "").replace("'", "") if extra_info is not None: info_label = extra_info subgroup = info_label raCol = colmap["ra"] decCol = colmap["dec"] degrees = colmap["raDecDeg"] if slicer is None: nside = 64 slicer = slicers.HealpixSlicer(nside=nside, lon_col=raCol, lat_col=decCol, lat_lon_deg=degrees) else: try: nside = slicer.nside except AttributeError: warnings.warn("Must use a healpix slicer. Swapping to the default.") nside = 64 slicer = slicers.HealpixSlicer(nside=nside, lat_col=decCol, lon_col=raCol, lat_lon_deg=degrees) subsetPlots = [plots.HealpixSkyMap(), plots.HealpixHistogram()] displayDict = { "group": "SRD Rapid Revisits", "subgroup": subgroup, "order": 0, "caption": None, } # Calculate the actual number of revisits within 30 minutes. dTmax = 30 # time in minutes m2 = metrics.NRevisitsMetric( d_t=dTmax, mjd_col=colmap["mjd"], normed=False, metric_name="NumberOfQuickRevisits", ) plotDict = {"color_min": 400, "color_max": 2000, "x_min": 400, "x_max": 2000} caption = "Number of consecutive visits with return times faster than %.1f minutes, " % (dTmax) caption += "in any filter, all proposals. " displayDict["caption"] = caption bundle = mb.MetricBundle( m2, slicer, sql, plot_dict=plotDict, plot_funcs=subsetPlots, info_label=info_label, display_dict=displayDict, summary_metrics=standard_summary(with_count=False), ) bundleList.append(bundle) displayDict["order"] += 1 # Better version of the rapid revisit requirements: # require a minimum number of visits between # dtMin and dtMax, but also a minimum number of visits # between dtMin and dtPair (the typical pair time). # 1 means the healpix met the requirements (0 means did not). dTmin = 40.0 / 60.0 # (minutes) 40s minimum for rapid revisit range dTpairs = 20.0 # minutes (time when pairs should start kicking in) dTmax = 30.0 # 30 minute maximum for rapid revisit range nOne = 82 # Number of revisits between 40s-30m required nTwo = 28 # Number of revisits between 40s - tPairs required. pix_area = float(hp.nside2pixarea(nside, degrees=True)) scale = pix_area * hp.nside2npix(nside) m1 = metrics.RapidRevisitMetric( metric_name="RapidRevisits", mjd_col=colmap["mjd"], d_tmin=dTmin / 60.0 / 60.0 / 24.0, d_tpairs=dTpairs / 60.0 / 24.0, d_tmax=dTmax / 60.0 / 24.0, min_n1=nOne, min_n2=nTwo, ) plotDict = { "x_min": 0, "x_max": 1, "color_min": 0, "color_max": 1, "log_scale": False, } cutoff1 = 0.9 summaryStats = [metrics.FracAboveMetric(cutoff=cutoff1, scale=scale, metric_name="Area (sq deg)")] caption = "Rapid Revisit: area that receives at least %d visits between %.3f and %.1f minutes, " % ( nOne, dTmin, dTmax, ) caption += "with at least %d of those visits falling between %.3f and %.1f minutes. " % ( nTwo, dTmin, dTpairs, ) caption += ( 'Summary statistic "Area" indicates the area on the sky which meets this requirement.' " (SRD design specification is 2000 sq deg)." ) displayDict["caption"] = caption bundle = mb.MetricBundle( m1, slicer, sql, plot_dict=plotDict, plot_funcs=subsetPlots, info_label=info_label, display_dict=displayDict, summary_metrics=summaryStats, ) bundleList.append(bundle) displayDict["order"] += 1 # Set the run_name for all bundles and return the bundleDict. for b in bundleList: b.set_run_name(run_name) return mb.make_bundles_dict_from_list(bundleList)
lsstREPO_NAMErubin_simPATH_START.@rubin_sim_extracted@rubin_sim-main@rubin_sim@maf@batches@srd_batch.py@.PATH_END.py
{ "filename": "demo_FEA_loads_static.py", "repo_name": "projectchrono/chrono", "repo_path": "chrono_extracted/chrono-main/src/demos/python/fea/demo_FEA_loads_static.py", "type": "Python" }
# ============================================================================= # PROJECT CHRONO - http://projectchrono.org # # Copyright (c) 2014 projectchrono.org # All rights reserved. # # Use of this source code is governed by a BSD-style license that can be found # in the LICENSE file at the top level of the distribution and at # http://projectchrono.org/license-chrono.txt. # # ============================================================================= import pychrono as chrono import pychrono.fea as fea import copy print("Copyright (c) 2017 projectchrono.org ") # Create the physical system sys = chrono.ChSystemSMC() # Create a mesh: mesh = fea.ChMesh() sys.Add(mesh) # Create some nodes. nodeA = fea.ChNodeFEAxyzrot(chrono.ChFramed(chrono.ChVector3d(0, 0, 0))) nodeB = fea.ChNodeFEAxyzrot(chrono.ChFramed(chrono.ChVector3d(2, 0, 0))) # Default mass for FEM nodes is zero nodeA.SetMass(0.0) nodeB.SetMass(0.0) mesh.AddNode(nodeA) mesh.AddNode(nodeB) # Create beam section & material beam_section = fea.ChBeamSectionEulerAdvanced() beam_wy = 0.1 beam_wz = 0.2 beam_section.SetAsRectangularSection(beam_wy, beam_wz) beam_section.SetYoungModulus(0.01e9) beam_section.SetShearModulus(0.01e9 * 0.3) beam_section.SetRayleighDamping(0.200) beam_section.SetDensity(1500) # Create a beam of Eulero-Bernoulli type: elementA = fea.ChElementBeamEuler() elementA.SetNodes(nodeA, nodeB) elementA.SetSection(beam_section) mesh.AddElement(elementA) # Create also a truss truss = chrono.ChBody() truss.SetFixed(True) sys.Add(truss) # Create a constraat the end of the beam constraintA = chrono.ChLinkMateGeneric() constraintA.Initialize(nodeA, truss, False, nodeA.Frame(), nodeA.Frame()) sys.Add(constraintA) constraintA.SetConstrainedCoords(True, True, True, # x, y, z True, True, True) # Rx, Ry, Rz # APPLY SOME LOADS! # First: loads must be added to "load containers", # and load containers must be added to your system load_container = chrono.ChLoadContainer() sys.Add(load_container) # Example 1: # Add a vertical load to the end of the beam element: wrench_load = fea.ChLoadBeamWrench(elementA) wrench_load.GetLoader().SetApplication(1.0) # in -1..+1 range, -1: end A, 0: mid, +1: end B wrench_load.GetLoader().SetForce(chrono.ChVector3d(0, -0.2, 0)) load_container.Add(wrench_load) # do not forget to add the load to the load container. # Example 2: # Add a distributed load along the beam element: distr_wrench_load = fea.ChLoadBeamWrenchDistributed(elementA) distr_wrench_load.GetLoader().SetForcePerUnit(chrono.ChVector3d(0, -0.1, 0)) # load per unit length load_container.Add(distr_wrench_load) # Example 3: # Add gravity (constant volumetric load) gravity_loader = chrono.ChLoaderGravity(elementA) gravity_load = chrono.ChLoad(gravity_loader) load_container.Add(gravity_load) # note that by default all solid elements in the mesh will already # get gravitational force, if you want to bypass this automatic gravity, do: mesh.SetAutomaticGravity(False) ### TODO Examples 4 & 5 in corresponding C++ demo # Example 6: # As before, create a custom load with stiff force, acting on a single node, but # this time we inherit directly from ChLoadCustom, i.e. a load that does not require ChLoader features. # This is mostly used in case one does not need the automatic surface/volume quadrature of ChLoader. # As a stiff load, this will automatically generate a jacobian (tangent stiffness matrix K) # that will be used in statics, implicit integrators, etc. nodeD = fea.ChNodeFEAxyz(chrono.ChVector3d(2, 10, 3)) mesh.AddNode(nodeD) class MyLoadCustom(chrono.ChLoadCustom): def __init__(self, loadable): chrono.ChLoadCustom.__init__(self, loadable) # "Virtual" copy constructor (covariant return type). def Clone(self): newinst = copy.deepcopy(self) return newinst # Compute Q=Q(x,v) # This is the function that you have to implement. It should return the generalized Q load # (i.e.the force in generalized lagrangian coordinates). # For ChNodeFEAxyz, Q loads are expected as 3-rows vectors, containing absolute force x,y,z. # As this is a stiff force field, dependency from state_x and state_y must be considered. def ComputeQ(self,state_x, # state position to evaluate Q state_w): # state speed to evaluate Q if not state_x==None and not state_w==None : node_pos = chrono.ChVector3d(state_x.GetItem(0), state_x.GetItem(1), state_x.GetItem(2)) node_vel = chrono.ChVector3d(state_w.GetItem(0), state_w.GetItem(1), state_w.GetItem(2)) else: mynode = fea.CastToChNodeFEAxyz( fea.CastToChNodeFEAbase( chrono.CastToChNodeBase(self.loadable) )) node_pos = mynode.GetPos() node_vel = mynode.GetPosDt() # Just implement a simple force+spring+damper in xy plane, # for spring&damper connected to absolute reference: Kx = 100 Ky = 400 Dx = 0.6 Dy = 0.9 x_offset = 2 y_offset = 10 x_force = 50 y_force = 0 # Store the computed generalized forces in this.load_Q, same x,y,z order as in state_w self.load_Q.SetItem(0, x_force - Kx * (node_pos.x - x_offset) - Dx * node_vel.x) self.load_Q.SetItem(1, y_force - Ky * (node_pos.y - y_offset) - Dy * node_vel.y) self.load_Q.SetItem(2, 0.0) # Compute jacobian not available from Python # Set this as stiff, to enable the Jacobians def IsStiff(self) : return True # Instance load object, applying to a node, as in previous example, and add to container: custom_load = MyLoadCustom(nodeD) load_container.Add(custom_load) # Example 7: # As before, create a custom load with stiff force, acting on MULTIPLE nodes at once. # This time we will need the ChLoadCustomMultiple as base class. # Those nodes (ie.e ChLoadable objects) can be added in mesh in whatever order, # not necessarily contiguous, because the bookkeeping is automated. # Being a stiff load, a jacobian will be automatically generated # by default using numerical differentiation but if you want you # can override ComputeJacobian() and compute mK, mR analytically - see prev.example. nodeE = fea.ChNodeFEAxyz(chrono.ChVector3d(2, 10, 3)) mesh.AddNode(nodeE) nodeF = fea.ChNodeFEAxyz(chrono.ChVector3d(2, 11, 3)) mesh.AddNode(nodeF) class MyLoadCustomMultiple(chrono.ChLoadCustomMultiple): def __init__(self, loadables): chrono.ChLoadCustomMultiple.__init__(self, loadables) # "Virtual" copy constructor (covariant return type). def Clone(self): print('I am there!') newinst = copy.deepcopy(self) return newinst # Compute Q=Q(x,v) # This is the function that you have to implement. It should return the generalized Q load # (i.e.the force in generalized lagrangian coordinates). # Since here we have multiple connected ChLoadable objects (the two nodes), the rule is that # all the vectors (load_Q, state_x, state_w) are split in the same order that the loadable objects # are added to MyLoadCustomMultiple in this case for instance Q={Efx,Efy,Efz,Ffx,Ffy,Ffz}. # As this is a stiff force field, dependency from state_x and state_y must be considered. def ComputeQ(self,state_x, # state position to evaluate Q state_w): # state speed to evaluate Q #chrono.ChVector3d Enode_pos #chrono.ChVector3d Enode_vel #chrono.ChVector3d Fnode_pos #chrono.ChVector3d Fnode_vel if not state_x==None and not state_w==None : Enode_pos = chrono.ChVector3d(state_x.GetItem(0), state_x.GetItem(1), state_x.GetItem(2)) Enode_vel = chrono.ChVector3d(state_w.GetItem(0), state_w.GetItem(1), state_w.GetItem(2)) Fnode_pos = chrono.ChVector3d(state_x.GetItem(3), state_x.GetItem(4), state_x.GetItem(5)) Fnode_vel = chrono.ChVector3d(state_w.GetItem(3), state_w.GetItem(4), state_w.GetItem(5)) else: # explicit integrators might call ComputeQ(0,0), null pointers mean # that we assume current state, without passing state_x for efficiency Enode = fea.CastToChNodeFEAxyz( fea.CastToChNodeFEAbase( chrono.CastToChNodeBase(self.loadables[0]))) Fnode = fea.CastToChNodeFEAxyz( fea.CastToChNodeFEAbase( chrono.CastToChNodeBase(self.loadables[1]))) Enode_pos = Enode.GetPos() Enode_vel = Enode.GetPosDt() Fnode_pos = Fnode.GetPos() Fnode_vel = Fnode.GetPosDt() # Just implement two simple force+spring+dampers in xy plane: # ... from node E to ground, Kx1 = 60 Ky1 = 50 Dx1 = 0.3 Dy1 = 0.2 E_x_offset = 2 E_y_offset = 10 spring1 = chrono.ChVector3d(-Kx1 * (Enode_pos.x - E_x_offset) - Dx1 * Enode_vel.x, -Ky1 * (Enode_pos.y - E_y_offset) - Dy1 * Enode_vel.y, 0) # ... from node F to node E, Ky2 = 10 Dy2 = 0.2 EF_dist = 1 spring2 = chrono.ChVector3d (0, -Ky2 * (Fnode_pos.y - Enode_pos.y - EF_dist) - Dy2 * (Enode_vel.y - Fnode_vel.y), 0) Fforcey = 2 # store generalized forces as a contiguous vector in this.load_Q, with same order of state_w self.load_Q.SetItem(0, spring1.x - spring2.x) # Fx component of force on 1st node self.load_Q.SetItem(1, spring1.y - spring2.y) # Fy component of force on 1st node self.load_Q.SetItem(2, spring1.z - spring2.z) # Fz component of force on 1st node self.load_Q.SetItem(3, spring2.x) # Fx component of force on 2nd node self.load_Q.SetItem(4, spring2.y + Fforcey) # Fy component of force on 2nd node self.load_Q.SetItem(5, spring2.z) # Fz component of force on 2nd node # Set this as stiff, to enable the Jacobians def IsStiff(self) : return True # Instance load object. This require a list of ChLoadable objects # (these are our two nodes,pay attention to the sequence order), and add to container. node_list = chrono.vector_ChLoadable() node_list.append(nodeE) node_list.append(nodeF) custom_multi_load = MyLoadCustomMultiple(node_list) load_container.Add(custom_multi_load) # -------------------- # Setup a MINRES solver. For FEA one cannot use the default PSOR type solver. solver = chrono.ChSolverMINRES() sys.SetSolver(solver) solver.SetMaxIterations(100) solver.SetTolerance(1e-10) solver.EnableDiagonalPreconditioner(True) solver.SetVerbose(True) # Perform a static analysis: sys.DoStaticLinear() reaction = constraintA.GetReaction2() print(" constraintA reaction force F= " + str(reaction.force)) print( " constraintA reaction torque T= " + str(reaction.torque)) print("nodeD position = ") print(nodeD.GetPos() ) print("custom_load K jacobian=" ) print( custom_load.GetJacobians().K.GetMatr() ) print(" nodeE position = " ) print( nodeE.GetPos() ) print(" nodeF position = " ) print( nodeF.GetPos() ) print(" custom_multi_load K jacobian=" ) print( custom_multi_load.GetJacobians().K.GetMatr() )
projectchronoREPO_NAMEchronoPATH_START.@chrono_extracted@chrono-main@src@demos@python@fea@demo_FEA_loads_static.py@.PATH_END.py
{ "filename": "utils.ipynb", "repo_name": "NOAO/nat-nb", "repo_path": "nat-nb_extracted/nat-nb-master/utils.ipynb", "type": "Jupyter Notebook" }
[![alt text](moon-snail.jpg "Moon Snail, Natica catena" )](http://www.aphotomarine.com/snail_euspira_catena_necklace_shell.html) ## Goals This notebook is intended to be loaded (using %run) into other notebooks in the same directory. It provides common configuration variables to the notebooks that load it. It is used across _Astro Data Archive_ "how-to" juypter notebooks. ```python import time def tic(): tic.start = time.perf_counter() def toc(): elapsed_seconds = time.perf_counter() - tic.start return elapsed_seconds # fractional about_archive = 'https://astroarchive.noirlab.edu/about/' # Example use of tic-toc # tic() # time.sleep(3) # print(toc()) ``` ```python # Public config natroot = 'https://astroarchive.noirlab.edu' #!natroot = 'http://localhost:8020/' testUserEmail = 'demo_user@mail.edu' testUserPassword = '!Password' testProposal = 'test-prop' publicFileId = '0000298c7e0b3ce96b3fff51515a6100' #proprietaryFileId = '5cb627467b1e4c28a18cd491cf09272e' # from S&F proprietaryFileId = 'a96e55509a4cf89ebcc3126bef2e6aa7' # from S&F proprietaryArch = 'c4d_140725_004418_ooi_g_v1.fits.fz' # from S&F m5url=f'{natroot}/api/retrieve/84289f753e3155b55955b7d4ffeb7c4b/?hdus=35' # for zoom ``` ```python print(f"Using server on {natroot}") print(f"About NSF's OIR Lab Astro Data Archive: {about_archive}") ``` Using server on https://astroarchive.noao.edu About NSF's OIR Lab Astro Data Archive: https://astroarchive.noao.edu/about/ ```python assert natroot == 'https://astroarchive.noirlab.edu', 'Notebook does NOT point to PRODUCTION' ```
NOAOREPO_NAMEnat-nbPATH_START.@nat-nb_extracted@nat-nb-master@utils.ipynb@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "brinckmann/montepython_public", "repo_path": "montepython_public_extracted/montepython_public-master/montepython/likelihoods/bao_boss_aniso_gauss_approx/__init__.py", "type": "Python" }
import os import numpy as np import warnings import montepython.io_mp as io_mp from montepython.likelihood_class import Likelihood import scipy.constants as conts class bao_boss_aniso_gauss_approx(Likelihood): # initialization routine def __init__(self, path, data, command_line): Likelihood.__init__(self, path, data, command_line) # are there conflicting experiments? if 'bao_boss_aniso' in data.experiments: raise io_mp.LikelihoodError( 'conflicting bao_boss_aniso measurments') # define array for values of z and data points self.z = np.array([], 'float64') self.DA_rdfid_by_rd_in_Mpc = np.array([], 'float64') self.DA_error = np.array([], 'float64') self.H_rd_by_rdfid_in_km_per_s_per_Mpc = np.array([], 'float64') self.H_error = np.array([], 'float64') self.cross_corr = np.array([], 'float64') self.rd_fid_in_Mpc = np.array([], 'float64') # read redshifts and data points i = 0 with open(os.path.join(self.data_directory, self.file), 'r') as filein: for i, line in enumerate(filein): if line.strip() and line.find('#') == -1: this_line = line.split() # this_line[0] is some identifier self.z = np.append(self.z, float(this_line[1])) self.DA_rdfid_by_rd_in_Mpc = np.append( self.DA_rdfid_by_rd_in_Mpc, float(this_line[2])) self.DA_error = np.append( self.DA_error, float(this_line[3])) self.H_rd_by_rdfid_in_km_per_s_per_Mpc = np.append( self.H_rd_by_rdfid_in_km_per_s_per_Mpc, float(this_line[4])) self.H_error = np.append( self.H_error, float(this_line[5])) self.cross_corr = np.append( self.cross_corr, float(this_line[6])) self.rd_fid_in_Mpc = np.append( self.rd_fid_in_Mpc, float(this_line[7])) # is the cross correlation coefficient valid #if self.cross_corr[i] < -1.0 or self.cross_corr[i] > 1.0: # raise io_mp.LikelihoodError( # "invalid cross correlation coefficient in entry " # "%d: %f" % (i, self.cross_corr[i])) # number of data points self.num_points = np.shape(self.z)[0] # end of initialization # compute likelihood def loglkl(self, cosmo, data): chi2 = 0. # for each point, compute angular distance da, radial distance dr, # volume distance dv, sound horizon at baryon drag rs_d, # theoretical prediction and chi2 contribution for i in range(self.num_points): DA_at_z = cosmo.angular_distance(self.z[i]) H_at_z = cosmo.Hubble(self.z[i]) * conts.c / 1000.0 #dv = pow(da * da * (1 + self.z[i]) * (1 + self.z[i]) * dr, 1. / 3.) rd = cosmo.rs_drag() * self.rs_rescale theo_DA_rdfid_by_rd_in_Mpc = DA_at_z / rd * self.rd_fid_in_Mpc[i] theo_H_rd_by_rdfid = H_at_z * rd / self.rd_fid_in_Mpc[i] chi2 += ((theo_DA_rdfid_by_rd_in_Mpc - self.DA_rdfid_by_rd_in_Mpc[i]) / self.DA_error[i]) ** 2 chi2 += ((theo_H_rd_by_rdfid - self.H_rd_by_rdfid_in_km_per_s_per_Mpc[i]) / self.H_error[i]) ** 2 # account for cross correlation chi2 -= 2 * self.cross_corr[i] \ * (theo_DA_rdfid_by_rd_in_Mpc - self.DA_rdfid_by_rd_in_Mpc[i]) \ * (theo_H_rd_by_rdfid - self.H_rd_by_rdfid_in_km_per_s_per_Mpc[i]) \ / self.DA_error[i] / self.H_error[i] # return ln(L) lkl = - 0.5 * chi2 return lkl
brinckmannREPO_NAMEmontepython_publicPATH_START.@montepython_public_extracted@montepython_public-master@montepython@likelihoods@bao_boss_aniso_gauss_approx@__init__.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "deepmind/optax", "repo_path": "optax_extracted/optax-main/optax/contrib/__init__.py", "type": "Python" }
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contributed optimizers in Optax.""" # pylint: disable=g-importing-member from optax.contrib._acprop import acprop from optax.contrib._acprop import scale_by_acprop from optax.contrib._cocob import cocob from optax.contrib._cocob import COCOBState from optax.contrib._cocob import scale_by_cocob from optax.contrib._complex_valued import split_real_and_imaginary from optax.contrib._complex_valued import SplitRealAndImaginaryState from optax.contrib._dadapt_adamw import dadapt_adamw from optax.contrib._dadapt_adamw import DAdaptAdamWState from optax.contrib._dog import dog from optax.contrib._dog import DoGState from optax.contrib._dog import dowg from optax.contrib._dog import DoWGState from optax.contrib._mechanic import MechanicState from optax.contrib._mechanic import mechanize from optax.contrib._momo import momo from optax.contrib._momo import momo_adam from optax.contrib._momo import MomoAdamState from optax.contrib._momo import MomoState from optax.contrib._privacy import differentially_private_aggregate from optax.contrib._privacy import DifferentiallyPrivateAggregateState from optax.contrib._privacy import dpsgd from optax.contrib._prodigy import prodigy from optax.contrib._prodigy import ProdigyState from optax.contrib._reduce_on_plateau import reduce_on_plateau from optax.contrib._reduce_on_plateau import ReduceLROnPlateauState from optax.contrib._sam import normalize from optax.contrib._sam import NormalizeState from optax.contrib._sam import sam from optax.contrib._sam import SAMState from optax.contrib._schedule_free import schedule_free from optax.contrib._schedule_free import schedule_free_adamw from optax.contrib._schedule_free import schedule_free_eval_params from optax.contrib._schedule_free import schedule_free_sgd from optax.contrib._schedule_free import ScheduleFreeState from optax.contrib._sophia import hutchinson_estimator_diag_hessian from optax.contrib._sophia import HutchinsonState from optax.contrib._sophia import sophia from optax.contrib._sophia import SophiaState
deepmindREPO_NAMEoptaxPATH_START.@optax_extracted@optax-main@optax@contrib@__init__.py@.PATH_END.py
{ "filename": "module.py", "repo_name": "guillochon/MOSFiT", "repo_path": "MOSFiT_extracted/MOSFiT-master/mosfit/modules/module.py", "type": "Python" }
"""Definitions for the ``Module`` class.""" import json from collections import OrderedDict import numpy as np from mosfit.printer import Printer class Module(object): """Base ``Module`` class.""" _REFERENCES = [] def __init__(self, name, model, **kwargs): """Initialize module. This is where expensive calculations that only need to be evaluated once should be located. """ self._name = name self._log = False self._model = model self._pool = model.pool() self._preprocessed = False self._wants_dense = False self._provide_dense = False self._replacements = OrderedDict() self._unset_recommended_keys = set() self._kinds_needed = set() if not model.printer(): self._printer = Printer() else: self._printer = model.printer() def __repr__(self): """Return a string representation of self.""" dict_copy = {} for key in self.__dict__.keys(): # Ignore associated classes. if key in ['_model', '_pool', '_printer']: continue if isinstance(self.__dict__[key], set): dict_copy[key] = list(self.__dict__[key]) else: dict_copy[key] = self.__dict__[key] return json.dumps(dict_copy) def process(self): """Process module, should always return a dictionary.""" return OrderedDict() def reset_preprocessed(self, exceptions): """Reset preprocessed flag.""" if self._name not in exceptions: self._preprocessed = False def send_request(self, request): """Send a request.""" return [] def name(self): """Return own name.""" return self._name def receive_requests(self, **requests): """Receive requests from other ``Module`` objects.""" def set_event_name(self, event_name): """Set the name of the event being modeled.""" self._event_name = event_name def set_attributes(self, task): """Set key replacement dictionary.""" self._replacements = task.get('replacements', OrderedDict()) if 'wants_dense' in task: self._wants_dense = task['wants_dense'] def get_bibcode(self): """Return any bibcodes associated with the present ``Module``.""" return [] def dense_key(self, key): """Manipulate output keys conditionally.""" new_key = self.key(key) if self._provide_dense and not key.startswith('dense_'): return 'dense_' + new_key return new_key def key(self, key): """Substitute user-defined replacement key names for local names.""" new_key = key for rep in self._replacements: if new_key == rep: new_key = self._replacements[rep] return new_key elif (new_key.startswith('dense') and new_key.split('_')[-1] == rep): new_key = 'dense_' + self._replacements[rep] return new_key return new_key def prepare_input(self, key, **kwargs): """Prepare keys conditionally.""" if key not in kwargs: if 'dense_' + key in kwargs: kwargs[key] = np.take( np.array(kwargs['dense_' + key]), np.array(kwargs['dense_indices'])) else: raise RuntimeError( 'Expecting `dense_` version of `{}` to exist before ' 'calling `{}` module.'.format(key, self._name)) return kwargs def reset_unset_recommended_keys(self): """Null the list of unset recommended keys.""" self._unset_recommended_keys = set() def get_unset_recommended_keys(self): """Return list of recommended keys that are not set.""" return self._unset_recommended_keys
guillochonREPO_NAMEMOSFiTPATH_START.@MOSFiT_extracted@MOSFiT-master@mosfit@modules@module.py@.PATH_END.py
{ "filename": "_align.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/splom/hoverlabel/_align.py", "type": "Python" }
import _plotly_utils.basevalidators class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="align", parent_name="splom.hoverlabel", **kwargs): super(AlignValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), values=kwargs.pop("values", ["left", "right", "auto"]), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@splom@hoverlabel@_align.py@.PATH_END.py
{ "filename": "_diffuse.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/isosurface/lighting/_diffuse.py", "type": "Python" }
import _plotly_utils.basevalidators class DiffuseValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="diffuse", parent_name="isosurface.lighting", **kwargs ): super(DiffuseValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), max=kwargs.pop("max", 1), min=kwargs.pop("min", 0), role=kwargs.pop("role", "style"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@isosurface@lighting@_diffuse.py@.PATH_END.py
{ "filename": "setup.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/scikit-learn/py2/sklearn/utils/setup.py", "type": "Python" }
import os from os.path import join from sklearn._build_utils import get_blas_info def configuration(parent_package='', top_path=None): import numpy from numpy.distutils.misc_util import Configuration config = Configuration('utils', parent_package, top_path) config.add_subpackage('sparsetools') cblas_libs, blas_info = get_blas_info() cblas_compile_args = blas_info.pop('extra_compile_args', []) cblas_includes = [join('..', 'src', 'cblas'), numpy.get_include(), blas_info.pop('include_dirs', [])] libraries = [] if os.name == 'posix': libraries.append('m') cblas_libs.append('m') config.add_extension('sparsefuncs_fast', sources=['sparsefuncs_fast.pyx'], libraries=libraries) config.add_extension('arrayfuncs', sources=['arrayfuncs.pyx'], depends=[join('src', 'cholesky_delete.h')], libraries=cblas_libs, include_dirs=cblas_includes, extra_compile_args=cblas_compile_args, **blas_info ) config.add_extension('murmurhash', sources=['murmurhash.pyx', join( 'src', 'MurmurHash3.cpp')], include_dirs=['src']) config.add_extension('lgamma', sources=['lgamma.pyx', join('src', 'gamma.c')], include_dirs=['src'], libraries=libraries) config.add_extension('graph_shortest_path', sources=['graph_shortest_path.pyx'], include_dirs=[numpy.get_include()]) config.add_extension('fast_dict', sources=['fast_dict.pyx'], language="c++", include_dirs=[numpy.get_include()], libraries=libraries) config.add_extension('seq_dataset', sources=['seq_dataset.pyx'], include_dirs=[numpy.get_include()]) config.add_extension('weight_vector', sources=['weight_vector.pyx'], include_dirs=cblas_includes, libraries=cblas_libs, **blas_info) config.add_extension("_random", sources=["_random.pyx"], include_dirs=[numpy.get_include()], libraries=libraries) config.add_extension("_logistic_sigmoid", sources=["_logistic_sigmoid.pyx"], include_dirs=[numpy.get_include()], libraries=libraries) config.add_subpackage('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@scikit-learn@py2@sklearn@utils@setup.py@.PATH_END.py
{ "filename": "_lineposition.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/streamtube/hoverlabel/font/_lineposition.py", "type": "Python" }
import _plotly_utils.basevalidators class LinepositionValidator(_plotly_utils.basevalidators.FlaglistValidator): def __init__( self, plotly_name="lineposition", parent_name="streamtube.hoverlabel.font", **kwargs, ): super(LinepositionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), extras=kwargs.pop("extras", ["none"]), flags=kwargs.pop("flags", ["under", "over", "through"]), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@streamtube@hoverlabel@font@_lineposition.py@.PATH_END.py
{ "filename": "sis_truncate.py", "repo_name": "lenstronomy/lenstronomy", "repo_path": "lenstronomy_extracted/lenstronomy-main/lenstronomy/LensModel/Profiles/sis_truncate.py", "type": "Python" }
__author__ = "sibirrer" import numpy as np from lenstronomy.LensModel.Profiles.base_profile import LensProfileBase __all__ = ["SIS_truncate"] class SIS_truncate(LensProfileBase): """This class contains the function and the derivatives of the Singular Isothermal Sphere.""" param_names = ["theta_E", "r_trunc", "center_x", "center_y"] lower_limit_default = { "theta_E": 0, "r_trunc": 0, "center_x": -100, "center_y": -100, } upper_limit_default = { "theta_E": 100, "r_trunc": 100, "center_x": 100, "center_y": 100, } def function(self, x, y, theta_E, r_trunc, center_x=0, center_y=0): x_shift = x - center_x y_shift = y - center_y r = np.sqrt(x_shift * x_shift + y_shift * y_shift) if isinstance(r, int) or isinstance(r, float): if r < r_trunc: f_ = theta_E * r elif r < 2 * r_trunc: f_ = theta_E * r_trunc + 1.0 / 2 * theta_E * (3 - r / r_trunc) * ( r - r_trunc ) else: f_ = 3.0 / 2 * theta_E * r_trunc else: f_ = np.zeros_like(r) f_[r < r_trunc] = theta_E * r[r < r_trunc] r_ = r[(r < 2 * r_trunc) & (r > r_trunc)] f_[(r < 2 * r_trunc) & (r > r_trunc)] = ( theta_E * r_trunc + 1.0 / 2 * theta_E * (3 - r_ / r_trunc) * (r_ - r_trunc) ) f_[r > 2 * r_trunc] = 3.0 / 2 * theta_E * r_trunc return f_ def derivatives(self, x, y, theta_E, r_trunc, center_x=0, center_y=0): """Returns df/dx and df/dy of the function.""" x_shift = x - center_x y_shift = y - center_y dphi_dr = self._dphi_dr(x_shift, y_shift, theta_E, r_trunc) dr_dx, dr_dy = self._dr_dx(x_shift, y_shift) f_x = dphi_dr * dr_dx f_y = dphi_dr * dr_dy return f_x, f_y def hessian(self, x, y, theta_E, r_trunc, center_x=0, center_y=0): """Returns Hessian matrix of function d^2f/dx^2, d^2/dxdy, d^2/dydx, d^f/dy^2.""" x_shift = x - center_x y_shift = y - center_y dphi_dr = self._dphi_dr(x_shift, y_shift, theta_E, r_trunc) d2phi_dr2 = self._d2phi_dr2(x_shift, y_shift, theta_E, r_trunc) dr_dx, dr_dy = self._dr_dx(x, y) d2r_dx2, d2r_dy2, d2r_dxy = self._d2r_dx2(x_shift, y_shift) f_xx = d2r_dx2 * dphi_dr + dr_dx**2 * d2phi_dr2 f_yy = d2r_dy2 * dphi_dr + dr_dy**2 * d2phi_dr2 f_xy = d2r_dxy * dphi_dr + dr_dx * dr_dy * d2phi_dr2 return f_xx, f_xy, f_xy, f_yy def _dphi_dr(self, x, y, theta_E, r_trunc): """ :param x: :param y: :param r_trunc: :return: """ r = np.sqrt(x * x + y * y) if isinstance(r, int) or isinstance(r, float): if r == 0: a = 0 elif r < r_trunc: a = theta_E elif r < 2 * r_trunc: a = theta_E * (2 - r / r_trunc) else: a = 0 else: a = np.zeros_like(r) a[(r < r_trunc) & (r > 0)] = theta_E r_ = r[(r < 2 * r_trunc) & (r >= r_trunc)] a[(r < 2 * r_trunc) & (r >= r_trunc)] = theta_E * (2 - r_ / r_trunc) a[r >= 2 * r_trunc] = 0 return a def _d2phi_dr2(self, x, y, theta_E, r_trunc): """Second derivative of the potential in radial direction :param x: :param y: :param theta_E: :param r_trunc: :return: """ r = np.sqrt(x * x + y * y) if isinstance(r, int) or isinstance(r, float): if r < r_trunc: a = 0 elif r < 2 * r_trunc: a = -theta_E / r_trunc else: a = 0 else: a = np.zeros_like(r) a[r < r_trunc] = 0 a[(r < 2 * r_trunc) & (r > r_trunc)] = -theta_E / r_trunc a[r > 2 * r_trunc] = 0 return a def _dr_dx(self, x, y): """Derivative of dr/dx, dr/dy :param x: :param y: :return: """ r = np.sqrt(x**2 + y**2) if isinstance(r, int) or isinstance(r, float): if r == 0: r = 1 else: r[r == 0] = 1 return x / r, y / r @staticmethod def _d2r_dx2(x, y): """Second derivative :param x: :param y: :return: """ r = np.sqrt(x**2 + y**2) if isinstance(r, int) or isinstance(r, float): if r == 0: r = 1 else: r[r == 0] = 1 return y**2 / r**3, x**2 / r**3, -x * y / r**3
lenstronomyREPO_NAMElenstronomyPATH_START.@lenstronomy_extracted@lenstronomy-main@lenstronomy@LensModel@Profiles@sis_truncate.py@.PATH_END.py
{ "filename": "cartesian.py", "repo_name": "desihub/LSS", "repo_path": "LSS_extracted/LSS-main/py/LSS/DESI_ke/cartesian.py", "type": "Python" }
import numpy as np from cosmo import cosmo from scipy.spatial.transform import Rotation as R def rotate(ras, decs, pos): phi = np.radians(ras) theta = np.pi/2. - np.radians(decs) mean_phi = np.median(phi) mean_theta = np.median(theta) rot = R.from_rotvec(-mean_phi * np.array([0, 0, 1])) res = rot.apply(pos) rot = R.from_rotvec((np.pi/2. - mean_theta) * np.array([0, 1, 0])) resres = rot.apply(res) return resres def cartesian(ras, decs, zs, rotate=False): phi = np.radians(ras) theta = np.pi/2. - np.radians(decs) mean_phi = np.median(phi) mean_theta = np.median(theta) chis = cosmo.comoving_distance(zs).value # [Mpc/h]. zs = chis * np.cos(theta) ys = chis * np.sin(theta) * np.sin(phi) xs = chis * np.sin(theta) * np.cos(phi) pos = np.c_[xs, ys, zs] if rotate: pos = rotate(ras, decs, pos) return pos if __name__ == '__main__': ras = np.random.uniform(10., 20., 100) decs = np.random.uniform(2., 3., 100) zs = np.random.uniform(2., 2.4, 100) pos = cartesian(ras, decs, zs) print(pos)
desihubREPO_NAMELSSPATH_START.@LSS_extracted@LSS-main@py@LSS@DESI_ke@cartesian.py@.PATH_END.py
{ "filename": "base.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/chains/pebblo_retrieval/base.py", "type": "Python" }
""" Pebblo Retrieval Chain with Identity & Semantic Enforcement for question-answering against a vector database. """ import datetime import inspect import logging from importlib.metadata import version from typing import Any, Dict, List, Optional from langchain.chains.base import Chain from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain_core.callbacks import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain_core.documents import Document from langchain_core.language_models import BaseLanguageModel from langchain_core.vectorstores import VectorStoreRetriever from pydantic import ConfigDict, Field, validator from langchain_community.chains.pebblo_retrieval.enforcement_filters import ( SUPPORTED_VECTORSTORES, set_enforcement_filters, ) from langchain_community.chains.pebblo_retrieval.models import ( App, AuthContext, ChainInfo, Framework, Model, SemanticContext, VectorDB, ) from langchain_community.chains.pebblo_retrieval.utilities import ( PLUGIN_VERSION, PebbloRetrievalAPIWrapper, get_runtime, ) logger = logging.getLogger(__name__) class PebbloRetrievalQA(Chain): """ Retrieval Chain with Identity & Semantic Enforcement for question-answering against a vector database. """ combine_documents_chain: BaseCombineDocumentsChain """Chain to use to combine the documents.""" input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: return_source_documents: bool = False """Return the source documents or not.""" retriever: VectorStoreRetriever = Field(exclude=True) """VectorStore to use for retrieval.""" auth_context_key: str = "auth_context" #: :meta private: """Authentication context for identity enforcement.""" semantic_context_key: str = "semantic_context" #: :meta private: """Semantic context for semantic enforcement.""" app_name: str #: :meta private: """App name.""" owner: str #: :meta private: """Owner of app.""" description: str #: :meta private: """Description of app.""" api_key: Optional[str] = None #: :meta private: """Pebblo cloud API key for app.""" classifier_url: Optional[str] = None #: :meta private: """Classifier endpoint.""" classifier_location: str = "local" #: :meta private: """Classifier location. It could be either of 'local' or 'pebblo-cloud'.""" _discover_sent: bool = False #: :meta private: """Flag to check if discover payload has been sent.""" enable_prompt_gov: bool = True #: :meta private: """Flag to check if prompt governance is enabled or not""" pb_client: PebbloRetrievalAPIWrapper = Field( default_factory=PebbloRetrievalAPIWrapper ) """Pebblo Retrieval API client""" def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Run get_relevant_text and llm on input query. If chain has 'return_source_documents' as 'True', returns the retrieved documents as well under the key 'source_documents'. Example: .. code-block:: python res = indexqa({'query': 'This is my query'}) answer, docs = res['result'], res['source_documents'] """ prompt_time = datetime.datetime.now().isoformat() _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() question = inputs[self.input_key] auth_context = inputs.get(self.auth_context_key) semantic_context = inputs.get(self.semantic_context_key) _, prompt_entities = self.pb_client.check_prompt_validity(question) accepts_run_manager = ( "run_manager" in inspect.signature(self._get_docs).parameters ) if accepts_run_manager: docs = self._get_docs( question, auth_context, semantic_context, run_manager=_run_manager ) else: docs = self._get_docs(question, auth_context, semantic_context) # type: ignore[call-arg] answer = self.combine_documents_chain.run( input_documents=docs, question=question, callbacks=_run_manager.get_child() ) self.pb_client.send_prompt( self.app_name, self.retriever, question, answer, auth_context, docs, prompt_entities, prompt_time, self.enable_prompt_gov, ) if self.return_source_documents: return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Run get_relevant_text and llm on input query. If chain has 'return_source_documents' as 'True', returns the retrieved documents as well under the key 'source_documents'. Example: .. code-block:: python res = indexqa({'query': 'This is my query'}) answer, docs = res['result'], res['source_documents'] """ prompt_time = datetime.datetime.now().isoformat() _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() question = inputs[self.input_key] auth_context = inputs.get(self.auth_context_key) semantic_context = inputs.get(self.semantic_context_key) accepts_run_manager = ( "run_manager" in inspect.signature(self._aget_docs).parameters ) _, prompt_entities = await self.pb_client.acheck_prompt_validity(question) if accepts_run_manager: docs = await self._aget_docs( question, auth_context, semantic_context, run_manager=_run_manager ) else: docs = await self._aget_docs(question, auth_context, semantic_context) # type: ignore[call-arg] answer = await self.combine_documents_chain.arun( input_documents=docs, question=question, callbacks=_run_manager.get_child() ) await self.pb_client.asend_prompt( self.app_name, self.retriever, question, answer, auth_context, docs, prompt_entities, prompt_time, self.enable_prompt_gov, ) if self.return_source_documents: return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} model_config = ConfigDict( populate_by_name=True, arbitrary_types_allowed=True, extra="forbid", ) @property def input_keys(self) -> List[str]: """Input keys. :meta private: """ return [self.input_key, self.auth_context_key, self.semantic_context_key] @property def output_keys(self) -> List[str]: """Output keys. :meta private: """ _output_keys = [self.output_key] if self.return_source_documents: _output_keys += ["source_documents"] return _output_keys @property def _chain_type(self) -> str: """Return the chain type.""" return "pebblo_retrieval_qa" @classmethod def from_chain_type( cls, llm: BaseLanguageModel, app_name: str, description: str, owner: str, chain_type: str = "stuff", chain_type_kwargs: Optional[dict] = None, api_key: Optional[str] = None, classifier_url: Optional[str] = None, classifier_location: str = "local", **kwargs: Any, ) -> "PebbloRetrievalQA": """Load chain from chain type.""" from langchain.chains.question_answering import load_qa_chain _chain_type_kwargs = chain_type_kwargs or {} combine_documents_chain = load_qa_chain( llm, chain_type=chain_type, **_chain_type_kwargs ) # generate app app: App = PebbloRetrievalQA._get_app_details( app_name=app_name, description=description, owner=owner, llm=llm, **kwargs, ) # initialize Pebblo API client pb_client = PebbloRetrievalAPIWrapper( api_key=api_key, classifier_location=classifier_location, classifier_url=classifier_url, ) # send app discovery request pb_client.send_app_discover(app) return cls( combine_documents_chain=combine_documents_chain, app_name=app_name, owner=owner, description=description, api_key=api_key, classifier_url=classifier_url, classifier_location=classifier_location, pb_client=pb_client, **kwargs, ) @validator("retriever", pre=True, always=True) def validate_vectorstore( cls, retriever: VectorStoreRetriever ) -> VectorStoreRetriever: """ Validate that the vectorstore of the retriever is supported vectorstores. """ if retriever.vectorstore.__class__.__name__ not in SUPPORTED_VECTORSTORES: raise ValueError( f"Vectorstore must be an instance of one of the supported " f"vectorstores: {SUPPORTED_VECTORSTORES}. " f"Got '{retriever.vectorstore.__class__.__name__}' instead." ) return retriever def _get_docs( self, question: str, auth_context: Optional[AuthContext], semantic_context: Optional[SemanticContext], *, run_manager: CallbackManagerForChainRun, ) -> List[Document]: """Get docs.""" set_enforcement_filters(self.retriever, auth_context, semantic_context) return self.retriever.get_relevant_documents( question, callbacks=run_manager.get_child() ) async def _aget_docs( self, question: str, auth_context: Optional[AuthContext], semantic_context: Optional[SemanticContext], *, run_manager: AsyncCallbackManagerForChainRun, ) -> List[Document]: """Get docs.""" set_enforcement_filters(self.retriever, auth_context, semantic_context) return await self.retriever.aget_relevant_documents( question, callbacks=run_manager.get_child() ) @staticmethod def _get_app_details( # type: ignore app_name: str, owner: str, description: str, llm: BaseLanguageModel, **kwargs ) -> App: """Fetch app details. Internal method. Returns: App: App details. """ framework, runtime = get_runtime() chains = PebbloRetrievalQA.get_chain_details(llm, **kwargs) app = App( name=app_name, owner=owner, description=description, runtime=runtime, framework=framework, chains=chains, plugin_version=PLUGIN_VERSION, client_version=Framework( name="langchain_community", version=version("langchain_community"), ), ) return app @classmethod def set_discover_sent(cls) -> None: cls._discover_sent = True @classmethod def get_chain_details( cls, llm: BaseLanguageModel, **kwargs: Any ) -> List[ChainInfo]: """ Get chain details. Args: llm (BaseLanguageModel): Language model instance. **kwargs: Additional keyword arguments. Returns: List[ChainInfo]: Chain details. """ llm_dict = llm.__dict__ chains = [ ChainInfo( name=cls.__name__, model=Model( name=llm_dict.get("model_name", llm_dict.get("model")), vendor=llm.__class__.__name__, ), vector_dbs=[ VectorDB( name=kwargs["retriever"].vectorstore.__class__.__name__, embedding_model=str( kwargs["retriever"].vectorstore._embeddings.model ) if hasattr(kwargs["retriever"].vectorstore, "_embeddings") else ( str(kwargs["retriever"].vectorstore._embedding.model) if hasattr(kwargs["retriever"].vectorstore, "_embedding") else None ), ) ], ), ] return chains
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@chains@pebblo_retrieval@base.py@.PATH_END.py
{ "filename": "test_variablepsf.py", "repo_name": "quatrope/ProperImage", "repo_path": "ProperImage_extracted/ProperImage-master/drafts/test_variablepsf.py", "type": "Python" }
#!/usr/bin/env python # -*- coding: utf-8 -*- # # test_recoverstats.py # # Copyright 2016 Bruno S <bruno.sanchez.63@gmail.com> # import os import shlex import subprocess import sys import numpy as np import matplotlib.pyplot as plt from properimage import simtools from properimage import propercoadd as pc from properimage import single_image as si from properimage import utils from properimage import plot # ============================================================================= # PSF measure test by propercoadd # ============================================================================= frames = [] for theta in [0, 45, 105, 150]: N = 512 # side X_FWHM = 5 + 2.5*theta/180 Y_FWHM = 5 t_exp = 1 max_fw = max(X_FWHM, Y_FWHM) test_dir = os.path.abspath('./test/test_images/psf_basis_kl_gs') x = np.random.randint(low=6*max_fw, high=N-6*max_fw, size=80) y = np.random.randint(low=6*max_fw, high=N-6*max_fw, size=80) xy = [(x[i], y[i]) for i in range(80)] SN = 5. # SN para poder medir psf weights = list(np.linspace(10, 1000., len(xy))) m = simtools.delta_point(N, center=False, xy=xy, weights=weights) im = simtools.image(m, N, t_exp, X_FWHM, Y_FWHM=Y_FWHM, theta=theta, SN=SN, bkg_pdf='poisson') frames.append(im+100.) frame = np.zeros((1024, 1024)) for j in range(2): for i in range(2): frame[i*512:(i+1)*512, j*512:(j+1)*512] = frames[i+2*j] with si.SingleImage(frame) as sim: a_fields, psf_basis = sim.get_variable_psf(inf_loss=0.025) x, y = sim.get_afield_domain() plt.imshow(np.log(frame), interpolation='none') plt.colorbar() plt.savefig(os.path.join(test_dir, 'test_frame.png')) plt.close() plot.plot_psfbasis(psf_basis, path=os.path.join(test_dir, 'psf_basis.png')) plot.plot_afields(a_fields, x, y, path=os.path.join(test_dir, 'a_fields.png'))
quatropeREPO_NAMEProperImagePATH_START.@ProperImage_extracted@ProperImage-master@drafts@test_variablepsf.py@.PATH_END.py
{ "filename": "test_repeat.py", "repo_name": "pandas-dev/pandas", "repo_path": "pandas_extracted/pandas-main/pandas/tests/indexes/datetimes/methods/test_repeat.py", "type": "Python" }
import numpy as np import pytest from pandas import ( DatetimeIndex, Timestamp, date_range, ) import pandas._testing as tm class TestRepeat: def test_repeat_range(self, tz_naive_fixture): rng = date_range("1/1/2000", "1/1/2001") result = rng.repeat(5) assert result.freq is None assert len(result) == 5 * len(rng) def test_repeat_range2(self, tz_naive_fixture, unit): tz = tz_naive_fixture index = date_range("2001-01-01", periods=2, freq="D", tz=tz, unit=unit) exp = DatetimeIndex( ["2001-01-01", "2001-01-01", "2001-01-02", "2001-01-02"], tz=tz ).as_unit(unit) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) assert res.freq is None def test_repeat_range3(self, tz_naive_fixture, unit): tz = tz_naive_fixture index = date_range("2001-01-01", periods=2, freq="2D", tz=tz, unit=unit) exp = DatetimeIndex( ["2001-01-01", "2001-01-01", "2001-01-03", "2001-01-03"], tz=tz ).as_unit(unit) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) assert res.freq is None def test_repeat_range4(self, tz_naive_fixture, unit): tz = tz_naive_fixture index = DatetimeIndex(["2001-01-01", "NaT", "2003-01-01"], tz=tz).as_unit(unit) exp = DatetimeIndex( [ "2001-01-01", "2001-01-01", "2001-01-01", "NaT", "NaT", "NaT", "2003-01-01", "2003-01-01", "2003-01-01", ], tz=tz, ).as_unit(unit) for res in [index.repeat(3), np.repeat(index, 3)]: tm.assert_index_equal(res, exp) assert res.freq is None def test_repeat(self, tz_naive_fixture, unit): tz = tz_naive_fixture reps = 2 msg = "the 'axis' parameter is not supported" rng = date_range(start="2016-01-01", periods=2, freq="30Min", tz=tz, unit=unit) expected_rng = DatetimeIndex( [ Timestamp("2016-01-01 00:00:00", tz=tz), Timestamp("2016-01-01 00:00:00", tz=tz), Timestamp("2016-01-01 00:30:00", tz=tz), Timestamp("2016-01-01 00:30:00", tz=tz), ] ).as_unit(unit) res = rng.repeat(reps) tm.assert_index_equal(res, expected_rng) assert res.freq is None tm.assert_index_equal(np.repeat(rng, reps), expected_rng) with pytest.raises(ValueError, match=msg): np.repeat(rng, reps, axis=1)
pandas-devREPO_NAMEpandasPATH_START.@pandas_extracted@pandas-main@pandas@tests@indexes@datetimes@methods@test_repeat.py@.PATH_END.py
{ "filename": "dist.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/setuptools/py3/setuptools/_distutils/dist.py", "type": "Python" }
"""distutils.dist Provides the Distribution class, which represents the module distribution being built/installed/distributed. """ import contextlib import logging import os import pathlib import re import sys from collections.abc import Iterable from email import message_from_file from ._vendor.packaging.utils import canonicalize_name, canonicalize_version try: import warnings except ImportError: warnings = None from ._log import log from .debug import DEBUG from .errors import ( DistutilsArgError, DistutilsClassError, DistutilsModuleError, DistutilsOptionError, ) from .fancy_getopt import FancyGetopt, translate_longopt from .util import check_environ, rfc822_escape, strtobool # Regex to define acceptable Distutils command names. This is not *quite* # the same as a Python NAME -- I don't allow leading underscores. The fact # that they're very similar is no coincidence; the default naming scheme is # to look for a Python module named after the command. command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$') def _ensure_list(value, fieldname): if isinstance(value, str): # a string containing comma separated values is okay. It will # be converted to a list by Distribution.finalize_options(). pass elif not isinstance(value, list): # passing a tuple or an iterator perhaps, warn and convert typename = type(value).__name__ msg = "Warning: '{fieldname}' should be a list, got type '{typename}'" msg = msg.format(**locals()) log.warning(msg) value = list(value) return value class Distribution: """The core of the Distutils. Most of the work hiding behind 'setup' is really done within a Distribution instance, which farms the work out to the Distutils commands specified on the command line. Setup scripts will almost never instantiate Distribution directly, unless the 'setup()' function is totally inadequate to their needs. However, it is conceivable that a setup script might wish to subclass Distribution for some specialized purpose, and then pass the subclass to 'setup()' as the 'distclass' keyword argument. If so, it is necessary to respect the expectations that 'setup' has of Distribution. See the code for 'setup()', in core.py, for details. """ # 'global_options' describes the command-line options that may be # supplied to the setup script prior to any actual commands. # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of # these global options. This list should be kept to a bare minimum, # since every global option is also valid as a command option -- and we # don't want to pollute the commands with too many options that they # have minimal control over. # The fourth entry for verbose means that it can be repeated. global_options = [ ('verbose', 'v', "run verbosely (default)", 1), ('quiet', 'q', "run quietly (turns verbosity off)"), ('dry-run', 'n', "don't actually do anything"), ('help', 'h', "show detailed help message"), ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'), ] # 'common_usage' is a short (2-3 line) string describing the common # usage of the setup script. common_usage = """\ Common commands: (see '--help-commands' for more) setup.py build will build the package underneath 'build/' setup.py install will install the package """ # options that are not propagated to the commands display_options = [ ('help-commands', None, "list all available commands"), ('name', None, "print package name"), ('version', 'V', "print package version"), ('fullname', None, "print <package name>-<version>"), ('author', None, "print the author's name"), ('author-email', None, "print the author's email address"), ('maintainer', None, "print the maintainer's name"), ('maintainer-email', None, "print the maintainer's email address"), ('contact', None, "print the maintainer's name if known, else the author's"), ( 'contact-email', None, "print the maintainer's email address if known, else the author's", ), ('url', None, "print the URL for this package"), ('license', None, "print the license of the package"), ('licence', None, "alias for --license"), ('description', None, "print the package description"), ('long-description', None, "print the long package description"), ('platforms', None, "print the list of platforms"), ('classifiers', None, "print the list of classifiers"), ('keywords', None, "print the list of keywords"), ('provides', None, "print the list of packages/modules provided"), ('requires', None, "print the list of packages/modules required"), ('obsoletes', None, "print the list of packages/modules made obsolete"), ] display_option_names = [translate_longopt(x[0]) for x in display_options] # negative options are options that exclude other options negative_opt = {'quiet': 'verbose'} # -- Creation/initialization methods ------------------------------- def __init__(self, attrs=None): # noqa: C901 """Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'. """ # Default values for our command-line options self.verbose = True self.dry_run = False self.help = False for attr in self.display_option_names: setattr(self, attr, 0) # Store the distribution meta-data (name, version, author, and so # forth) in a separate object -- we're getting to have enough # information here (and enough command-line options) that it's # worth it. Also delegate 'get_XXX()' methods to the 'metadata' # object in a sneaky and underhanded (but efficient!) way. self.metadata = DistributionMetadata() for basename in self.metadata._METHOD_BASENAMES: method_name = "get_" + basename setattr(self, method_name, getattr(self.metadata, method_name)) # 'cmdclass' maps command names to class objects, so we # can 1) quickly figure out which class to instantiate when # we need to create a new command object, and 2) have a way # for the setup script to override command classes self.cmdclass = {} # 'command_packages' is a list of packages in which commands # are searched for. The factory for command 'foo' is expected # to be named 'foo' in the module 'foo' in one of the packages # named here. This list is searched from the left; an error # is raised if no named package provides the command being # searched for. (Always access using get_command_packages().) self.command_packages = None # 'script_name' and 'script_args' are usually set to sys.argv[0] # and sys.argv[1:], but they can be overridden when the caller is # not necessarily a setup script run from the command-line. self.script_name = None self.script_args = None # 'command_options' is where we store command options between # parsing them (from config files, the command-line, etc.) and when # they are actually needed -- ie. when the command in question is # instantiated. It is a dictionary of dictionaries of 2-tuples: # command_options = { command_name : { option : (source, value) } } self.command_options = {} # 'dist_files' is the list of (command, pyversion, file) that # have been created by any dist commands run so far. This is # filled regardless of whether the run is dry or not. pyversion # gives sysconfig.get_python_version() if the dist file is # specific to a Python version, 'any' if it is good for all # Python versions on the target platform, and '' for a source # file. pyversion should not be used to specify minimum or # maximum required Python versions; use the metainfo for that # instead. self.dist_files = [] # These options are really the business of various commands, rather # than of the Distribution itself. We provide aliases for them in # Distribution as a convenience to the developer. self.packages = None self.package_data = {} self.package_dir = None self.py_modules = None self.libraries = None self.headers = None self.ext_modules = None self.ext_package = None self.include_dirs = None self.extra_path = None self.scripts = None self.data_files = None self.password = '' # And now initialize bookkeeping stuff that can't be supplied by # the caller at all. 'command_obj' maps command names to # Command instances -- that's how we enforce that every command # class is a singleton. self.command_obj = {} # 'have_run' maps command names to boolean values; it keeps track # of whether we have actually run a particular command, to make it # cheap to "run" a command whenever we think we might need to -- if # it's already been done, no need for expensive filesystem # operations, we just check the 'have_run' dictionary and carry on. # It's only safe to query 'have_run' for a command class that has # been instantiated -- a false value will be inserted when the # command object is created, and replaced with a true value when # the command is successfully run. Thus it's probably best to use # '.get()' rather than a straight lookup. self.have_run = {} # Now we'll use the attrs dictionary (ultimately, keyword args from # the setup script) to possibly override any or all of these # distribution options. if attrs: # Pull out the set of command options and work on them # specifically. Note that this order guarantees that aliased # command options will override any supplied redundantly # through the general options dictionary. options = attrs.get('options') if options is not None: del attrs['options'] for command, cmd_options in options.items(): opt_dict = self.get_option_dict(command) for opt, val in cmd_options.items(): opt_dict[opt] = ("setup script", val) if 'licence' in attrs: attrs['license'] = attrs['licence'] del attrs['licence'] msg = "'licence' distribution option is deprecated; use 'license'" if warnings is not None: warnings.warn(msg) else: sys.stderr.write(msg + "\n") # Now work on the rest of the attributes. Any attribute that's # not already defined is invalid! for key, val in attrs.items(): if hasattr(self.metadata, "set_" + key): getattr(self.metadata, "set_" + key)(val) elif hasattr(self.metadata, key): setattr(self.metadata, key, val) elif hasattr(self, key): setattr(self, key, val) else: msg = f"Unknown distribution option: {key!r}" warnings.warn(msg) # no-user-cfg is handled before other command line args # because other args override the config files, and this # one is needed before we can load the config files. # If attrs['script_args'] wasn't passed, assume false. # # This also make sure we just look at the global options self.want_user_cfg = True if self.script_args is not None: for arg in self.script_args: if not arg.startswith('-'): break if arg == '--no-user-cfg': self.want_user_cfg = False break self.finalize_options() def get_option_dict(self, command): """Get the option dictionary for a given command. If that command's option dictionary hasn't been created yet, then create it and return the new dictionary; otherwise, return the existing option dictionary. """ dict = self.command_options.get(command) if dict is None: dict = self.command_options[command] = {} return dict def dump_option_dicts(self, header=None, commands=None, indent=""): from pprint import pformat if commands is None: # dump all command option dicts commands = sorted(self.command_options.keys()) if header is not None: self.announce(indent + header) indent = indent + " " if not commands: self.announce(indent + "no commands known yet") return for cmd_name in commands: opt_dict = self.command_options.get(cmd_name) if opt_dict is None: self.announce(indent + f"no option dict for '{cmd_name}' command") else: self.announce(indent + f"option dict for '{cmd_name}' command:") out = pformat(opt_dict) for line in out.split('\n'): self.announce(indent + " " + line) # -- Config file finding/parsing methods --------------------------- def find_config_files(self): """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions). There are multiple possible config files: - distutils.cfg in the Distutils installation directory (i.e. where the top-level Distutils __inst__.py file lives) - a file in the user's home directory named .pydistutils.cfg on Unix and pydistutils.cfg on Windows/Mac; may be disabled with the ``--no-user-cfg`` option - setup.cfg in the current directory - a file named by an environment variable """ check_environ() files = [str(path) for path in self._gen_paths() if os.path.isfile(path)] if DEBUG: self.announce("using config files: {}".format(', '.join(files))) return files def _gen_paths(self): # The system-wide Distutils config file sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent yield sys_dir / "distutils.cfg" # The per-user config file prefix = '.' * (os.name == 'posix') filename = prefix + 'pydistutils.cfg' if self.want_user_cfg: yield pathlib.Path('~').expanduser() / filename # All platforms support local setup.cfg yield pathlib.Path('setup.cfg') # Additional config indicated in the environment with contextlib.suppress(TypeError): yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG")) def parse_config_files(self, filenames=None): # noqa: C901 from configparser import ConfigParser # Ignore install directory options if we have a venv if sys.prefix != sys.base_prefix: ignore_options = [ 'install-base', 'install-platbase', 'install-lib', 'install-platlib', 'install-purelib', 'install-headers', 'install-scripts', 'install-data', 'prefix', 'exec-prefix', 'home', 'user', 'root', ] else: ignore_options = [] ignore_options = frozenset(ignore_options) if filenames is None: filenames = self.find_config_files() if DEBUG: self.announce("Distribution.parse_config_files():") parser = ConfigParser() for filename in filenames: if DEBUG: self.announce(f" reading {filename}") parser.read(filename, encoding='utf-8') for section in parser.sections(): options = parser.options(section) opt_dict = self.get_option_dict(section) for opt in options: if opt != '__name__' and opt not in ignore_options: val = parser.get(section, opt) opt = opt.replace('-', '_') opt_dict[opt] = (filename, val) # Make the ConfigParser forget everything (so we retain # the original filenames that options come from) parser.__init__() # If there was a "global" section in the config file, use it # to set Distribution options. if 'global' in self.command_options: for opt, (_src, val) in self.command_options['global'].items(): alias = self.negative_opt.get(opt) try: if alias: setattr(self, alias, not strtobool(val)) elif opt in ('verbose', 'dry_run'): # ugh! setattr(self, opt, strtobool(val)) else: setattr(self, opt, val) except ValueError as msg: raise DistutilsOptionError(msg) # -- Command-line parsing methods ---------------------------------- def parse_command_line(self): """Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' -- see 'setup()' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the 'user_options' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that 'options' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line was successfully parsed and we should carry on with executing commands; false if no errors but we shouldn't execute commands (currently, this only happens if user asks for help). """ # # We now have enough information to show the Macintosh dialog # that allows the user to interactively specify the "command line". # toplevel_options = self._get_toplevel_options() # We have to parse the command line a bit at a time -- global # options, then the first command, then its options, and so on -- # because each command will be handled by a different class, and # the options that are valid for a particular class aren't known # until we have loaded the command class, which doesn't happen # until we know what the command is. self.commands = [] parser = FancyGetopt(toplevel_options + self.display_options) parser.set_negative_aliases(self.negative_opt) parser.set_aliases({'licence': 'license'}) args = parser.getopt(args=self.script_args, object=self) option_order = parser.get_option_order() logging.getLogger().setLevel(logging.WARN - 10 * self.verbose) # for display options we return immediately if self.handle_display_options(option_order): return while args: args = self._parse_command_opts(parser, args) if args is None: # user asked for help (and got it) return # Handle the cases of --help as a "global" option, ie. # "setup.py --help" and "setup.py --help command ...". For the # former, we show global options (--verbose, --dry-run, etc.) # and display-only options (--name, --version, etc.); for the # latter, we omit the display-only options and show help for # each command listed on the command line. if self.help: self._show_help( parser, display_options=len(self.commands) == 0, commands=self.commands ) return # Oops, no commands found -- an end-user error if not self.commands: raise DistutilsArgError("no commands supplied") # All is well: return true return True def _get_toplevel_options(self): """Return the non-display options recognized at the top level. This includes options that are recognized *only* at the top level as well as options recognized for commands. """ return self.global_options + [ ( "command-packages=", None, "list of packages that provide distutils commands", ), ] def _parse_command_opts(self, parser, args): # noqa: C901 """Parse the command-line options for a single command. 'parser' must be a FancyGetopt instance; 'args' must be the list of arguments, starting with the current command (whose options we are about to parse). Returns a new version of 'args' with the next command at the front of the list; will be the empty list if there are no more commands on the command line. Returns None if the user asked for help on this command. """ # late import because of mutual dependence between these modules from distutils.cmd import Command # Pull the current command from the head of the command line command = args[0] if not command_re.match(command): raise SystemExit(f"invalid command name '{command}'") self.commands.append(command) # Dig up the command class that implements this command, so we # 1) know that it's a valid command, and 2) know which options # it takes. try: cmd_class = self.get_command_class(command) except DistutilsModuleError as msg: raise DistutilsArgError(msg) # Require that the command class be derived from Command -- want # to be sure that the basic "command" interface is implemented. if not issubclass(cmd_class, Command): raise DistutilsClassError( f"command class {cmd_class} must subclass Command" ) # Also make sure that the command object provides a list of its # known options. if not ( hasattr(cmd_class, 'user_options') and isinstance(cmd_class.user_options, list) ): msg = ( "command class %s must provide " "'user_options' attribute (a list of tuples)" ) raise DistutilsClassError(msg % cmd_class) # If the command class has a list of negative alias options, # merge it in with the global negative aliases. negative_opt = self.negative_opt if hasattr(cmd_class, 'negative_opt'): negative_opt = negative_opt.copy() negative_opt.update(cmd_class.negative_opt) # Check for help_options in command class. They have a different # format (tuple of four) so we need to preprocess them here. if hasattr(cmd_class, 'help_options') and isinstance( cmd_class.help_options, list ): help_options = fix_help_options(cmd_class.help_options) else: help_options = [] # All commands support the global options too, just by adding # in 'global_options'. parser.set_option_table( self.global_options + cmd_class.user_options + help_options ) parser.set_negative_aliases(negative_opt) (args, opts) = parser.getopt(args[1:]) if hasattr(opts, 'help') and opts.help: self._show_help(parser, display_options=False, commands=[cmd_class]) return if hasattr(cmd_class, 'help_options') and isinstance( cmd_class.help_options, list ): help_option_found = 0 for help_option, _short, _desc, func in cmd_class.help_options: if hasattr(opts, parser.get_attr_name(help_option)): help_option_found = 1 if callable(func): func() else: raise DistutilsClassError( f"invalid help function {func!r} for help option '{help_option}': " "must be a callable object (function, etc.)" ) if help_option_found: return # Put the options from the command-line into their official # holding pen, the 'command_options' dictionary. opt_dict = self.get_option_dict(command) for name, value in vars(opts).items(): opt_dict[name] = ("command line", value) return args def finalize_options(self): """Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects. """ for attr in ('keywords', 'platforms'): value = getattr(self.metadata, attr) if value is None: continue if isinstance(value, str): value = [elm.strip() for elm in value.split(',')] setattr(self.metadata, attr, value) def _show_help( self, parser, global_options=True, display_options=True, commands: Iterable = () ): """Show help for the setup script command-line in the form of several lists of command-line options. 'parser' should be a FancyGetopt instance; do not expect it to be returned in the same state, as its option table will be reset to make it generate the correct help text. If 'global_options' is true, lists the global options: --verbose, --dry-run, etc. If 'display_options' is true, lists the "display-only" options: --name, --version, etc. Finally, lists per-command help for every command name or command class in 'commands'. """ # late import because of mutual dependence between these modules from distutils.cmd import Command from distutils.core import gen_usage if global_options: if display_options: options = self._get_toplevel_options() else: options = self.global_options parser.set_option_table(options) parser.print_help(self.common_usage + "\nGlobal options:") print() if display_options: parser.set_option_table(self.display_options) parser.print_help( "Information display options (just display information, ignore any commands)" ) print() for command in self.commands: if isinstance(command, type) and issubclass(command, Command): klass = command else: klass = self.get_command_class(command) if hasattr(klass, 'help_options') and isinstance(klass.help_options, list): parser.set_option_table( klass.user_options + fix_help_options(klass.help_options) ) else: parser.set_option_table(klass.user_options) parser.print_help(f"Options for '{klass.__name__}' command:") print() print(gen_usage(self.script_name)) def handle_display_options(self, option_order): """If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. """ from distutils.core import gen_usage # User just wants a list of commands -- we'll print it out and stop # processing now (ie. if they ran "setup --help-commands foo bar", # we ignore "foo bar"). if self.help_commands: self.print_commands() print() print(gen_usage(self.script_name)) return 1 # If user supplied any of the "display metadata" options, then # display that metadata in the order in which the user supplied the # metadata options. any_display_options = 0 is_display_option = set() for option in self.display_options: is_display_option.add(option[0]) for opt, val in option_order: if val and opt in is_display_option: opt = translate_longopt(opt) value = getattr(self.metadata, "get_" + opt)() if opt in ('keywords', 'platforms'): print(','.join(value)) elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): print('\n'.join(value)) else: print(value) any_display_options = 1 return any_display_options def print_command_list(self, commands, header, max_length): """Print a subset of the list of all commands -- used by 'print_commands()'. """ print(header + ":") for cmd in commands: klass = self.cmdclass.get(cmd) if not klass: klass = self.get_command_class(cmd) try: description = klass.description except AttributeError: description = "(no description available)" print(" %-*s %s" % (max_length, cmd, description)) def print_commands(self): """Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute 'description'. """ import distutils.command std_commands = distutils.command.__all__ is_std = set() for cmd in std_commands: is_std.add(cmd) extra_commands = [] for cmd in self.cmdclass.keys(): if cmd not in is_std: extra_commands.append(cmd) max_length = 0 for cmd in std_commands + extra_commands: if len(cmd) > max_length: max_length = len(cmd) self.print_command_list(std_commands, "Standard commands", max_length) if extra_commands: print() self.print_command_list(extra_commands, "Extra commands", max_length) def get_command_list(self): """Get a list of (command, description) tuples. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute 'description'. """ # Currently this is only used on Mac OS, for the Mac-only GUI # Distutils interface (by Jack Jansen) import distutils.command std_commands = distutils.command.__all__ is_std = set() for cmd in std_commands: is_std.add(cmd) extra_commands = [] for cmd in self.cmdclass.keys(): if cmd not in is_std: extra_commands.append(cmd) rv = [] for cmd in std_commands + extra_commands: klass = self.cmdclass.get(cmd) if not klass: klass = self.get_command_class(cmd) try: description = klass.description except AttributeError: description = "(no description available)" rv.append((cmd, description)) return rv # -- Command class/object methods ---------------------------------- def get_command_packages(self): """Return a list of packages from which commands are loaded.""" pkgs = self.command_packages if not isinstance(pkgs, list): if pkgs is None: pkgs = '' pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != ''] if "distutils.command" not in pkgs: pkgs.insert(0, "distutils.command") self.command_packages = pkgs return pkgs def get_command_class(self, command): """Return the class that implements the Distutils command named by 'command'. First we check the 'cmdclass' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module ("distutils.command." + command) and fetch the command class from the module. The loaded class is also stored in 'cmdclass' to speed future calls to 'get_command_class()'. Raises DistutilsModuleError if the expected module could not be found, or if that module does not define the expected class. """ klass = self.cmdclass.get(command) if klass: return klass for pkgname in self.get_command_packages(): module_name = f"{pkgname}.{command}" klass_name = command try: __import__(module_name) module = sys.modules[module_name] except ImportError: continue try: klass = getattr(module, klass_name) except AttributeError: raise DistutilsModuleError( f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')" ) self.cmdclass[command] = klass return klass raise DistutilsModuleError(f"invalid command '{command}'") def get_command_obj(self, command, create=True): """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no command object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. """ cmd_obj = self.command_obj.get(command) if not cmd_obj and create: if DEBUG: self.announce( "Distribution.get_command_obj(): " f"creating '{command}' command object" ) klass = self.get_command_class(command) cmd_obj = self.command_obj[command] = klass(self) self.have_run[command] = False # Set any options that were supplied in config files # or on the command line. (NB. support for error # reporting is lame here: any errors aren't reported # until 'finalize_options()' is called, which means # we won't report the source of the error.) options = self.command_options.get(command) if options: self._set_command_options(cmd_obj, options) return cmd_obj def _set_command_options(self, command_obj, option_dict=None): # noqa: C901 """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command'). 'command_obj' must be a Command instance. If 'option_dict' is not supplied, uses the standard option dictionary for this command (from 'self.command_options'). """ command_name = command_obj.get_command_name() if option_dict is None: option_dict = self.get_option_dict(command_name) if DEBUG: self.announce(f" setting options for '{command_name}' command:") for option, (source, value) in option_dict.items(): if DEBUG: self.announce(f" {option} = {value} (from {source})") try: bool_opts = [translate_longopt(o) for o in command_obj.boolean_options] except AttributeError: bool_opts = [] try: neg_opt = command_obj.negative_opt except AttributeError: neg_opt = {} try: is_string = isinstance(value, str) if option in neg_opt and is_string: setattr(command_obj, neg_opt[option], not strtobool(value)) elif option in bool_opts and is_string: setattr(command_obj, option, strtobool(value)) elif hasattr(command_obj, option): setattr(command_obj, option, value) else: raise DistutilsOptionError( f"error in {source}: command '{command_name}' has no such option '{option}'" ) except ValueError as msg: raise DistutilsOptionError(msg) def reinitialize_command(self, command, reinit_subcommands=False): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real. 'command' should be a command name (string) or command object. If 'reinit_subcommands' is true, also reinitializes the command's sub-commands, as declared by the 'sub_commands' class attribute (if it has one). See the "install" command for an example. Only reinitializes the sub-commands that actually matter, ie. those whose test predicates return true. Returns the reinitialized command object. """ from distutils.cmd import Command if not isinstance(command, Command): command_name = command command = self.get_command_obj(command_name) else: command_name = command.get_command_name() if not command.finalized: return command command.initialize_options() command.finalized = False self.have_run[command_name] = False self._set_command_options(command) if reinit_subcommands: for sub in command.get_sub_commands(): self.reinitialize_command(sub, reinit_subcommands) return command # -- Methods that operate on the Distribution ---------------------- def announce(self, msg, level=logging.INFO): log.log(level, msg) def run_commands(self): """Run each command that was seen on the setup script command line. Uses the list of commands found and cache of command objects created by 'get_command_obj()'. """ for cmd in self.commands: self.run_command(cmd) # -- Methods that operate on its Commands -------------------------- def run_command(self, command): """Do whatever it takes to run a command (including nothing at all, if the command has already been run). Specifically: if we have already created and run the command named by 'command', return silently without doing anything. If the command named by 'command' doesn't even have a command object yet, create one. Then invoke 'run()' on that command object (or an existing one). """ # Already been here, done that? then return silently. if self.have_run.get(command): return log.info("running %s", command) cmd_obj = self.get_command_obj(command) cmd_obj.ensure_finalized() cmd_obj.run() self.have_run[command] = True # -- Distribution query methods ------------------------------------ def has_pure_modules(self): return len(self.packages or self.py_modules or []) > 0 def has_ext_modules(self): return self.ext_modules and len(self.ext_modules) > 0 def has_c_libraries(self): return self.libraries and len(self.libraries) > 0 def has_modules(self): return self.has_pure_modules() or self.has_ext_modules() def has_headers(self): return self.headers and len(self.headers) > 0 def has_scripts(self): return self.scripts and len(self.scripts) > 0 def has_data_files(self): return self.data_files and len(self.data_files) > 0 def is_pure(self): return ( self.has_pure_modules() and not self.has_ext_modules() and not self.has_c_libraries() ) # -- Metadata query methods ---------------------------------------- # If you're looking for 'get_name()', 'get_version()', and so forth, # they are defined in a sneaky way: the constructor binds self.get_XXX # to self.metadata.get_XXX. The actual code is in the # DistributionMetadata class, below. class DistributionMetadata: """Dummy class to hold the distribution meta-data: name, version, author, and so forth. """ _METHOD_BASENAMES = ( "name", "version", "author", "author_email", "maintainer", "maintainer_email", "url", "license", "description", "long_description", "keywords", "platforms", "fullname", "contact", "contact_email", "classifiers", "download_url", # PEP 314 "provides", "requires", "obsoletes", ) def __init__(self, path=None): if path is not None: self.read_pkg_file(open(path)) else: self.name = None self.version = None self.author = None self.author_email = None self.maintainer = None self.maintainer_email = None self.url = None self.license = None self.description = None self.long_description = None self.keywords = None self.platforms = None self.classifiers = None self.download_url = None # PEP 314 self.provides = None self.requires = None self.obsoletes = None def read_pkg_file(self, file): """Reads the metadata values from a file object.""" msg = message_from_file(file) def _read_field(name): value = msg[name] if value and value != "UNKNOWN": return value def _read_list(name): values = msg.get_all(name, None) if values == []: return None return values metadata_version = msg['metadata-version'] self.name = _read_field('name') self.version = _read_field('version') self.description = _read_field('summary') # we are filling author only. self.author = _read_field('author') self.maintainer = None self.author_email = _read_field('author-email') self.maintainer_email = None self.url = _read_field('home-page') self.license = _read_field('license') if 'download-url' in msg: self.download_url = _read_field('download-url') else: self.download_url = None self.long_description = _read_field('description') self.description = _read_field('summary') if 'keywords' in msg: self.keywords = _read_field('keywords').split(',') self.platforms = _read_list('platform') self.classifiers = _read_list('classifier') # PEP 314 - these fields only exist in 1.1 if metadata_version == '1.1': self.requires = _read_list('requires') self.provides = _read_list('provides') self.obsoletes = _read_list('obsoletes') else: self.requires = None self.provides = None self.obsoletes = None def write_pkg_info(self, base_dir): """Write the PKG-INFO file into the release tree.""" with open( os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8' ) as pkg_info: self.write_pkg_file(pkg_info) def write_pkg_file(self, file): """Write the PKG-INFO format data to a file object.""" version = '1.0' if ( self.provides or self.requires or self.obsoletes or self.classifiers or self.download_url ): version = '1.1' # required fields file.write(f'Metadata-Version: {version}\n') file.write(f'Name: {self.get_name()}\n') file.write(f'Version: {self.get_version()}\n') def maybe_write(header, val): if val: file.write(f"{header}: {val}\n") # optional fields maybe_write("Summary", self.get_description()) maybe_write("Home-page", self.get_url()) maybe_write("Author", self.get_contact()) maybe_write("Author-email", self.get_contact_email()) maybe_write("License", self.get_license()) maybe_write("Download-URL", self.download_url) maybe_write("Description", rfc822_escape(self.get_long_description() or "")) maybe_write("Keywords", ",".join(self.get_keywords())) self._write_list(file, 'Platform', self.get_platforms()) self._write_list(file, 'Classifier', self.get_classifiers()) # PEP 314 self._write_list(file, 'Requires', self.get_requires()) self._write_list(file, 'Provides', self.get_provides()) self._write_list(file, 'Obsoletes', self.get_obsoletes()) def _write_list(self, file, name, values): values = values or [] for value in values: file.write(f'{name}: {value}\n') # -- Metadata query methods ---------------------------------------- def get_name(self): return self.name or "UNKNOWN" def get_version(self): return self.version or "0.0.0" def get_fullname(self): return self._fullname(self.get_name(), self.get_version()) @staticmethod def _fullname(name: str, version: str) -> str: """ >>> DistributionMetadata._fullname('setup.tools', '1.0-2') 'setup_tools-1.0.post2' >>> DistributionMetadata._fullname('setup-tools', '1.2post2') 'setup_tools-1.2.post2' >>> DistributionMetadata._fullname('setup-tools', '1.0-r2') 'setup_tools-1.0.post2' >>> DistributionMetadata._fullname('setup.tools', '1.0.post') 'setup_tools-1.0.post0' >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1') 'setup_tools-1.0+ubuntu.1' """ return "{}-{}".format( canonicalize_name(name).replace('-', '_'), canonicalize_version(version, strip_trailing_zero=False), ) def get_author(self): return self.author def get_author_email(self): return self.author_email def get_maintainer(self): return self.maintainer def get_maintainer_email(self): return self.maintainer_email def get_contact(self): return self.maintainer or self.author def get_contact_email(self): return self.maintainer_email or self.author_email def get_url(self): return self.url def get_license(self): return self.license get_licence = get_license def get_description(self): return self.description def get_long_description(self): return self.long_description def get_keywords(self): return self.keywords or [] def set_keywords(self, value): self.keywords = _ensure_list(value, 'keywords') def get_platforms(self): return self.platforms def set_platforms(self, value): self.platforms = _ensure_list(value, 'platforms') def get_classifiers(self): return self.classifiers or [] def set_classifiers(self, value): self.classifiers = _ensure_list(value, 'classifiers') def get_download_url(self): return self.download_url # PEP 314 def get_requires(self): return self.requires or [] def set_requires(self, value): import distutils.versionpredicate for v in value: distutils.versionpredicate.VersionPredicate(v) self.requires = list(value) def get_provides(self): return self.provides or [] def set_provides(self, value): value = [v.strip() for v in value] for v in value: import distutils.versionpredicate distutils.versionpredicate.split_provision(v) self.provides = value def get_obsoletes(self): return self.obsoletes or [] def set_obsoletes(self, value): import distutils.versionpredicate for v in value: distutils.versionpredicate.VersionPredicate(v) self.obsoletes = list(value) def fix_help_options(options): """Convert a 4-tuple 'help_options' list as found in various command classes to the 3-tuple form required by FancyGetopt. """ new_options = [] for help_tuple in options: new_options.append(help_tuple[0:3]) return new_options
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@setuptools@py3@setuptools@_distutils@dist.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "mit-ll/spacegym-kspdg", "repo_path": "spacegym-kspdg_extracted/spacegym-kspdg-main/src/kspdg/private_src/python3_12/Windows_x86_64/kspdg_envs/lbg1/__init__.py", "type": "Python" }
# Pyarmor 8.5.11 (trial), 000000, non-profits, 2024-12-09T10:19:38.025174 from kspdg.private_src.python3_12.Windows_x86_64.pyarmor_runtime_000000 import __pyarmor__ __pyarmor__(__name__, __file__, b'PY000000\x00\x03\x0c\x00\xcb\r\r\n\x80\x00\x01\x00\x08\x00\x00\x00\x04\x00\x00\x00@\x00\x00\x00\x89\x00\x00\x00\x12\t\x04\x00\x1d\x12\xc4\xa1\x14\x82\x04\x890C<N\x0e\xc1\xfe/\x00\x00\x00\x00\x00\x00\x00\x00\x94\xd0\x84\xea^\x92\xa4u\xbc\xc2\xdbV\xee\x18\\Re\xb6\x06;\xa0\xae];\x7fp\xe0\xf7\x10\x1c\x89d\xd1\x9e\x86K\x9bp\x99\xc4;\xe3gl\xa7\x16\xbd-@\xda\x1b\x06\xb3:{=\xc0\x91w\xbeQ%\t\xec\x02\x90\xfa\xec\xcb\x1cP\x94\x1f\xc0\x1da\xc6\xcf\xf2\xaco\xeb\xe6Q\xf1\xb1\xeb\xfc\xa5\xa9\x06\xbb\x95\xe3K\xc3\x7f\xca\xc1\xfa;K\x11"\x1f!\xd8\xc9X\xe9\xee)\xceCX"\xcc\xa2\xc0\x9b\xf8\xad\xe0\xf9iz\xf7C\x9dKzF\xe2\x1f\xa8\xda\xce')
mit-llREPO_NAMEspacegym-kspdgPATH_START.@spacegym-kspdg_extracted@spacegym-kspdg-main@src@kspdg@private_src@python3_12@Windows_x86_64@kspdg_envs@lbg1@__init__.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "vpelgrims/Bisp_1", "repo_path": "Bisp_1_extracted/Bisp_1-main/README.md", "type": "Markdown" }
*** BISP-1 Bayesian Inference of Starlight Polarization in 1D *** ``BISP-1`` implements the Bayesian method for tomographic decomposition of the plane-of-sky orientation of the magnetic field with the use of stellar polarimetry and distance developed in [Pelgrims et al., 2022, A&A, (submitted)](https://arxiv.org/abs/2208.02278). The method decomposes the polarization signal along distance in terms of dust polarization screens: dust clouds of the interstellar medium of our Galaxy. ``BISP-1`` has been developed in the framework of the [PASIPHAE](https://pasiphae.science) project. Install ======= The code can be cloned from the repository ``` git clone git@github.com:vpelgrims/Bisp_1.git /where/to/clone ``` and you can install the python library **not (yet)** using ``` pip install BISP-1 ``` but in going to the folder /where/to/clone and running the command: ``` python -m pip install -e . ``` You may need sudo right. Use the -e option at install time if you plan to make changes to ``BISP-1`` without having to reinstall with each change. Otherwize, drop it. Don't forget the '.' at the end of the command, that is part of it. Running the above command will deploy ``BISP-1`` to your device and you can use the code from anywhere, not just the /where/to/clone folder. Background ========== The code uses the [``dynesty``](https://dynesty.readthedocs.io/en/latest/index.html) Python nested sampler to analyze the polarization + distance data through a maximum-likelihood method. The polarization signal is decomposed in thin dust-polarizing layers placed along distance. Each layer is characterized by its distance (formally the parallax) as well as by its mean polarization (Stokes parameters q and u) and intrinstic scatter which accounts for turbulence. The model and the likelihood are fully determined in [our](https://arxiv.org/abs/2208.02278) paper. Dependencies ============ ``BISP-1`` depends on several libraries reported in the [pyproject.toml](https://github.com/vpelgrims/Bisp_1/blob/main/pyproject.toml) file. They will be installed at installation if requirements are not met. ``BISP-1`` does not explicitly rely on ``scipy`` but it calls utilities in ``dynesty`` that require it, so ``scipy`` is added as a requirement. Usage ===== A [jupyter notebook](https://github.com/vpelgrims/Bisp_1/blob/main/tests/Usage_Tutorial.ipynb) is provided to describe the overal structure of the code, to ease its handling, and demonstrate the several features that are included such as results display and plotting utilities. Assuming a star sample with appropriate formating, a basic usage with default setting could read as: ``` import BISP_1 as bisp mystars = bisp.Stars(starsample) # initialization of a Stars object mypriors = bisp.Priors(mystars) # initialization of a Priors object mylos = bisp.Bisp(mystars,mypriors) # initialization of the main object # 1. run the Bayesian decomposition assuming 1 cloud along the sightline: mylos.run_OneLayer() # 2. run the Bayesian decomposition assuming 2 clouds along the sightline: mylos.run_TwoLayers() # 3. compare the performance of both tested model mylos.printSummaryStat() ``` References ========== If ``BISP-1`` is useful for you and your research please cite [this](https://arxiv.org/abs/2208.02278) PASIPHAE paper: "Starlight-polarization-based tomography of the magnetized ISM: Pasiphae's line-of-sight inversion method" Pelgrims, Panopoulou, Tassis, Pavlidou et al., 2022 Astronomy & Astrophysics, submitted. --- Bisp-1 -- ReadMe Copyright (C) 2022 V.Pelgrims
vpelgrimsREPO_NAMEBisp_1PATH_START.@Bisp_1_extracted@Bisp_1-main@README.md@.PATH_END.py
{ "filename": "data_download.py", "repo_name": "EoRImaging/FHD", "repo_path": "FHD_extracted/FHD-master/data_download.py", "type": "Python" }
#!/usr/bin/python import os from astropy.time import Time from astropy.io import fits import psycopg2 import sys import socket from optparse import OptionParser import subprocess import datetime import time import zipfile import numpy as np #******************************** #Script that downloads GPU box files, runs cotter, updates the mwa_qc database with the uvfits #locations, and deletes the GPU box files. It performs a check for existing GPU box files #and will not download them if they already exist. Option for downloading uvfits files and #bypassing cotter. Files are downloaded to whichever nodes have sufficient free space. Download #and cotter processes are parallelized with grid engine for efficiency. #Script written by Nichole Barry and Ruby Byrne, July 2016. def main(): #Parse the command line inputs. #Set version and subversion to a number to indicate which cotter settings to use (defined in #run_cotter in the cotter_args dict). Required unless uvfits_download_check is set, which #forces uvfits download only and bypasses cotter. parser=OptionParser() parser.add_option("-v", "--version", dest="version", \ help="Version for cotter arguments defined in run_cotter function") parser.add_option("-s", "--subversion", dest="subversion", \ help="Subversion for cotter arguments defined in run_cotter function") parser.add_option("-o", "--obsfile_name", dest="obsfile_name", \ help="Path to a file with the observation IDs for processing") parser.add_option("-u", "--uvfits_download_check", dest="uvfits_download_check", \ help="Download only the uvfits from the ngas server") #parser.add_option("-f", "--flagfiles", dest="flagfiles", \ # help="Use the flag files generated by NGAS run of cotter, which is the default.",default=1) parser.add_option("-c", "--db_comment", dest="db_comment", \ help="Optional comment to be placed in the uvfits database.",default='') (options, args)=parser.parse_args() version=options.version subversion=options.subversion obsfile_name=options.obsfile_name uvfits_download_check=options.uvfits_download_check db_comment=options.db_comment if (version is None) and (subversion is None) and (uvfits_download_check is None): print "ERROR: version, subversion, and uvfits_download_check were not set." print "To run cotter, set a version and subversion (defined in script)." print "To download uvfits files only and bypass cotter, set -u 1 on the command line." sys.exit(1) obs_per_chunk = 4 #number of obsids to run in parallel #find which nodes have enough space for downloads: all_nodes = ["eor-02", "eor-03", "eor-04", "eor-05","eor-07", "eor-08", "eor-10", "eor-11", "eor-12", "eor-13", "eor-14"] #eor06 temporarly dropped all_nodes = ["/nfs/" + nodename + "/r1/" for nodename in all_nodes] #Get obsids to download obsfile = open(obsfile_name, "r") obsids = [line.split( ) for line in obsfile.readlines()] obsids = [obs[0] for obs in obsids] obsfile.close() nonredundant_obsids = list(set(obsids)) if len(obsids) != len(nonredundant_obsids): print "WARNING: Obs list contains redundant entries." obsids = nonredundant_obsids #Define the progress bar (first element is obs done, second element is total obs) obs_progress = [0,len(obsids)] #Find the obsids' save directory names t = Time([int(obsid) for obsid in obsids], format="gps", scale="utc") jds = t.jd jds = [int(jd) for jd in jds] save_directories = ["EoRuvfits/jd" + str(jd) + "v"+ str(version) + "_" + str(subversion) + "/" for jd in jds] #Check to see if GPU box files already exist, define a preferred node if they do: node_preferred = [] for i, obsid in enumerate(obsids): gpu_loc_node = find_gpubox(obsid, save_directories[i], all_nodes) if not gpu_loc_node: node_preferred.append(False) else: node_preferred.append(gpu_loc_node) obs_submitted = [False for i in range(len(obsids))] download_tries = 4 #number of times a obsid will attempt to download correctly for download_try in range(download_tries): if download_try > 0: print "Reprocessing failed obsids: Download attempt number " + str(download_try+1) + "/" + str(download_tries) #Find which nodes are available for downloads free_nodes = filespace(all_nodes) if len(free_nodes) == 0: print "ERROR: No file space found." sys.exit(1) obs_chunk = [] failed_obs = [] obs_running = [] save_paths_running = [] download_script_paths_running = [] metafits_script_paths_running = [] cotter_script_paths_running = [] final_task_jobids_running = [] use_node_index = 0 while obs_submitted.count(False) > 0: #Find which node the chunk should run on if len(obs_running) < len(free_nodes): #if not all the nodes have been used for the first time node = free_nodes[use_node_index] use_node_index += 1 else: #if all the nodes have been used for the first time, begin waiting for nodes to finish while True: #Wait for a chunk to finish running use_node_index = wait_for_gridengine(obs_running, final_task_jobids_running) #Process the completed chunk new_failed_obs = chunk_complete(download_script_paths_running[use_node_index], \ metafits_script_paths_running[use_node_index], cotter_script_paths_running[use_node_index], \ obs_running[use_node_index], save_paths_running[use_node_index], version, subversion, cotter_version, \ db_comment, uvfits_download_check, obs_progress) failed_obs.extend(new_failed_obs) #Check to see if the node that finished has enough space to accept a new chunk; if not, remove that node from use node = free_nodes[use_node_index] if len(filespace([node])) == 0: del free_nodes[use_node_index] del obs_running[use_node_index] del save_paths_running[use_node_index] del download_script_paths_running[use_node_index] del metafits_script_paths_running[use_node_index] del cotter_script_paths_running[use_node_index] del final_task_jobids_running[use_node_index] else: break #Assemble an obs_chunk: while len(obs_chunk) != obs_per_chunk and obs_submitted.count(False) > 0: #Find the indices of obsids that haven't been submitted obs_indices = [index for index, value in enumerate(obs_submitted) if value == False] node_preferred_use = [node_preferred[obs_index] for obs_index in obs_indices] for obs_index in obs_indices: #First priority is to choose obsids that have a "preferred node" that matches the node it will be run on if node_preferred_use.count(node) > 0: if node_preferred[obs_index] == node: obs_chunk.append(obsids[obs_index]) obs_submitted[obs_index] = True else: #Next choose obsids that don't have a "preferred node" if node_preferred_use.count(False) > 0: if node_preferred[obs_index] == False: obs_chunk.append(obsids[obs_index]) obs_submitted[obs_index] = True #Finally choose obsids that have a "preferred node" that isn't the node it will be run on else: obs_chunk.append(obsids[obs_index]) obs_submitted[obs_index] = True #Chunk is done if it has obs_per_chunk number of obsids or if it contains the last obsids to be submitted if len(obs_chunk) == obs_per_chunk or obs_submitted.count(False) == 0: break download_script_paths = [] metafits_script_paths = [] cotter_script_paths = [] final_task_jobid = [] download = [] save_paths = [] for obsid in obs_chunk: obs_index = obsids.index(obsid) if node_preferred[obs_index] == False: download.append(True) save_paths.append(node + save_directories[obs_index]) else: download.append(False) save_paths.append(node_preferred[obs_index] + save_directories[obs_index]) #Find the path to python using a child process stdoutpointer = subprocess.Popen(["which","python"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #Check to see if a path was found for python if stderr_data: print 'ERROR: The command "which python" did not return the path of the python installation you want to use.' print 'Please add the path to python.' sys.exit(1) python_path = stdout_data #Check to make sure the log_files directory exists on the node if not os.path.exists(node + 'EoRuvfits/log_files/'): os.makedirs(node + 'EoRuvfits/log_files/') #Check to make sure the obsid directory exists on the node for each obsid #Otherwise, script runs ahead of Grid Engine, and requires directory before GE can make it. for i in range(len(obs_chunk)): if not os.path.exists(save_paths[i] + obs_chunk[i]): os.makedirs(save_paths[i] + obs_chunk[i]) #initialize task_jobid = False #Mount your home directory and the node directories to remove stale NFS handles #stdoutpointer = subprocess.Popen(("cd $HOME ; ls ; cd " + node + '; ls').split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #stdout_data, stderr_data = stdoutpointer.communicate() #Download the files (a uvfits or gpuboxes depending on uvfits_download_check) if any(download) or uvfits_download_check: (task_jobid, download_script_path) = download_files(save_paths, obs_chunk, uvfits_download_check, python_path, node, download) download_script_paths.append(download_script_path) #If metafits does not exist in the same location as the gpubox files, set up logic to create it metafits_logic = [] for i in range(len(obs_chunk)): if not os.path.isfile(save_paths[i] + obs_chunk[i] +'/' + obs_chunk[i] + '.metafits'): metafits_logic.append(True) else: metafits_logic.append(False) print "Using metafits file found for obsid " + obs_chunk[i] + " located in " + save_paths[i] if any(metafits_logic): #Make a metafits file for the obsids, will bypass if all the metafits exists. (task_jobid, metafits_script_path) = make_metafits(obs_chunk, save_paths,task_jobid,python_path,node,metafits_logic) metafits_script_paths.append(metafits_script_path) #Run cotter if gpubox files were downloaded if not uvfits_download_check: (task_jobid, cotter_version, cotter_script_path) = run_cotter(version,subversion,save_paths,obs_chunk,task_jobid,node) cotter_script_paths.append(cotter_script_path) else: cotter_version='' #Grab the last Grid Engine jobid to watch while the program sleeps final_task_jobid.append(task_jobid) #Record information for the currently running chunks if len(obs_running) < use_node_index: obs_running.append(obs_chunk) save_paths_running.append(save_paths) download_script_paths_running.append(download_script_paths) metafits_script_paths_running.append(metafits_script_paths) cotter_script_paths_running.append(cotter_script_paths) final_task_jobids_running.append(final_task_jobid) else: obs_running[use_node_index] = obs_chunk save_paths_running[use_node_index] = save_paths download_script_paths_running[use_node_index] = download_script_paths metafits_script_paths_running[use_node_index] = metafits_script_paths cotter_script_paths_running[use_node_index] = cotter_script_paths final_task_jobids_running[use_node_index] = final_task_jobid obs_chunk = [] while len(obs_running) > 0: #Wait for a chunk to finish running use_node_index = wait_for_gridengine(obs_running, final_task_jobids_running) #Process the completed chunk new_failed_obs = chunk_complete(download_script_paths_running[use_node_index], metafits_script_paths_running[use_node_index], \ cotter_script_paths_running[use_node_index], obs_running[use_node_index], save_paths_running[use_node_index], \ version, subversion, cotter_version,db_comment, uvfits_download_check,obs_progress) failed_obs.extend(new_failed_obs) del free_nodes[use_node_index] del obs_running[use_node_index] del save_paths_running[use_node_index] del download_script_paths_running[use_node_index] del metafits_script_paths_running[use_node_index] del cotter_script_paths_running[use_node_index] del final_task_jobids_running[use_node_index] #Mark which obsids need to be reran, if any: if len(failed_obs) == 0: print "All obsids downloaded successfully." break else: for failed in failed_obs: obs_submitted[obsids.index(failed)] = False print str(len(obsids)-len(failed_obs)) + "/" + str(len(obsids)) + " obsids downloaded successfully." #******************************** #******************************** #Module that searches for saved GPU box files def find_gpubox(obsid, save_directory, all_nodes): for gpu_loc_node in all_nodes: gpu_loc_path = gpu_loc_node + save_directory if os.path.isdir(gpu_loc_path + obsid): #checks to see if the directory exists directory_contents = os.listdir(gpu_loc_path + obsid) gpubox00 = 0 gpubox01 = 0 flags = 0 metafits = 0 for filename in directory_contents: #counts how many of each type of file exists if filename.endswith("_00.fits"): gpubox00 += 1 if filename.endswith("_01.fits"): gpubox01 += 1 if filename.endswith("_flags.zip"): flags += 1 if filename.endswith("_metafits_ppds.fits"): metafits += 1 if gpubox00 >= 24 and (gpubox01 >= 24 or gpubox01 == 0) and flags >= 1 and metafits >= 1: print "GPU box files for obsid " + obsid + " located in " + gpu_loc_path #if gpubox00 != 24 or gpubox01 != 24 or flags != 1 or metafits != 1: # print "WARNING: Directory contains extra GPU box files." return gpu_loc_node return False #******************************** #******************************** #Module that sleeps while periodically checking to see if a task has finished in gridengine def wait_for_gridengine(obs_running, final_task_jobids_running): sleep_time = 20 while True: time.sleep(sleep_time) for use_node_index in range(len(obs_running)): obs_chunk = obs_running[use_node_index] final_task_jobid = final_task_jobids_running[use_node_index] job_finish_array = [False for obsid in obs_chunk] #Check each of tasks in the task array for the last submitted job for task_array_index in range(len(obs_chunk)): #Talk to Grid Engine about the last submitted job for one of the tasks qsub_command = 'qacct -j ' + str(final_task_jobid[0]) + ' -t ' + str(task_array_index) stdoutpointer = subprocess.Popen(qsub_command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #If the command that only works when the job is done does not throw an error, then the job finished if not stderr_data: job_finish_array[task_array_index] = True #If all of the tasks are done, then break the sleeper loop if all(job_finish_array): return use_node_index #******************************** #******************************** #Module that manages a chunk after it has been processed in Grid Engine; it removes temporary scripts, #checks if the downloads were successful, and deletes the gpubox files def chunk_complete(download_script_path, metafits_script_path, cotter_script_path, obs_chunk, save_paths, \ version, subversion, cotter_version,db_comment, uvfits_download_check, obs_progress): #Make a list of non-duplicate entries in the script paths for easy deletion download_script_path=list(set(download_script_path)) metafits_script_path=list(set(metafits_script_path)) cotter_script_path=list(set(cotter_script_path)) #Remove the temporary bash script for download, metafits, and cotter in Grid Engine for script in download_script_path: os.remove(script) for script in metafits_script_path: os.remove(script) for script in cotter_script_path: os.remove(script) #Check that all gpubox files were successfully downloaded failed_obs = [] obs_chunk_finished = [] save_path_finished = [] for i, obsid in enumerate(obs_chunk): failed = False if os.path.isdir(save_paths[i] + obsid): #checks to see if the directory exists directory_contents = os.listdir(save_paths[i] + obsid) gpubox00 = 0 gpubox01 = 0 flags = 0 metafits_ppds = 0 metafits = 0 uvfits = 0 for filename in directory_contents: #counts how many of each type of file exists if filename.endswith("_00.fits"): gpubox00 += 1 if filename.endswith("_01.fits"): gpubox01 += 1 if filename.endswith("_flags.zip"): flags += 1 if filename.endswith("_metafits_ppds.fits"): metafits_ppds += 1 if filename.endswith(".metafits"): metafits += 1 if filename.endswith(".uvfits"): #Check to see if the uvfits has any information in it if os.stat(save_paths[i] + obsid + '/' + obsid + '.uvfits').st_size == 0: failed = True else: uvfits += 1 if gpubox00 < 24 or (gpubox01 < 24 and gpubox01 != 0) or flags < 1 or metafits_ppds < 1 or metafits < 1: failed = True #If only the uvfits file was to be downloaded and it was successful, reset the failed variable if uvfits_download_check and (metafits > 0) and (uvfits > 0): failed = False else: failed = True if failed: print "Obsid " + obsid + " not successfully downloaded." failed_obs.append(obsid) else: obs_progress[0] = obs_progress[0] + 1 obs_chunk_finished.append(obsid) save_path_finished.append(save_paths[i]) print "Obsid " + obsid + " sucessfully downloaded to " + save_paths[i] + ', ' + str(obs_progress[0]) + '/' + str(obs_progress[1]) + ' done' #Fill the database with the new uvfits that finished fill_database(obs_chunk_finished,version,subversion,save_path_finished,cotter_version,db_comment,uvfits_download_check) #Delete the gpubox files delete_gpubox(obs_chunk_finished,save_path_finished) return failed_obs #******************************** #******************************** #Module that takes a list of file paths and returns those that have more than #a specified amount of free disk space; prints a warning if the free disk space #is less than another specified amount def filespace(nodes): enough_space = 2 #disks with less than this amount in TB of free space will not be used space_warning = 4 #disks with less than this amount in TB of free space will return a warning free_nodes = [] for node in nodes: if os.path.isdir(node): stat = os.statvfs(node) free_space = (stat.f_bavail * stat.f_frsize)/1024.**4 if free_space > enough_space: free_nodes.append(node) if free_space < space_warning: print "WARNING: Limited disk space in " + node else: print "WARNING: No disk space in " + node else: print "WARNING: Disk " + node + " not found." return free_nodes #******************************** #******************************** def download_files(save_paths, obs_chunk, uvfits_download_check, python_path, node, download): #Check to see that the MWA_Tools is in the path so obsdownload.py can be found #Find the path of MWA_Tools by looking in the system path variable mwa_tools_path="" for parsed_path in os.environ['PATH'].split(':'): if "MWA_Tools" in parsed_path: mwa_tools_path = parsed_path #If the MWA_Tools path doesn't exist, throw an error. if not mwa_tools_path: print 'ERROR: MWA_Tools is not in the path, obsdownload.py not found!' print 'Please add the path to MWA_Tools to your system path.' sys.exit(1) #Setup the path to the download script and log files obsdownload_path = mwa_tools_path[0:mwa_tools_path.find("MWA_Tools")+9] + '/scripts/obsdownload.py' log_path = (save_paths[0])[0:(save_paths[0]).rfind("jd")] + "log_files/" #Pick out the obsids that need to be downloaded given the download logic created in main. obs_chunk_download=[] save_paths_download=[] for i in range(len(download)): if download[i]: obs_chunk_download.append(obs_chunk[i]) save_paths_download.append(save_paths[i]) #Setup the u tag argument, with or without the uvfits only option if not uvfits_download_check: u_arg = '' else: u_arg = ' -u 1' #Write a bash script so that Grid Engine can run a task array for the downloads. download_script_path = save_paths_download[0] + 'download_commands_file_chunk'+obs_chunk_download[0]+'.sh' download_commands_file = open(download_script_path, 'w') #Write the contents of the file and the necessary arguments, mount directories to remove stale handles download_commands_file.write('#!/bin/bash\n\n' + \ '#$ -S /bin/bash\n\n' + \ 'save_paths_download=(0 '+" ".join(save_paths_download) + ')\n' + \ 'obs_chunk_download=(0 ' + " ".join(obs_chunk_download) + ')\n' + \ 'ls ${save_paths_download[$SGE_TASK_ID]} > /dev/null \n' + \ 'ls $HOME > /dev/null \n' + \ python_path.strip('\n') + ' ' + obsdownload_path + ' -d ${save_paths_download[$SGE_TASK_ID]} -o ${obs_chunk_download[$SGE_TASK_ID]} -t 1 ' + u_arg) #Close the file download_commands_file.close() #Make the file executable os.chmod(download_script_path, 0775) #Setup the the bulk of the qsub command qsub_command = "qsub -l h_vmem=1G,h_stack=512,h_rt=05:00:00,h=" + node.split('/')[2] + ".mit.edu -pe chost 1 -e " + \ log_path + " -o " + log_path + " -N obs_download -t 1:" + str(len(obs_chunk_download)) #Run the qsub command stdoutpointer = subprocess.Popen((qsub_command + ' ' + download_script_path).split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #If Grid Engine had an error, report and exit if stderr_data: print "WARNING: Grid Engine threw an error trying to run obsdownload.py." print stderr_data sys.exit(1) #Get the jobid of the download task array to hold future jobs till it finishes. task_jobid = (stdout_data.split())[2].rsplit('.')[0] return (task_jobid, download_script_path) #******************************** #******************************** #Module for running cotter given input version and subversion, and for finding #the version of cotter itself. Will make a metafits if it does not exist in the #save_path directory def run_cotter(version,subversion,save_paths,obs_chunk,task_jobid,node): #Perform check to make sure essential information is known for the module if not obs_chunk: print "ERROR: obs_chunk not defined in run_cotter." sys.exit(1) if not version: print "ERROR: version not defined in run_cotter" sys.exit(1) if not subversion: print "ERROR: subversion not defined in run_cotter" sys.exit(1) if not save_paths: print "ERROR: save_paths not defined in run_cotter" sys.exit(1) if not node: print "ERROR: node not defined in run_cotter" sys.exit(1) #Warn the user if uvfits were automatically downloaded for at least one observation in the #chunk. Will delete this automatic uvfits and rerun cotter with the specifications. uvfits_logic = [] for i in range(len(save_paths)): if os.path.isfile(save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] + '.uvfits'): uvfits_logic.append(True) os.remove(save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] + '.uvfits') if any(uvfits_logic): print "WARNING: At least one uvfits was automatically downloaded, which will be deleted and rerun with your cotter specifications." print "Please set -u to download uvfits only and bypass cotter." #A dictionary of all version and subversion cotter arguments. FEEL FREE TO ADD MORE VERSIONS, #but please add a comment below. #3,3 was used to test compressed fits #3,4 was a rerun of 3,1 with a newer version of cotter before that version was recorded #4,0 went back to old settings for an industrial run #4,1 was the same as 4,0 but for running on compressed gpubox files #5,0 was a test to phase all obs to zenith (phasing needs to be added per obs currently) #5,1 incorperates flag files and runs cotter without the bp applied, with all the other default settings cotter_args = { \ "0,0": "-timeavg 4 -freqavg 2 -flagedges 2 -usepcentre -initflag 2 -noflagautos", \ "1,0": "-timeavg 4 -freqavg 2 -flagedges 2", \ "2,0": "-timeavg 4 -freqavg 2 -flagedges 2 -usepcentre -initflag 2 -noflagautos", \ "2,1": "-timeavg 4 -flagedges 2 -usepcentre -initflag 2 -noflagautos", \ "2,2": "-timeavg 4 -freqavg 2 -flagedges 2 -usepcentre -initflag 2 -noflagautos", \ "2,3": "-timeavg 1 -freqavg 2 -flagedges 2 -usepcentre -initflag 2 -noflagautos", \ "3,0": "-timeavg 4 -freqavg 2 -flagedges 2 -usepcentre -initflag 2 -noflagautos", \ "3,1": "-timeavg 4 -freqavg 1 -edgewidth 80 -usepcentre -initflag 0 -noflagautos", \ "3,2": "-timeavg 1 -freqavg 2 -edgewidth 80 -usepcentre -initflag 0 -noflagautos", \ "3,3": "-timeavg 1 -freqavg 2 -edgewidth 80 -usepcentre -initflag 0 -noflagautos", \ "3,4": "-timeavg 4 -freqavg 1 -edgewidth 80 -usepcentre -initflag 0 -noflagautos", \ "4,0": "-timeres 2 -freqres 80 -edgewidth 80 -usepcentre -initflag 2 -noflagautos", \ "4,1": "-timeres 2 -freqres 80 -edgewidth 80 -usepcentre -initflag 2 -noflagautos", \ "5,0": "-timeres 2 -freqres 80 -edgewidth 80 -initflag 2 -noflagautos", \ "5,1": "-timeres 2 -freqres 80 -edgewidth 80 -usepcentre -initflag 2 -noflagautos -norfi -flagfiles -sbpassband" \ } #Check that the version and subversion supplied exist in the argument dictionary if not cotter_args.get(version + ',' + subversion): print 'ERROR: Cotter version ' + version + ', subversion ' + subversion + ' does not exist in the python dictionary in module run_cotter.' print 'Please choose another version and subversion or update the run_cotter module.' sys.exit(1) #Find the path to cotter using a child process stdoutpointer = subprocess.Popen(["which","cotter"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #Check to see if a path was found for cotter if stderr_data: print 'ERROR: The command "which cotter" did not return the path of the cotter installation you want to use.' print 'Please add the path to cotter.' sys.exit(1) #Path setups cotter_path = stdout_data.strip('\n') metafits_path = [save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] + '.metafits' for i in range(len(obs_chunk))] uvfits_path = [save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] + '.uvfits' for i in range(len(obs_chunk))] flagfiles_path = [save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] + '_%%.mwaf' for i in range(len(obs_chunk))] flagfiles_zip = [save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] + '_flags.zip' for i in range(len(obs_chunk))] flagfiles_dir = [save_paths[i] + obs_chunk[i] + '/' for i in range(len(obs_chunk))] gpubox_path = [save_paths[i] + obs_chunk[i] + '/' + obs_chunk[i] for i in range(len(obs_chunk))] #Find out the version of the found cotter using a child process stdoutpointer = subprocess.Popen((cotter_path + " --version").split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #String manipulation to extract the version and version date cotter_version_string = stdout_data.splitlines()[0] cotter_version = cotter_version_string[cotter_version_string.rfind("version"):cotter_version_string.rfind(".")] #Setup the path to the log files log_path = (save_paths[0])[0:(save_paths[0]).rfind("jd")] + "log_files/" #If flagfiles is set in the cotter args, unzip the flag folder and place their path in the dict if '-flagfiles' in cotter_args[str(version)+','+str(subversion)]: index = cotter_args[str(version)+','+str(subversion)].find('-flagfiles') output_line = cotter_args[str(version)+','+str(subversion)][:index+10] + ' ${flagfiles_path[$SGE_TASK_ID]}' + cotter_args[str(version)+','+str(subversion)][index+10:] cotter_args[str(version)+','+str(subversion)] = output_line #If the sbpassband is set in the cotter args, make a file of 1's to be read into cotter and insert #that into the dict. This removes bandpass division, which is assumed to be the desired effect. if '-sbpassband' in cotter_args[str(version)+','+str(subversion)]: if not os.path.isfile(save_paths[0] + 'sbpassband_1s.txt'): sbpassband_1s_file = open(save_paths[0] + 'sbpassband_1s.txt', 'w') array_ones = np.ones((32,5)) np.savetxt(sbpassband_1s_file, array_ones, fmt=['%d','%d','%d','%d','%d']) sbpassband_1s_file.close() index = cotter_args[str(version)+','+str(subversion)].find('-sbpassband') output_line = cotter_args[str(version)+','+str(subversion)][:index+11] + ' ' + save_paths[0] + 'sbpassband_1s.txt' + cotter_args[str(version)+','+str(subversion)][index+11:] cotter_args[str(version)+','+str(subversion)] = output_line #Write a bash script so that Grid Engine can run a task array for the downloads. cotter_script_path = save_paths[0] + 'cotter_commands_file_chunk'+obs_chunk[0]+'.sh' cotter_commands_file = open(cotter_script_path, 'w') #Write the contents of the file and the necessary arguments cotter_commands_file.write('#!/bin/bash\n\n' + \ '#$ -S /bin/bash\n\n' + \ 'uvfits_path=(0 '+" ".join(uvfits_path) + ')\n' + \ 'gpubox_path=(0 ' + " ".join(gpubox_path) + ')\n' + \ 'metafits_path=(0 ' + " ".join(metafits_path) + ')\n' + \ 'flagfiles_path=(0 ' + " ".join(flagfiles_path) + ')\n' + \ 'flagfiles_zip=(0 ' + " ".join(flagfiles_zip) + ')\n' + \ 'flagfiles_dir=(0 ' + " ".join(flagfiles_dir) + ')\n' + \ 'ls ${gpubox_path[$SGE_TASK_ID]} > /dev/null\n' + \ 'ls $HOME > /dev/null \n\n' + \ 'echo JOB_ID $JOB_ID \n' + \ 'echo TASK_ID $SGE_TASK_ID \n' + \ 'if [ "$(ls -l ${gpubox_path[$SGE_TASK_ID]}*gpubox*_00.fits | wc -l)" -ne "24" ] ; then exit ; fi\n') #Check to make sure gpubox files exist before queuing up if '-flagfiles' in cotter_args[str(version)+','+str(subversion)]: cotter_commands_file.write('unzip -o ${flagfiles_zip[$SGE_TASK_ID]} -d ${flagfiles_dir[$SGE_TASK_ID]}\n') cotter_commands_file.write(cotter_path + ' ' + cotter_args[str(version)+','+str(subversion)] + \ ' -mem 25 -m ${metafits_path[$SGE_TASK_ID]} -o ${uvfits_path[$SGE_TASK_ID]} ${gpubox_path[$SGE_TASK_ID]}*gpubox*.fits') cotter_commands_file.close() #Make the file executable os.chmod(cotter_script_path, 0775) #Setup the bulk of the Grid Engine command, depending on if there is a task to wait on if task_jobid: qsub_command = "qsub -V -b y -hold_jid " + task_jobid + " -l h_vmem=20G,h_stack=512,h_rt=02:00:00,h=" + node.split('/')[2] \ + ".mit.edu -pe chost 1 -e " + log_path + " -o " + log_path +" -N cotter -t 1:" + str(len(obs_chunk)) + " " + cotter_script_path else: qsub_command = "qsub -V -b y -l h_vmem=20G,h_stack=512,h_rt=02:00:00,h=" + node.split('/')[2] \ + ".mit.edu -pe chost 1 -e " + log_path + " -o " + log_path +" -N cotter -t 1:" + str(len(obs_chunk)) + " " + cotter_script_path #Run cotter with the correct arguments, the path to the metafits, the uvfits output path, and the gpubox file paths stdoutpointer = subprocess.Popen((qsub_command + ' ' + cotter_script_path).split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #If there is data in the standard error output from cotter, let the user know if stderr_data: print 'WARNING: Grid Engine has thrown an error in trying to run cotter.' print stderr_data #Get the jobid of the cotter task array for checking later. task_jobid = (stdout_data.split())[2].rsplit('.')[0] #return the version of cotter used for fill_database and the qsub job id return (task_jobid, cotter_version, cotter_script_path) #Some stats about the MIT cluster's performance with cotter leading to the decision regarding allocation #100% memory allowed in cotter, allocating 80G per job (used <46), ran 1 jobs per cpu, took ~80 min for 7 job run #50% memory allowed in cotter, allocating 25G per job (used <25), ran 3 jobs per cpu, took ~45 min for 7 job run #25% memory allowed in cotter, allocating 20G per job (used <18), ran 4 jobs per cpu, took ~43 min for 7 job run #Under 25% memory in cotter causes memory allocation errors. #absmem option for cotter did not work with 20G allocation #******************************** #******************************** def make_metafits(obs_chunk, save_paths, task_jobid, python_path, node, metafits_logic): #Elements of obsids to make metafits for obs_elements = [i for i, x in enumerate(metafits_logic) if x] #Find the path of MWA_Tools by looking in the system path variable mwa_tools_path="" for parsed_path in os.environ['PATH'].split(':'): if "MWA_Tools" in parsed_path: mwa_tools_path = parsed_path #If the MWA_Tools path doesn't exist, throw an error. if not mwa_tools_path: print 'ERROR: MWA_Tools is not in the path, make_metafits.py not found!' print 'Please add the path to MWA_Tools to your system path.' sys.exit(1) #Setup the path to make_metafits.py and to the metafits file make_metafits_path = mwa_tools_path[0:mwa_tools_path.find("MWA_Tools")+9] + '/scripts/make_metafits.py' metafits_path = [save_paths[obs_elements[i]] + obs_chunk[obs_elements[i]] + '/' + obs_chunk[obs_elements[i]] + '.metafits' for i in range(len(obs_elements))] metafits_dir = [save_paths[obs_elements[i]] + obs_chunk[obs_elements[i]] for i in range(len(obs_elements))] #Setup the log path for Grid Engine log_path = (save_paths[0])[0:(save_paths[0]).rfind("jd")] + "log_files/" #Write a bash script so that Grid Engine can run a task array for the metafits. metafits_script_path = save_paths[obs_elements[0]] + 'metafits_commands_file_chunk'+obs_chunk[obs_elements[0]]+'.sh' metafits_commands_file = open(metafits_script_path, 'w') #Write the contents of the file and the necessary arguments metafits_commands_file.write('#!/bin/bash\n\n' + \ '#$ -S /bin/bash\n\n' + \ 'save_paths_metafits=(0 '+" ".join(metafits_path) + ')\n' + \ 'metafits_dir=(0 '+" ".join(metafits_dir) + ')\n' + \ 'obs_chunk_metafits=(0 ' + " ".join([obs_chunk[obs_element] for obs_element in obs_elements]) + ')\n' + \ 'ls ${metafits_dir[$SGE_TASK_ID]} > /dev/null\n' + \ python_path.strip('\n') + ' ' + make_metafits_path + ' -o ${save_paths_metafits[$SGE_TASK_ID]} --gps ${obs_chunk_metafits[$SGE_TASK_ID]} ') #Close the file metafits_commands_file.close() #Make the file executable os.chmod(metafits_script_path, 0775) #Setup the bulk of the Grid Engine command, depending on if there is a task to wait on if task_jobid: qsub_command = "qsub -hold_jid " + task_jobid + " -l h_vmem=1G,h_stack=512,h_rt=01:00:00,h=" + node.split('/')[2] + \ ".mit.edu -V -pe chost 1 -e " + log_path + " -o " + log_path +" -N make_metafits -t 1:" + str(len(obs_elements)) else: qsub_command = "qsub -l h_vmem=1G,h_stack=512,h_rt=01:00:00,h=" + node.split('/')[2] + \ ".mit.edu -V -pe chost 1 -e " + log_path + " -o " + log_path +" -N make_metafits -t 1:" + str(len(obs_elements)) #Run the metafits script to create a metafits for the obsid in the uvfits folder stdoutpointer = subprocess.Popen((qsub_command + ' ' + metafits_script_path).split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = stdoutpointer.communicate() #If there is data in the standard error output from the metafits script, let the user know if stderr_data: print 'WARNING: Grid Engine threw an error trying to run make_metafits.py' print stderr_data #Get the jobid of the metafits task array to hold future jobs till it finishes. task_jobid = (stdout_data.split())[2].rsplit('.')[0] return (task_jobid, metafits_script_path) #******************************** #******************************** #Module designed to fill the uvfits table on the mwa_qc database located on eor-00. #Fills the uvfits table with the uvfits version and subversion for the obsid run, as well as #the path to the uvfits, the cotter version that generated it, a timestamp for when it was #run, an optional comment, and the bottom and top of the frequency range the uvfits file #spans. def fill_database(obs_chunk,version,subversion,save_paths,cotter_version,db_comment,uvfits_download_check): #Connect to the database on eor-00 using the mwa username. try: conn = psycopg2.connect(database='mwa_qc',user='mwa',password='BowTie',host='eor-00.mit.edu') except: print 'Could not connect to mwa database.' sys.exit(1) #Module only works on the MIT cluster. if not 'mit.edu' in socket.gethostname(): print 'Sorry, this script is currently only supported on eor-xx.mit.edu machines.' sys.exit(1) cur = conn.cursor() #Perform check to make sure essential information is known about the uvfits file if not obs_chunk: print "WARNING: obs_chunk not defined in fill_database. Database not updated" return if not version and not uvfits_download_check: print "WARNING: version not defined in fill_database. Database not updated" return if not subversion and not uvfits_download_check: print "WARNING: subversion not defined in fill_database. Database not updated" return if not save_paths: print "WARNING: save_paths not defined in fill_database. Database not updated" return if not cotter_version and not uvfits_download_check: print "WARNING: cotter_version not defined in fill_database. Database not updated" return iteration = 0 for obsid in obs_chunk: save_path = save_paths[iteration] + obsid + '/' iteration = iteration + 1 #Check to make sure the uvfits and metafits specified exist if not os.path.isfile(save_path + obsid + '.uvfits'): print "ERROR: " + save_path + obsid + ".uvfits does not exist! Database not updated" #sys.exit(1) return # Was there a reason sys.exit(1) was used instead? I don't think this should be a fatal error -RB, 10/16 if not os.path.isfile(save_path + obsid + '.metafits'): print "WARNING: " + save_path + obsid + ".metafits does not exist! Database not updated" return #Open up the metafits file that was made with the uvfits file (assumes they are in the same location) metafits_file = save_path + obsid + '.metafits' hdu_list_metafits = fits.open(metafits_file) header_metafits = hdu_list_metafits[0].header #Get the frequency center and bandwidth (assumes contiguous frequency channels) freq_cent = header_metafits['FREQCENT'] bandwidth = header_metafits['BANDWDTH'] top_freq_mhz = "{0:.2f}".format(freq_cent + bandwidth/2) bottom_freq_mhz = "{0:.2f}".format(freq_cent - bandwidth/2) #Close the metafits file hdu_list_metafits.close() #Get the time for the timestamp in UTC timestamp = str(datetime.datetime.utcnow()) #Check to make sure that a similar uvfits file does not already exist, throw warning if it does. cur.execute("SELECT uvfits.obsid FROM uvfits WHERE (obsid,version,subversion,cotter_version,bottom_freq_mhz,top_freq_mhz)=(%s,%s,%s,%s,%s,%s);", \ (obsid,version,subversion,cotter_version,bottom_freq_mhz,top_freq_mhz)) if cur.fetchall(): print "WARNING: A uvfits file for obsid " + obsid + ", version " + version + ", subversion " + subversion + \ ", cotter " + cotter_version + ", and frequency range " + bottom_freq_mhz + "-" + top_freq_mhz + " already exists." #Create the database row, and fill it with the inputs. cur.execute("INSERT INTO uvfits(obsid,version,subversion,path,cotter_version,timestamp,comment,bottom_freq_mhz,top_freq_mhz) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);", \ (obsid,version,subversion,save_path + obsid + '.uvfits',cotter_version,timestamp,db_comment,bottom_freq_mhz,top_freq_mhz)) #Commit all the cur.execute, and close the connection. conn.commit() cur.close() conn.close() #Print completion message print "Filled the uvfits table in the mwa_qc database with the current uvfits information." #******************************** #******************************** #Module for deleting gpubox files after the uvfits creation. Will check to see if a uvfits file #exists before deletion def delete_gpubox(obs_chunk,save_paths): iteration = 0 gpubox_flag = False for obsid in obs_chunk: save_path = save_paths[iteration] iteration = iteration + 1 #Perform check to make sure essential information is known about the uvfits file if not obsid: print "WARNING: obsid not defined in delete_gpubox. Gpubox files not deleted" return if not save_path: print "WARNING: save_path not defined in delete_gpubox. Gpubox files not deleted" return #If the uvfits file does not exist with the gpubox files, do not delete the gpubox files if not os.path.isfile(save_path + obsid + '/' + obsid + '.uvfits'): print "WARNING: uvfits file does not exist in the directory with the gpubox files. Gpubox files not deleted" return directory_contents = os.listdir(save_path + obsid) for filename in directory_contents: if filename.endswith("_00.fits") or filename.endswith("_01.fits") or filename.endswith('.mwaf'): os.remove(save_path + obsid + '/' + filename) gpubox_flag = True #If the gpubox files do not exist, exit module if not gpubox_flag: print "WARNING: there are not gpubox files to delete in " + save_path + " for obsid " + obsid return else: print "Gpubox files in " + save_path + " for obsid " + obsid + " have been deleted." #******************************** if __name__ == '__main__': main()
EoRImagingREPO_NAMEFHDPATH_START.@FHD_extracted@FHD-master@data_download.py@.PATH_END.py
{ "filename": "info_theory.py", "repo_name": "astropy/astropy", "repo_path": "astropy_extracted/astropy-main/astropy/stats/info_theory.py", "type": "Python" }
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple functions for model selection. """ from __future__ import annotations import numpy as np __all__ = [ "akaike_info_criterion", "akaike_info_criterion_lsq", "bayesian_info_criterion", "bayesian_info_criterion_lsq", ] __doctest_requires__ = { "bayesian_info_criterion_lsq": ["scipy"], "akaike_info_criterion_lsq": ["scipy"], } def bayesian_info_criterion( log_likelihood: float, n_params: int, n_samples: int, ) -> float: r"""Computes the Bayesian Information Criterion (BIC) given the log of the likelihood function evaluated at the estimated (or analytically derived) parameters, the number of parameters, and the number of samples. The BIC is usually applied to decide whether increasing the number of free parameters (hence, increasing the model complexity) yields significantly better fittings. The decision is in favor of the model with the lowest BIC. BIC is given as .. math:: \mathrm{BIC} = k \ln(n) - 2L, in which :math:`n` is the sample size, :math:`k` is the number of free parameters, and :math:`L` is the log likelihood function of the model evaluated at the maximum likelihood estimate (i. e., the parameters for which L is maximized). When comparing two models define :math:`\Delta \mathrm{BIC} = \mathrm{BIC}_h - \mathrm{BIC}_l`, in which :math:`\mathrm{BIC}_h` is the higher BIC, and :math:`\mathrm{BIC}_l` is the lower BIC. The higher is :math:`\Delta \mathrm{BIC}` the stronger is the evidence against the model with higher BIC. The general rule of thumb is: :math:`0 < \Delta\mathrm{BIC} \leq 2`: weak evidence that model low is better :math:`2 < \Delta\mathrm{BIC} \leq 6`: moderate evidence that model low is better :math:`6 < \Delta\mathrm{BIC} \leq 10`: strong evidence that model low is better :math:`\Delta\mathrm{BIC} > 10`: very strong evidence that model low is better For a detailed explanation, see [1]_ - [5]_. Parameters ---------- log_likelihood : float Logarithm of the likelihood function of the model evaluated at the point of maxima (with respect to the parameter space). n_params : int Number of free parameters of the model, i.e., dimension of the parameter space. n_samples : int Number of observations. Returns ------- bic : float Bayesian Information Criterion. Examples -------- The following example was originally presented in [1]_. Consider a Gaussian model (mu, sigma) and a t-Student model (mu, sigma, delta). In addition, assume that the t model has presented a higher likelihood. The question that the BIC is proposed to answer is: "Is the increase in likelihood due to larger number of parameters?" >>> from astropy.stats.info_theory import bayesian_info_criterion >>> lnL_g = -176.4 >>> lnL_t = -173.0 >>> n_params_g = 2 >>> n_params_t = 3 >>> n_samples = 100 >>> bic_g = bayesian_info_criterion(lnL_g, n_params_g, n_samples) >>> bic_t = bayesian_info_criterion(lnL_t, n_params_t, n_samples) >>> bic_g - bic_t # doctest: +FLOAT_CMP np.float64(2.1948298140119391) Therefore, there exist a moderate evidence that the increasing in likelihood for t-Student model is due to the larger number of parameters. References ---------- .. [1] Richards, D. Maximum Likelihood Estimation and the Bayesian Information Criterion. <https://hea-www.harvard.edu/astrostat/Stat310_0910/dr_20100323_mle.pdf> .. [2] Wikipedia. Bayesian Information Criterion. <https://en.wikipedia.org/wiki/Bayesian_information_criterion> .. [3] Origin Lab. Comparing Two Fitting Functions. <https://www.originlab.com/doc/Origin-Help/PostFit-CompareFitFunc> .. [4] Liddle, A. R. Information Criteria for Astrophysical Model Selection. 2008. <https://arxiv.org/pdf/astro-ph/0701113v2.pdf> .. [5] Liddle, A. R. How many cosmological parameters? 2008. <https://arxiv.org/pdf/astro-ph/0401198v3.pdf> """ return n_params * np.log(n_samples) - 2.0 * log_likelihood # NOTE: bic_t - bic_g doctest is skipped because it produced slightly # different result in arm64 and big-endian s390x CI jobs. def bayesian_info_criterion_lsq( ssr: float, n_params: int, n_samples: int, ) -> float: r""" Computes the Bayesian Information Criterion (BIC) assuming that the observations come from a Gaussian distribution. In this case, BIC is given as .. math:: \mathrm{BIC} = n\ln\left(\dfrac{\mathrm{SSR}}{n}\right) + k\ln(n) in which :math:`n` is the sample size, :math:`k` is the number of free parameters and :math:`\mathrm{SSR}` stands for the sum of squared residuals between model and data. This is applicable, for instance, when the parameters of a model are estimated using the least squares statistic. See [1]_ and [2]_. Parameters ---------- ssr : float Sum of squared residuals (SSR) between model and data. n_params : int Number of free parameters of the model, i.e., dimension of the parameter space. n_samples : int Number of observations. Returns ------- bic : float Examples -------- Consider the simple 1-D fitting example presented in the Astropy modeling webpage [3]_. There, two models (Box and Gaussian) were fitted to a source flux using the least squares statistic. However, the fittings themselves do not tell much about which model better represents this hypothetical source. Therefore, we are going to apply to BIC in order to decide in favor of a model. >>> import numpy as np >>> from astropy.modeling import models, fitting >>> from astropy.stats.info_theory import bayesian_info_criterion_lsq >>> # Generate fake data >>> np.random.seed(0) >>> x = np.linspace(-5., 5., 200) >>> y = 3 * np.exp(-0.5 * (x - 1.3)**2 / 0.8**2) >>> y += np.random.normal(0., 0.2, x.shape) >>> # Fit the data using a Box model. >>> # Bounds are not really needed but included here to demonstrate usage. >>> t_init = models.Trapezoid1D(amplitude=1., x_0=0., width=1., slope=0.5, ... bounds={"x_0": (-5., 5.)}) >>> fit_t = fitting.LevMarLSQFitter() >>> t = fit_t(t_init, x, y) >>> # Fit the data using a Gaussian >>> g_init = models.Gaussian1D(amplitude=1., mean=0, stddev=1.) >>> fit_g = fitting.LevMarLSQFitter() >>> g = fit_g(g_init, x, y) >>> # Compute the mean squared errors >>> ssr_t = np.sum((t(x) - y)*(t(x) - y)) >>> ssr_g = np.sum((g(x) - y)*(g(x) - y)) >>> # Compute the bics >>> bic_t = bayesian_info_criterion_lsq(ssr_t, 4, x.shape[0]) >>> bic_g = bayesian_info_criterion_lsq(ssr_g, 3, x.shape[0]) >>> bic_t - bic_g # doctest: +SKIP 30.644474706065466 Hence, there is a very strong evidence that the Gaussian model has a significantly better representation of the data than the Box model. This is, obviously, expected since the true model is Gaussian. References ---------- .. [1] Wikipedia. Bayesian Information Criterion. <https://en.wikipedia.org/wiki/Bayesian_information_criterion> .. [2] Origin Lab. Comparing Two Fitting Functions. <https://www.originlab.com/doc/Origin-Help/PostFit-CompareFitFunc> .. [3] Astropy Models and Fitting <https://docs.astropy.org/en/stable/modeling> """ return bayesian_info_criterion( -0.5 * n_samples * np.log(ssr / n_samples), n_params, n_samples ) def akaike_info_criterion( log_likelihood: float, n_params: int, n_samples: int, ) -> float: r""" Computes the Akaike Information Criterion (AIC). Like the Bayesian Information Criterion, the AIC is a measure of relative fitting quality which is used for fitting evaluation and model selection. The decision is in favor of the model with the lowest AIC. AIC is given as .. math:: \mathrm{AIC} = 2(k - L) in which :math:`n` is the sample size, :math:`k` is the number of free parameters, and :math:`L` is the log likelihood function of the model evaluated at the maximum likelihood estimate (i. e., the parameters for which L is maximized). In case that the sample size is not "large enough" a correction is applied, i.e. .. math:: \mathrm{AIC} = 2(k - L) + \dfrac{2k(k+1)}{n - k - 1} Rule of thumb [1]_: :math:`\Delta\mathrm{AIC}_i = \mathrm{AIC}_i - \mathrm{AIC}_{min}` :math:`\Delta\mathrm{AIC}_i < 2`: substantial support for model i :math:`3 < \Delta\mathrm{AIC}_i < 7`: considerably less support for model i :math:`\Delta\mathrm{AIC}_i > 10`: essentially none support for model i in which :math:`\mathrm{AIC}_{min}` stands for the lower AIC among the models which are being compared. For detailed explanations see [1]_-[6]_. Parameters ---------- log_likelihood : float Logarithm of the likelihood function of the model evaluated at the point of maxima (with respect to the parameter space). n_params : int Number of free parameters of the model, i.e., dimension of the parameter space. n_samples : int Number of observations. Returns ------- aic : float Akaike Information Criterion. Examples -------- The following example was originally presented in [2]_. Basically, two models are being compared. One with six parameters (model 1) and another with five parameters (model 2). Despite of the fact that model 2 has a lower AIC, we could decide in favor of model 1 since the difference (in AIC) between them is only about 1.0. >>> n_samples = 121 >>> lnL1 = -3.54 >>> n1_params = 6 >>> lnL2 = -4.17 >>> n2_params = 5 >>> aic1 = akaike_info_criterion(lnL1, n1_params, n_samples) >>> aic2 = akaike_info_criterion(lnL2, n2_params, n_samples) >>> aic1 - aic2 # doctest: +FLOAT_CMP 0.9551029748283746 Therefore, we can strongly support the model 1 with the advantage that it has more free parameters. References ---------- .. [1] Cavanaugh, J. E. Model Selection Lecture II: The Akaike Information Criterion. <http://machinelearning102.pbworks.com/w/file/fetch/47699383/ms_lec_2_ho.pdf> .. [2] Mazerolle, M. J. Making sense out of Akaike's Information Criterion (AIC): its use and interpretation in model selection and inference from ecological data. .. [3] Wikipedia. Akaike Information Criterion. <https://en.wikipedia.org/wiki/Akaike_information_criterion> .. [4] Origin Lab. Comparing Two Fitting Functions. <https://www.originlab.com/doc/Origin-Help/PostFit-CompareFitFunc> .. [5] Liddle, A. R. Information Criteria for Astrophysical Model Selection. 2008. <https://arxiv.org/pdf/astro-ph/0701113v2.pdf> .. [6] Liddle, A. R. How many cosmological parameters? 2008. <https://arxiv.org/pdf/astro-ph/0401198v3.pdf> """ # Correction in case of small number of observations if n_samples / float(n_params) >= 40.0: aic = 2.0 * (n_params - log_likelihood) else: aic = 2.0 * (n_params - log_likelihood) + 2.0 * n_params * (n_params + 1.0) / ( n_samples - n_params - 1.0 ) return aic def akaike_info_criterion_lsq( ssr: float, n_params: int, n_samples: int, ) -> float: r""" Computes the Akaike Information Criterion assuming that the observations are Gaussian distributed. In this case, AIC is given as .. math:: \mathrm{AIC} = n\ln\left(\dfrac{\mathrm{SSR}}{n}\right) + 2k In case that the sample size is not "large enough", a correction is applied, i.e. .. math:: \mathrm{AIC} = n\ln\left(\dfrac{\mathrm{SSR}}{n}\right) + 2k + \dfrac{2k(k+1)}{n-k-1} in which :math:`n` is the sample size, :math:`k` is the number of free parameters and :math:`\mathrm{SSR}` stands for the sum of squared residuals between model and data. This is applicable, for instance, when the parameters of a model are estimated using the least squares statistic. Parameters ---------- ssr : float Sum of squared residuals (SSR) between model and data. n_params : int Number of free parameters of the model, i.e., the dimension of the parameter space. n_samples : int Number of observations. Returns ------- aic : float Akaike Information Criterion. Examples -------- This example is based on Astropy Modeling webpage, Compound models section. >>> import numpy as np >>> from astropy.modeling import models, fitting >>> from astropy.stats.info_theory import akaike_info_criterion_lsq >>> np.random.seed(42) >>> # Generate fake data >>> g1 = models.Gaussian1D(.1, 0, 0.2) # changed this to noise level >>> g2 = models.Gaussian1D(.1, 0.3, 0.2) # and added another Gaussian >>> g3 = models.Gaussian1D(2.5, 0.5, 0.1) >>> x = np.linspace(-1, 1, 200) >>> y = g1(x) + g2(x) + g3(x) + np.random.normal(0., 0.2, x.shape) >>> # Fit with three Gaussians >>> g3_init = (models.Gaussian1D(.1, 0, 0.1) ... + models.Gaussian1D(.1, 0.2, 0.15) ... + models.Gaussian1D(2.4, .4, 0.1)) >>> fitter = fitting.LevMarLSQFitter() >>> g3_fit = fitter(g3_init, x, y) >>> # Fit with two Gaussians >>> g2_init = (models.Gaussian1D(.1, 0, 0.1) + ... models.Gaussian1D(2, 0.5, 0.1)) >>> g2_fit = fitter(g2_init, x, y) >>> # Fit with only one Gaussian >>> g1_init = models.Gaussian1D(amplitude=2., mean=0.3, stddev=.5) >>> g1_fit = fitter(g1_init, x, y) >>> # Compute the mean squared errors >>> ssr_g3 = np.sum((g3_fit(x) - y)**2.0) >>> ssr_g2 = np.sum((g2_fit(x) - y)**2.0) >>> ssr_g1 = np.sum((g1_fit(x) - y)**2.0) >>> akaike_info_criterion_lsq(ssr_g3, 9, x.shape[0]) # doctest: +FLOAT_CMP np.float64(-634.5257517810961) >>> akaike_info_criterion_lsq(ssr_g2, 6, x.shape[0]) # doctest: +FLOAT_CMP np.float64(-662.83834510232043) >>> akaike_info_criterion_lsq(ssr_g1, 3, x.shape[0]) # doctest: +FLOAT_CMP np.float64(-647.47312032659499) Hence, from the AIC values, we would prefer to choose the model g2_fit. However, we can considerably support the model g3_fit, since the difference in AIC is about 2.4. We should reject the model g1_fit. References ---------- .. [1] Akaike Information Criterion. <https://en.wikipedia.org/wiki/Akaike_information_criterion> .. [2] Origin Lab. Comparing Two Fitting Functions. <https://www.originlab.com/doc/Origin-Help/PostFit-CompareFitFunc> """ return akaike_info_criterion( -0.5 * n_samples * np.log(ssr / n_samples), n_params, n_samples )
astropyREPO_NAMEastropyPATH_START.@astropy_extracted@astropy-main@astropy@stats@info_theory.py@.PATH_END.py
{ "filename": "special_parse.py", "repo_name": "gmbrandt/HTOF", "repo_path": "HTOF_extracted/HTOF-main/htof/special_parse.py", "type": "Python" }
import numpy as np import warnings import pkg_resources from pandas import DataFrame, Series from shutil import copy from copy import deepcopy from astropy.time import Time from astropy.coordinates import Angle from astropy import units as u from scipy import stats, special from astropy.table import Table from htof.fit import AstrometricFitter from htof.parse import HipparcosRereductionJavaTool, HipparcosRereductionDVDBook, DataParser class Hipparcos2Recalibrated(HipparcosRereductionJavaTool): """ A parser class which re-calibrates the hipparcos 2 data according to Brandt et al. 2022 This is a monstrous parser class because well it is doing a lot. Note that this "Parser" class actually refits the data. This is programmatically poorly set up, in the sense that we parse the data and fit it, mixing this class with an AstrometricFitter class... For now, this is OK because the objective of this class is mainly so other users can save and inspect the recalibrated hipparcos 2 IAD. """ EPOCHREJECTLIST = Table.read(pkg_resources.resource_filename('htof', 'data/epoch_reject_shortlist.csv'), format='ascii') def __init__(self, scan_angle=None, epoch=None, residuals=None, inverse_covariance_matrix=None, along_scan_errs=None, meta=None, residual_offset=0.141, cosmic_dispersion=2.25): super(Hipparcos2Recalibrated, self).__init__(scan_angle=scan_angle, along_scan_errs=along_scan_errs, epoch=epoch, residuals=residuals, inverse_covariance_matrix=inverse_covariance_matrix, meta=meta) self.residual_offset = residual_offset self.cosmic_dispersion = cosmic_dispersion self.recalibrated_header = None self.recalibrated_data = None def parse(self, star_id, intermediate_data_directory, attempt_adhoc_rejection=True, reject_known=True, **kwargs): # important that the 2007 error inflation is turned off (error_inflate=False) header, raw_data = super(Hipparcos2Recalibrated, self).parse(star_id, intermediate_data_directory, error_inflate=False, attempt_adhoc_rejection=attempt_adhoc_rejection, reject_known=reject_known, **kwargs) apply_calibrations = True if not (self.meta['catalog_soltype'] == 5 or self.meta['catalog_soltype'] == 7 or self.meta['catalog_soltype'] == 9): warnings.warn(f'This source has a solution type of {self.meta["catalog_soltype"]}. ' f'htof will only recalibrate 5, 7, and 9 parameter solutions currently. ' f'No recalibration will be performed.') apply_calibrations = False if attempt_adhoc_rejection is False or reject_known is False: warnings.warn('We have not tested recalibration without rejecting any of the flagged or bugged ' 'observations. No recalibration will be performed.') apply_calibrations = False if apply_calibrations: # apply the calibrations self.residuals += self.residual_offset # note that this modifies the raw_data column also. self.along_scan_errs = np.sqrt(self.along_scan_errs**2 + self.cosmic_dispersion**2) self.calculate_inverse_covariance_matrices() # munge the parallax factors into the correct form. Note that we are using # the parallax factors from the catalog here to keep everything consistent. ra_motion, dec_motion = to_ra_dec_basis(self.parallax_factors.values, self.scan_angle.values) parallactic_perturbations = {'ra_plx': ra_motion, 'dec_plx': dec_motion} # refit the data, calculate the new residuals, and parameters. fit_degree = {5: 1, 7: 2, 9: 3}[int(self.meta['catalog_soltype'])] fitter = AstrometricFitter(inverse_covariance_matrices=self.inverse_covariance_matrix, epoch_times=Time(Time(self.julian_day_epoch(), format='jd'), format='jyear').value, central_epoch_dec=1991.25, central_epoch_ra=1991.25, fit_degree=fit_degree, use_parallax=True, parallactic_pertubations=parallactic_perturbations) # get residuals in ra and dec. ra = Angle(self.residuals.values * np.sin(self.scan_angle.values), unit='mas') dec = Angle(self.residuals.values * np.cos(self.scan_angle.values), unit='mas') # fit the residuals coeffs, errors, Q, new_residuals = fitter.fit_line(ra.mas, dec.mas, return_all=True) # compute the along-scan residuals new_residuals = to_along_scan_basis(new_residuals[:, 0], new_residuals[:, 1], self.scan_angle.values) self.residuals = Series(new_residuals, index=self.residuals.index) """ update the header with the new statistics """ ntransits, nparam = len(self), int(self.meta['catalog_soltype']) header['second']['NOB'] = len(self) header['second']['NR'] = 0 # because we automatically remove any "flagged as rejected" observations. header['first']['F1'] = 0 header['first']['NRES'] = len(self) header['first']['F2'] = special.erfcinv(stats.chi2.sf(Q, ntransits - nparam)*2)*np.sqrt(2) if np.isfinite(header['first']['F2']): header['first']['F2'] = np.round(header['first']['F2'], 4) # update the best fit parameters with the new values # dpmRA dpmDE e_dpmRA e_dpmDE ddpmRA ddpmDE e_ddpmRA e_ddpmDE for i, key, dp, in zip(np.arange(nparam), ['Plx', 'RAdeg', 'DEdeg', 'pm_RA', 'pm_DE', 'dpmRA', 'dpmDE', 'ddpmRA', 'ddpmDE'], [2, 8, 8, 2, 2, 2, 2, 2, 2]): if key != 'RAdeg' and key != 'DEdeg': header['third'][key] = np.round(header['third'][key] + coeffs[i], dp) else: # convert the perturbation from mas to degrees. header['third'][key] = np.round(header['third'][key] + (coeffs[i] * u.mas).to(u.degree).value, dp) # update the errors with the new errors for i, key, dp, in zip(np.arange(nparam), ['e_Plx', 'e_RA', 'e_DE', 'e_pmRA', 'e_pmDE', 'e_dpmRA', 'e_dpmDE', 'e_ddpmRA', 'e_ddpmDE'], [2, 2, 2, 2, 2, 2, 2, 2, 2]): header['third'][key] = np.round(errors[i], dp) # save the modified header to the class, because these will be # used by self.write_as_javatool_format() self.recalibrated_header = deepcopy(header) """ update the raw_data columns with the new data. Note that rejected/bugged epochs are already taken care of. """ # data order in Java tool data: IORB EPOCH PARF CPSI SPSI RES SRES recalibrated_data = DataFrame({'1': self._iorb, '2': self._epoch - 1991.25, '3': self.parallax_factors, '4': self._cpsi, '5': self._spsi, '6': np.round(self.residuals.values, 3), '7': np.round(self.along_scan_errs.values, 3)}) self.recalibrated_data = recalibrated_data header, raw_data = None, None # the raw header and raw data have been modified, so clear them. return header, raw_data def write_as_javatool_format(self, path: str): """ Variant of the .write() method that is specially for this Parser. It writes out the fixed data with the exact same format as the input JavaTool IAD (i.e., the .d files). We recommend using the normal .write() format. This method is for users who do not want to adopt the htof file format output by the normal .write() format. :param: path: path to write the file to. filename should end with .d . ".d" is the same file ending as the java tool IAD. But in principle, most common ascii file extensions should work (e.g., ".txt" etc). """ if self.recalibrated_header is None or self.recalibrated_data is None: warnings.warn('This source was NOT recalibrated, see earlier warnings as to why. Will not save any ' f'output file at {path} because no recalibration was done.') return None # order of the header values: ks1 = ['HIP', 'MCE', 'NRES', 'NC', 'isol_n', 'SCE', 'F2', 'F1'] ks2 = ['Hp', 'B-V', 'VarAnn', 'NOB', 'NR'] ks3 = ['RAdeg', 'DEdeg', 'Plx', 'pm_RA', 'pm_DE', 'e_RA', 'e_DE', 'e_Plx', 'e_pmRA', 'e_pmDE', 'dpmRA', 'dpmDE', 'e_dpmRA', 'e_dpmDE', 'ddpmRA', 'ddpmDE', 'e_ddpmRA', 'e_ddpmDE', 'upsRA', 'upsDE', 'e_upsRA', 'e_upsDE', 'var'] # byte entries of each header value. Stored as (start, stop) inclusive intervals. # the exact bytes are stored, according to the IAD readme, so that the output format is exactly the same. bs1 = [(3, 8), (10, 15), (17, 19), (22, 22), (25, 27), (32, 35), (37, 42), (44, 45)] bs2 = [(3, 9), (11, 16), (18, 18), (25, 27), (29, 31)] bs3 = [(3, 14), (16, 27), (29, 36), (38, 45), (47, 54), (56, 61), (63, 68), (70, 75), (77, 82), (84, 89), (91, 96), (98, 103), (105, 110), (114, 119), (123, 128), (131, 136), (139, 144), (149, 154), (159, 164), (167, 172), (175, 180), (184, 189), (193, 198)] header_template_fpath = pkg_resources.resource_filename('htof', 'data/hip2_recalibrated_header.txt') copy(header_template_fpath, path) # copy the template file to the output path. # populate the header lines. f = open(path, 'r') lines = f.readlines() for idx, hline, ks, bs, line_length in zip([6, 8, 10], ['first', 'second', 'third'], [ks1, ks2, ks3], [bs1, bs2, bs3], [48, 34, 201]): matter = ["#"] + [" "] * (line_length - 1) # strings are immutable in python. This is a gross solution to get past that. for key, byte_start_stop in zip(ks, bs): minn, maxx = min(byte_start_stop)-1, max(byte_start_stop)-1 # -1 because python indexes from 0. final_len = 1 + maxx-minn value = str(self.recalibrated_header[hline][key]) matter[minn: maxx + 1] = list(value[:final_len].ljust(final_len, " ")) matter = "".join(matter) # convert to a string instead of a list of characters. lines[idx] = matter + '\n' lines[idx] = lines[idx].replace('nan', '---') lines[-1] += '\n' # populate the IAD entries iad_bytes = [(3, 6), (8, 14), (16, 22), (24, 30), (32, 38), (42, 46), (49, 53)] significance = [None, 4, 4, 4, 4, 2, 2] # None means values in that column will not be rounded. # line_length = 56 for line in self.recalibrated_data.to_numpy(): matter = [" "] * line_length # strings are immutable in python. This is a gross solution to get past that. for col, value, byte_start_stop, sig in zip(np.arange(7), line, iad_bytes, significance): minn, maxx = min(byte_start_stop) - 1, max(byte_start_stop) - 1 # -1 because python indexes from 0. final_len = 1 + maxx - minn if col != 0: # left justify every column except the orbit column. Round floats also. value = value if sig is None else np.round(value, sig) value = str(value) if value < 0 else ' ' + str(value) # left pad with a space if it is positive. matter[minn: maxx + 1] = list(value[:final_len].ljust(final_len, " ")) else: # right justify the orbit column value = str(int(value)) matter[minn: maxx + 1] = list(value[:final_len].rjust(final_len, " ")) matter = "".join(matter) + '\n' # convert to a string instead of a list of characters. lines.append(matter) # write it out to file. f = open(path, 'w') f.writelines(lines) f.close() return None class Hipparcos2ParserFactory: """ A factory method for HipparcosRereductionDVDBook and HipparcosRereductionJavaTool. It detects which format the IAD is in, then chooses and returns the appropriate parser. """ @staticmethod def get_appropriate_parser(filepath): if filepath == '': return HipparcosRereductionJavaTool datatype = get_datatype(filepath) if datatype == 'hip2dvd': return HipparcosRereductionDVDBook if datatype == 'hip2javatool': return HipparcosRereductionJavaTool @classmethod def parse_and_instantiate(cls, star_id: str, intermediate_data_directory: str, **kwargs): filepath, msg = DataParser.get_intermediate_data_file_path(star_id, intermediate_data_directory) CorrectDataParser = cls.get_appropriate_parser(filepath) return CorrectDataParser.parse_and_instantiate(star_id, intermediate_data_directory, **kwargs) def to_ra_dec_basis(value, scan_angle): """ Convert values (e.g. residuals) along the direction of the scan to the same value in RA and Dec. I.e. assume the value has a zero across_scan component and all of the value is in the along-scan direction, then convert that value to a vector in RA and Dec. these maths are just from https://en.wikipedia.org/wiki/Rotation_of_axes . """ dec_value, ra_value = value * np.cos(scan_angle), value * np.sin(scan_angle) return ra_value, dec_value def to_along_scan_basis(ra_value, dec_value, scan_angle): """ Convert values (e.g. residuals) in RA and Dec to the same value along the direction of the scan. I.e convert from RA, DEC to Along-scan , Across-scan basis, then keep only the along-scan component. these maths are just from https://en.wikipedia.org/wiki/Rotation_of_axes . note that the inputs ra_value and dec_value may have nonzero across scan components. This function will zero out the cross-scan component. to_ra_dec_basis and to_along_scan_basis() are ONLY inverse transforms for data that has components solely in the across-scan direction. """ along_scan_value = dec_value * np.cos(scan_angle) + ra_value * np.sin(scan_angle) return along_scan_value def get_datatype(filepath): with open(filepath) as f: lines = f.readlines() if 'This file contains residual records' in lines[0]: datatype = 'hip2javatool' else: datatype = 'hip2dvd' return datatype
gmbrandtREPO_NAMEHTOFPATH_START.@HTOF_extracted@HTOF-main@htof@special_parse.py@.PATH_END.py
{ "filename": "lonlat.py", "repo_name": "NeoGeographyToolkit/StereoPipeline", "repo_path": "StereoPipeline_extracted/StereoPipeline-master/graveyard/ngt_utils/lonlat.py", "type": "Python" }
## __BEGIN_LICENSE__ ## Copyright (C) 2006-2010 United States Government as represented by ## the Administrator of the National Aeronautics and Space Administration ## All Rights Reserved. ## __END_LICENSE__ import sys import math import numpy def w2e_deg(lon): '''Convert positive-west longitude to positive-east in the range [-180,180).''' lon = -lon if lon >= 180: lon -= 360 if lon <= -180: lon += 360 return lon def pm180(lon): '''Convert latitudes to the range [-180,180).''' if lon >= 180: lon -= 360 return lon def lonlat_to_vec(lon, lat=None): if lat is None: lon, lat = lon x = math.cos(lat*math.pi/180) * math.cos(lon*math.pi/180) y = math.cos(lat*math.pi/180) * math.sin(lon*math.pi/180) z = math.sin(lat*math.pi/180) return numpy.array((x,y,z)) def vec_to_lonlat(vec): x, y, z = vec lat = 180/math.pi*math.atan2(z,math.sqrt(x**2+y**2)) lon = 180/math.pi*math.atan2(y,x) return numpy.array((lon,lat)) def vec_norm(vec): return math.sqrt(numpy.dot(vec,vec)) def heading(pt1,pt2): '''Compute the heading from point 1 to point 2, in expressed as (lon,lat) in degrees.''' lon1,lat1 = pt1[0:2] lon2,lat2 = pt2[0:2] x1 = math.cos(lat1*math.pi/180) * math.cos(lon1*math.pi/180) y1 = math.cos(lat1*math.pi/180) * math.sin(lon1*math.pi/180) z1 = math.sin(lat1*math.pi/180) x2 = math.cos(lat2*math.pi/180) * math.cos(lon2*math.pi/180) y2 = math.cos(lat2*math.pi/180) * math.sin(lon2*math.pi/180) z2 = math.sin(lat2*math.pi/180) x1 = x2 + 0.0001 * (x1-x2) y1 = y2 + 0.0001 * (y1-y2) z1 = z2 + 0.0001 * (z1-z2) lat1 = 180/math.pi*math.atan2(z1,math.sqrt(x1*x1+y1*y1)) lon1 = 180/math.pi*math.atan2(y1,x1) return 90-180/math.pi*math.atan2(lat2-lat1,(lon2-lon1)*math.cos(lat2*math.pi/180)) def interpolate_lonlat(ll1,ll2,n): '''Returns a list of points interpolating between two (lon,lat) points along a great circle. If the third argument is an integer, this function returns that many points, uniformly spaced. If the third argument is a list, the elements are interpreted as blend parameters, with 0 representing the first point and 1 representing the second point. Passing in blend parameters outside the range [0,1] will result in extrapolation.''' if n.__class__ == list: alphas = n else: alphas = [float(i)/(n-1) for i in range(n)] lon1 = math.pi*ll1[0]/180 lat1 = math.pi*ll1[1]/180 lon2 = math.pi*ll2[0]/180 lat2 = math.pi*ll2[1]/180 v1 = numpy.array([math.cos(lon1)*math.cos(lat1), math.sin(lon1)*math.cos(lat1), math.sin(lat1)]) assert abs(numpy.dot(v1,v1)-1) < 1e-8 v2 = numpy.array([math.cos(lon2)*math.cos(lat2), math.sin(lon2)*math.cos(lat2), math.sin(lat2)]) assert abs(numpy.dot(v2,v2)-1) < 1e-8 axis = numpy.cross(v1,v2) assert abs(numpy.dot(v1,axis)) < 1e-8 assert abs(numpy.dot(v2,axis)) < 1e-8 axis = axis / math.sqrt(numpy.dot(axis,axis)) assert abs(numpy.dot(v1,axis)) < 1e-8 assert abs(numpy.dot(v2,axis)) < 1e-8 assert abs(numpy.dot(axis,axis)-1) < 1e-8 angle = math.acos(numpy.dot(v1,v2)) ovec = numpy.cross(v1,axis) assert abs(numpy.dot(v1,ovec)) < 1e-8 assert abs(numpy.dot(axis,ovec)) < 1e-8 assert abs(numpy.dot(ovec,ovec)-1) < 1e-8 M = numpy.array([v1,axis,ovec]) assert numpy.allclose(numpy.dot(M,M.T),numpy.array([[1,0,0],[0,1,0],[0,0,1]])) values = [] for alpha in alphas: c = math.cos(angle*alpha) s = math.sin(angle*alpha) R = numpy.array([[c,0,s],[0,1,0],[-s,0,c]]) v = numpy.dot( numpy.dot( numpy.dot(M.T,R), M ), v1 ) lon = 180/math.pi*math.atan2(v[1],v[0]) lat = 180/math.pi*math.atan2(v[2],math.sqrt(v[0]**2+v[1]**2)) values.append( (lon,lat) ) return values def dispatch_cmd(context, argv): '''A helper for building command-line tools.''' commands = {} for name, value in context.iteritems(): if name.startswith('cmd_') and callable(value): commands[name[4:]] = value if len(argv) < 2 or argv[1] not in commands: if context['__doc__']: print context['__doc__'] + '\n' print 'Usage: ' + sys.argv[0] + ' <command>' + '\n' print 'Commands: ' for command, func in commands.iteritems(): print ' %s : %s' % (command, func.__doc__) sys.exit(1) commands[argv[1]](*argv[2:])
NeoGeographyToolkitREPO_NAMEStereoPipelinePATH_START.@StereoPipeline_extracted@StereoPipeline-master@graveyard@ngt_utils@lonlat.py@.PATH_END.py
{ "filename": "activations.py", "repo_name": "fchollet/keras", "repo_path": "keras_extracted/keras-master/keras/src/activations/activations.py", "type": "Python" }
from keras.src import backend from keras.src import ops from keras.src.api_export import keras_export @keras_export("keras.activations.relu") def relu(x, negative_slope=0.0, max_value=None, threshold=0.0): """Applies the rectified linear unit activation function. With default values, this returns the standard ReLU activation: `max(x, 0)`, the element-wise maximum of 0 and the input tensor. Modifying default parameters allows you to use non-zero thresholds, change the max value of the activation, and to use a non-zero multiple of the input for values below the threshold. Examples: >>> x = [-10, -5, 0.0, 5, 10] >>> keras.activations.relu(x) [ 0., 0., 0., 5., 10.] >>> keras.activations.relu(x, negative_slope=0.5) [-5. , -2.5, 0. , 5. , 10. ] >>> keras.activations.relu(x, max_value=5.) [0., 0., 0., 5., 5.] >>> keras.activations.relu(x, threshold=5.) [-0., -0., 0., 0., 10.] Args: x: Input tensor. negative_slope: A `float` that controls the slope for values lower than the threshold. max_value: A `float` that sets the saturation threshold (the largest value the function will return). threshold: A `float` giving the threshold value of the activation function below which values will be damped or set to zero. Returns: A tensor with the same shape and dtype as input `x`. """ if backend.any_symbolic_tensors((x,)): return ReLU( negative_slope=negative_slope, max_value=max_value, threshold=threshold, )(x) return ReLU.static_call( x, negative_slope=negative_slope, max_value=max_value, threshold=threshold, ) class ReLU(ops.Operation): def __init__( self, negative_slope=0.0, max_value=None, threshold=0.0, name=None ): super().__init__(name=name) self.negative_slope = negative_slope self.max_value = max_value self.threshold = threshold def call(self, x): return self.static_call( x, negative_slope=self.negative_slope, max_value=self.max_value, threshold=self.threshold, ) def compute_output_spec(self, x): return backend.KerasTensor(x.shape, x.dtype) @staticmethod def static_call(x, negative_slope=0.0, max_value=None, threshold=0.0): x = backend.convert_to_tensor(x) if negative_slope != 0.0: if max_value is None and threshold == 0: return backend.nn.leaky_relu(x, negative_slope=negative_slope) if threshold != 0: negative_part = backend.nn.relu(-x + threshold) else: negative_part = backend.nn.relu(-x) else: negative_part = 1 clip_max = max_value is not None if threshold != 0: # computes x for x > threshold else 0 threshold = ops.cast(threshold, dtype=x.dtype) x = x * backend.cast( backend.numpy.greater(x, threshold), dtype=x.dtype ) elif max_value == 6: # if no threshold, then can use nn.relu6 native op for performance x = backend.nn.relu6(x) clip_max = False else: x = backend.nn.relu(x) if clip_max: min_value = ops.cast(0.0, dtype=x.dtype) max_value = ops.cast(max_value, dtype=x.dtype) x = backend.numpy.clip(x, min_value, max_value) if negative_slope != 0.0: x -= negative_slope * negative_part return x @keras_export("keras.activations.leaky_relu") def leaky_relu(x, negative_slope=0.2): """Leaky relu activation function. Args: x: Input tensor. negative_slope: A `float` that controls the slope for values lower than the threshold. """ return ops.leaky_relu(x, negative_slope=negative_slope) @keras_export("keras.activations.relu6") def relu6(x): """Relu6 activation function. It's the ReLU function, but truncated to a maximum value of 6. Args: x: Input tensor. """ return ops.relu6(x) @keras_export("keras.activations.softmax") def softmax(x, axis=-1): """Softmax converts a vector of values to a probability distribution. The elements of the output vector are in range `[0, 1]` and sum to 1. Each input vector is handled independently. The `axis` argument sets which axis of the input the function is applied along. Softmax is often used as the activation for the last layer of a classification network because the result could be interpreted as a probability distribution. The softmax of each vector x is computed as `exp(x) / sum(exp(x))`. The input values in are the log-odds of the resulting probability. Args: x: Input tensor. axis: Integer, axis along which the softmax is applied. """ output = ops.softmax(x, axis=axis) # Cache the logits to use for crossentropy loss. try: output._keras_logits = x except AttributeError: # We're dealing with a C-type. pass return output @keras_export("keras.activations.elu") def elu(x, alpha=1.0): """Exponential Linear Unit. The exponential linear unit (ELU) with `alpha > 0` is defined as: - `x` if `x > 0` - alpha * `exp(x) - 1` if `x < 0` ELUs have negative values which pushes the mean of the activations closer to zero. Mean activations that are closer to zero enable faster learning as they bring the gradient closer to the natural gradient. ELUs saturate to a negative value when the argument gets smaller. Saturation means a small derivative which decreases the variation and the information that is propagated to the next layer. Args: x: Input tensor. Reference: - [Clevert et al., 2016](https://arxiv.org/abs/1511.07289) """ return ops.elu(x, alpha=alpha) @keras_export("keras.activations.selu") def selu(x): """Scaled Exponential Linear Unit (SELU). The Scaled Exponential Linear Unit (SELU) activation function is defined as: - `scale * x` if `x > 0` - `scale * alpha * (exp(x) - 1)` if `x < 0` where `alpha` and `scale` are pre-defined constants (`alpha=1.67326324` and `scale=1.05070098`). Basically, the SELU activation function multiplies `scale` (> 1) with the output of the `keras.activations.elu` function to ensure a slope larger than one for positive inputs. The values of `alpha` and `scale` are chosen so that the mean and variance of the inputs are preserved between two consecutive layers as long as the weights are initialized correctly (see `keras.initializers.LecunNormal` initializer) and the number of input units is "large enough" (see reference paper for more information). Args: x: Input tensor. Notes: - To be used together with the `keras.initializers.LecunNormal` initializer. - To be used together with the dropout variant `keras.layers.AlphaDropout` (rather than regular dropout). Reference: - [Klambauer et al., 2017](https://arxiv.org/abs/1706.02515) """ return ops.selu(x) @keras_export("keras.activations.softplus") def softplus(x): """Softplus activation function. It is defined as: `softplus(x) = log(exp(x) + 1)`. Args: x: Input tensor. """ return ops.softplus(x) @keras_export("keras.activations.softsign") def softsign(x): """Softsign activation function. Softsign is defined as: `softsign(x) = x / (abs(x) + 1)`. Args: x: Input tensor. """ return ops.softsign(x) @keras_export("keras.activations.soft_shrink") def soft_shrink(x, threshold=0.5): """Soft Shrink activation function. It is defined as: `soft_shrink(x) = x - threshold` if `x > threshold`, `soft_shrink(x) = x + threshold` if `x < -threshold`, `soft_shrink(x) = 0` otherwise. Args: x: Input tensor. threshold: Threshold value. Defaults to 0.5. """ return ops.soft_shrink(x, threshold=threshold) @keras_export("keras.activations.sparse_plus") def sparse_plus(x): """SparsePlus activation function. SparsePlus is defined as: `sparse_plus(x) = 0` for `x <= -1`. `sparse_plus(x) = (1/4) * (x + 1)^2` for `-1 < x < 1`. `sparse_plus(x) = x` for `x >= 1`. Args: x: Input tensor. """ return ops.sparse_plus(x) @keras_export(["keras.activations.silu", "keras.activations.swish"]) def silu(x): """Swish (or Silu) activation function. It is defined as: `swish(x) = x * sigmoid(x)`. The Swish (or Silu) activation function is a smooth, non-monotonic function that is unbounded above and bounded below. Args: x: Input tensor. Reference: - [Ramachandran et al., 2017](https://arxiv.org/abs/1710.05941) """ return ops.silu(x) @keras_export("keras.activations.squareplus") def squareplus(x, b=4): """Squareplus activation function. The Squareplus activation function is defined as: `f(x) = (x + sqrt(x^2 + b)) / 2` Where `b` is a smoothness parameter. Args: x: Input tensor. b: Smoothness parameter. Defaults to 4. Reference: - [Ramachandran et al., 2021](https://arxiv.org/abs/2112.11687) """ return ops.squareplus(x, b=b) @keras_export("keras.activations.gelu") def gelu(x, approximate=False): """Gaussian error linear unit (GELU) activation function. The Gaussian error linear unit (GELU) is defined as: `gelu(x) = x * P(X <= x)` where `P(X) ~ N(0, 1)`, i.e. `gelu(x) = 0.5 * x * (1 + erf(x / sqrt(2)))`. GELU weights inputs by their value, rather than gating inputs by their sign as in ReLU. Args: x: Input tensor. approximate: A `bool`, whether to enable approximation. Reference: - [Hendrycks et al., 2016](https://arxiv.org/abs/1606.08415) """ return ops.gelu(x, approximate=approximate) @keras_export("keras.activations.celu") def celu(x, alpha=1.0): """Continuously Differentiable Exponential Linear Unit. The CeLU activation function is defined as: `celu(x) = alpha * (exp(x / alpha) - 1) for x < 0`,`celu(x) = x for x >= 0`. where `alpha` is a scaling parameter that controls the activation's shape. Args: x: Input tensor. alpha: The α value for the CeLU formulation. Defaults to `1.0`. Reference: - [Barron, J. T., 2017](https://arxiv.org/abs/1704.07483) """ return ops.celu(x, alpha=alpha) @keras_export("keras.activations.glu") def glu(x, axis=-1): """Gated Linear Unit (GLU) activation function. The GLU activation function is defined as: `glu(x) = a * sigmoid(b)`, where `x` is split into two equal parts `a` and `b` along the given axis. Args: x: Input tensor. axis: The axis along which to split the input tensor. Defaults to `-1`. Reference: - [Dauphin et al., 2017](https://arxiv.org/abs/1612.08083) """ return ops.glu(x, axis=axis) @keras_export("keras.activations.tanh") def tanh(x): """Hyperbolic tangent activation function. It is defined as: `tanh(x) = sinh(x) / cosh(x)`, i.e. `tanh(x) = ((exp(x) - exp(-x)) / (exp(x) + exp(-x)))`. Args: x: Input tensor. """ return ops.tanh(x) @keras_export("keras.activations.tanh_shrink") def tanh_shrink(x): """Tanh shrink activation function. It is defined as: `f(x) = x - tanh(x)`. Args: x: Input tensor. """ return ops.tanh_shrink(x) @keras_export("keras.activations.hard_tanh") def hard_tanh(x): """HardTanh activation function. It is defined as: `hard_tanh(x) = -1 for x < -1`, `hard_tanh(x) = x for -1 <= x <= 1`, `hard_tanh(x) = 1 for x > 1`. Args: x: Input tensor. """ return ops.hard_tanh(x) @keras_export("keras.activations.hard_shrink") def hard_shrink(x, threshold=0.5): """Hard Shrink activation function. It is defined as: `hard_shrink(x) = x` if `|x| > threshold`, `hard_shrink(x) = 0` otherwise. Args: x: Input tensor. threshold: Threshold value. Defaults to 0.5. """ return ops.hard_shrink(x, threshold=threshold) @keras_export("keras.activations.threshold") def threshold(x, threshold, default_value): """Threshold activation function. It is defined as: `threshold(x) = x` if `x > threshold`, `threshold(x) = default_value` otherwise. Args: x: Input tensor. threshold: The value that decides when to retain or replace x. default_value: Value to assign when `x <= threshold`. """ return ops.threshold(x, threshold, default_value) @keras_export("keras.activations.sigmoid") def sigmoid(x): """Sigmoid activation function. It is defined as: `sigmoid(x) = 1 / (1 + exp(-x))`. For small values (<-5), `sigmoid` returns a value close to zero, and for large values (>5) the result of the function gets close to 1. Sigmoid is equivalent to a 2-element softmax, where the second element is assumed to be zero. The sigmoid function always returns a value between 0 and 1. Args: x: Input tensor. """ output = ops.sigmoid(x) # Cache the logits to use for crossentropy loss. try: output._keras_logits = x except AttributeError: # We're dealing with a C-type. pass return output @keras_export("keras.activations.exponential") def exponential(x): """Exponential activation function. Args: x: Input tensor. """ return ops.exp(x) @keras_export("keras.activations.hard_sigmoid") def hard_sigmoid(x): """Hard sigmoid activation function. The hard sigmoid activation is defined as: - `0` if `if x <= -3` - `1` if `x >= 3` - `(x/6) + 0.5` if `-3 < x < 3` It's a faster, piecewise linear approximation of the sigmoid activation. Args: x: Input tensor. Reference: - [Wikipedia "Hard sigmoid"](https://en.wikipedia.org/wiki/Hard_sigmoid) """ return ops.hard_sigmoid(x) @keras_export("keras.activations.log_sigmoid") def log_sigmoid(x): """Logarithm of the sigmoid activation function. It is defined as `f(x) = log(1 / (1 + exp(-x)))`. Args: x: Input tensor. """ return ops.log_sigmoid(x) @keras_export(["keras.activations.hard_silu", "keras.activations.hard_swish"]) def hard_silu(x): """Hard SiLU activation function, also known as Hard Swish. It is defined as: - `0` if `if x < -3` - `x` if `x > 3` - `x * (x + 3) / 6` if `-3 <= x <= 3` It's a faster, piecewise linear approximation of the silu activation. Args: x: Input tensor. Reference: - [A Howard, 2019](https://arxiv.org/abs/1905.02244) """ x = backend.convert_to_tensor(x) return ops.hard_silu(x) @keras_export("keras.activations.linear") def linear(x): """Linear activation function (pass-through). A "linear" activation is an identity function: it returns the input, unmodified. Args: x: Input tensor. """ return x class Mish(ops.Operation): def call(self, x): return self.static_call(x) def compute_output_spec(self, x): return backend.KerasTensor(x.shape, x.dtype) @staticmethod def static_call(x): return x * backend.nn.tanh(backend.nn.softplus(x)) @keras_export("keras.activations.mish") def mish(x): """Mish activation function. It is defined as: `mish(x) = x * tanh(softplus(x))` where `softplus` is defined as: `softplus(x) = log(exp(x) + 1)` Args: x: Input tensor. Reference: - [Misra, 2019](https://arxiv.org/abs/1908.08681) """ x = backend.convert_to_tensor(x) return Mish.static_call(x) @keras_export("keras.activations.log_softmax") def log_softmax(x, axis=-1): """Log-Softmax activation function. Each input vector is handled independently. The `axis` argument sets which axis of the input the function is applied along. Args: x: Input tensor. axis: Integer, axis along which the softmax is applied. """ return ops.log_softmax(x, axis=axis) @keras_export(["keras.activations.sparsemax"]) def sparsemax(x, axis=-1): """Sparsemax activation function. For each batch `i`, and class `j`, sparsemax activation function is defined as: `sparsemax(x)[i, j] = max(x[i, j] - τ(x[i, :]), 0).` Args: x: Input tensor. axis: `int`, axis along which the sparsemax operation is applied. Returns: A tensor, output of sparsemax transformation. Has the same type and shape as `x`. Reference: - [Martins et.al., 2016](https://arxiv.org/abs/1602.02068) """ x = backend.convert_to_tensor(x) return ops.sparsemax(x, axis)
fcholletREPO_NAMEkerasPATH_START.@keras_extracted@keras-master@keras@src@activations@activations.py@.PATH_END.py
{ "filename": "parse.py", "repo_name": "Caltech-IPAC/Montage", "repo_path": "Montage_extracted/Montage-main/python/MontagePy/macos_wheels/parse.py", "type": "Python" }
import os import glob import json from jinja2 import Template MONTAGELIB = os.path.join('Montage', 'MontageLib') CTYPE = {} CTYPE['int'] = 'int ' CTYPE['int*'] = 'int *' CTYPE['integer'] = 'int ' CTYPE['char'] = 'char ' CTYPE['string'] = 'char *' CTYPE['string*'] = 'char *' CTYPE['boolean'] = 'int ' CTYPE['boolean*'] = 'int *' CTYPE['double'] = 'double ' CTYPE['double*'] = 'double *' PTYPE = {} PTYPE['int'] = 'int' PTYPE['int*'] = 'np.ndarray' PTYPE['integer'] = 'int' PTYPE['char'] = 'str' PTYPE['string'] = 'str' PTYPE['string*'] = 'str' PTYPE['boolean'] = 'bool' PTYPE['boolean*'] = 'np.ndarray' PTYPE['double'] = 'float' PTYPE['double*'] = 'np.ndarray' with open('templates/template.pxd', 'r') as f: template_pxd = Template(f.read()) with open('templates/template.pyx', 'r') as f: template_pyx = Template(f.read()) with open('templates/template_main.pyx', 'r') as f: template_main_pyx = Template(f.read()) functions = [] for json_file in glob.glob(os.path.join(MONTAGELIB, '*', '*.json')): print("Parsing {0}...".format(json_file)) with open(json_file, 'r') as fjson: data = json.load(fjson) if data['return'] is None: continue # We set up our own dictionary that we will then pass on to the jinja2 # templates. function = {} # The name and description of the function function['name'] = data['function'] function['summary'] = data['desc'] # We now compile a list of arguments with defaults and arguments without # defaults - this is used in several places below. The arguments without # defaults come first. sorted_args = [arg for arg in data['arguments'] if 'default' not in arg] sorted_args += [arg for arg in data['arguments'] if 'default' in arg] # We now set up the lists of arguments. # Normal list of arguments function['arguments'] = [arg['name'] for arg in data['arguments']] # List of arguments to use in the C function declaration (functions # defined using cdef). function['arguments_cdef'] = [] # List of arguments to use when calling the cdef wrapper from the normal # Cython function - this has to include converting string arguments to # bytes strings with .encode('ascii') and converting arrays with e.g. # .data.as_doubles. function['arguments_py_to_cdef'] = [] for arg in data['arguments']: argument = "{0}{1}".format(CTYPE[arg['type']], arg['name']) function['arguments_cdef'].append(argument) function['arguments_with_defaults'] = [] for arg in sorted_args: if 'default' in arg: function['arguments_with_defaults'].append(arg['name'] + '=' + repr(arg['default'])) else: function['arguments_with_defaults'].append(arg['name']) function['array'] = [] function['arguments_py_to_cdef'] = [] for arg in data['arguments']: if arg['type'] == 'double*': function['array'].append("cdef _array.array {0}_arr = _array.array('d', {0})".format(arg['name'])) function['arguments_py_to_cdef'].append('{0}_arr.data.as_doubles'.format(arg['name'])) elif arg['type'] == 'int*': function['array'].append("cdef _array.array {0}_arr = _array.array('i', {0})".format(arg['name'])) function['arguments_py_to_cdef'].append('{0}_arr.data.as_ints'.format(arg['name'])) elif arg['type'] == 'boolean*': function['array'].append("cdef _array.array {0}_arr = _array.array('i', {0})".format(arg['name'])) function['arguments_py_to_cdef'].append('{0}_arr.data.as_ints'.format(arg['name'])) else: if 'string' in arg['type']: function['arguments_py_to_cdef'].append(arg['name'] + ".encode('ascii')") else: function['arguments_py_to_cdef'].append(arg['name']) function['struct_vars'] = [] function['struct_vars_decl'] = [] for ret in data['return']: struct_var = "{0}{1}".format(CTYPE[ret['type']], ret['name']) function['struct_vars'].append(ret['name']) function['struct_vars_decl'].append(struct_var) function['docstring_arguments'] = [] for inp in sorted_args: arg = {} arg['name'] = inp['name'] arg['type'] = PTYPE[inp['type']] if 'default' in inp: arg['type'] += ", optional" arg['description'] = inp['desc'] function['docstring_arguments'].append(arg) function['return_arguments'] = [] for ret in data['return']: arg = {} arg['name'] = ret['name'] arg['type'] = PTYPE[ret['type']] arg['description'] = ret['desc'] function['return_arguments'].append(arg) functions.append(function) with open('src/MontagePy/wrappers.pxd', 'w') as f: f.write(template_pxd.render(functions=functions)) with open('src/MontagePy/_wrappers.pyx', 'w') as f: f.write(template_pyx.render(functions=functions)) with open('src/MontagePy/main.pyx', 'w') as f: f.write(template_main_pyx.render(functions=functions))
Caltech-IPACREPO_NAMEMontagePATH_START.@Montage_extracted@Montage-main@python@MontagePy@macos_wheels@parse.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "jotaylor/acdc-hst", "repo_path": "acdc-hst_extracted/acdc-hst-main/src/acdc/data/__init__.py", "type": "Python" }
jotaylorREPO_NAMEacdc-hstPATH_START.@acdc-hst_extracted@acdc-hst-main@src@acdc@data@__init__.py@.PATH_END.py
{ "filename": "trackzone.py", "repo_name": "ultralytics/ultralytics", "repo_path": "ultralytics_extracted/ultralytics-main/ultralytics/solutions/trackzone.py", "type": "Python" }
# Ultralytics YOLO 🚀, AGPL-3.0 license import cv2 import numpy as np from ultralytics.solutions.solutions import BaseSolution from ultralytics.utils.plotting import Annotator, colors class TrackZone(BaseSolution): """ A class to manage region-based object tracking in a video stream. This class extends the BaseSolution class and provides functionality for tracking objects within a specific region defined by a polygonal area. Objects outside the region are excluded from tracking. It supports dynamic initialization of the region, allowing either a default region or a user-specified polygon. Attributes: region (ndarray): The polygonal region for tracking, represented as a convex hull. Methods: trackzone: Processes each frame of the video, applying region-based tracking. Examples: >>> tracker = TrackZone() >>> frame = cv2.imread("frame.jpg") >>> processed_frame = tracker.trackzone(frame) >>> cv2.imshow("Tracked Frame", processed_frame) """ def __init__(self, **kwargs): """Initializes the TrackZone class for tracking objects within a defined region in video streams.""" super().__init__(**kwargs) default_region = [(150, 150), (1130, 150), (1130, 570), (150, 570)] self.region = cv2.convexHull(np.array(self.region or default_region, dtype=np.int32)) def trackzone(self, im0): """ Processes the input frame to track objects within a defined region. This method initializes the annotator, creates a mask for the specified region, extracts tracks only from the masked area, and updates tracking information. Objects outside the region are ignored. Args: im0 (numpy.ndarray): The input image or frame to be processed. Returns: (numpy.ndarray): The processed image with tracking id and bounding boxes annotations. Examples: >>> tracker = TrackZone() >>> frame = cv2.imread("path/to/image.jpg") >>> tracker.trackzone(frame) """ self.annotator = Annotator(im0, line_width=self.line_width) # Initialize annotator # Create a mask for the region and extract tracks from the masked image masked_frame = cv2.bitwise_and(im0, im0, mask=cv2.fillPoly(np.zeros_like(im0[:, :, 0]), [self.region], 255)) self.extract_tracks(masked_frame) cv2.polylines(im0, [self.region], isClosed=True, color=(255, 255, 255), thickness=self.line_width * 2) # Iterate over boxes, track ids, classes indexes list and draw bounding boxes for box, track_id, cls in zip(self.boxes, self.track_ids, self.clss): self.annotator.box_label(box, label=f"{self.names[cls]}:{track_id}", color=colors(track_id, True)) self.display_output(im0) # display output with base class function return im0 # return output image for more usage
ultralyticsREPO_NAMEultralyticsPATH_START.@ultralytics_extracted@ultralytics-main@ultralytics@solutions@trackzone.py@.PATH_END.py
{ "filename": "driver.py", "repo_name": "radiocosmology/driftscan", "repo_path": "driftscan_extracted/driftscan-master/examples/disharray/driver.py", "type": "Python" }
from drift.core import beamtransfer, manager from drift.pipeline import timestream from simplearray import DishArray ### Make the analysis products for the telescope. This examples focuses only ### on the m-mode products for mapmaking # Create telescope object and set zenith tel = DishArray(latitude=30.0, longitude=0.0) # Create Beam Transfer manager, and generate products bt = beamtransfer.BeamTransfer("pydriver/btdir/", telescope=tel) bt.generate() ### Simulate and make a map froma timestream # Create an empty ProductManager m = manager.ProductManager() # Set the Beam Transfers m.beamtransfer = bt # Create a timestream with no noise (ndays=0) from a given map (could be a list of maps) ts = timestream.simulate(m, "pydriver/ts1/", ["simulated_map.hdf5"], ndays=0) # Make m-mode from the timestream ts.generate_mmodes() # Make a Healpix map from the m-modes (with NSIDE=256) ts.mapmake_full(256, "observed_map.hdf5")
radiocosmologyREPO_NAMEdriftscanPATH_START.@driftscan_extracted@driftscan-master@examples@disharray@driver.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/partners/ollama/tests/unit_tests/__init__.py", "type": "Python" }
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@partners@ollama@tests@unit_tests@__init__.py@.PATH_END.py
{ "filename": "plot_violin.py", "repo_name": "vblanka24/Ba_star_classification_PaperIII", "repo_path": "Ba_star_classification_PaperIII_extracted/Ba_star_classification_PaperIII-main/plotting_resids_correls/plot_violin.py", "type": "Python" }
import sys, os import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from collections import defaultdict import seaborn as sns import numpy as np import pandas as pd import seaborn as sns # from process_data_lib import * from processplot_data_lib import * from plot_lib import * allthree = False # True if CM, RF and NN models are plotted on each other for comparison; False if just one classifier FIGNAME="viol-all3" # root of figure names #sys.path.insert(0, "/correl1") font = {'family': 'sans-serif', 'size': 30} matplotlib.rc('font', **font) fig = plt.figure(figsize=[42, 12]) # Save files with data and directory if len(sys.argv) < 2: #if not console input #files = ["supsol-rf-mon-setA-nonorm.txt", "supsol-nn-monash-setA.txt", "supsol-cm-monash-setA.txt"] #files = ["supsol-rf-fruity-setA-nonorm.txt", "supsol-nn-fruity-setA.txt", "supsol-cm-fruity-setA.txt"] files = ["APUB-out-rf-fru.txt"] pathn = "viol-rf-forgit" set = "setA" monfru = "fru" else: files = sys.argv[1:-3] print(files) pathn = sys.argv[-3] set = sys.argv[-2] monfru = sys.argv[-1] plots_lst = [] def boxplot_main(files, clf_name, pathn, set, monfru, FIGNAME, fig, boxcolor="cornflowerblue", alph=1.0): TITLE = 'Statistics of the residuals of features, {:}'.format(clf_name) figname = '{:}-{:}'.format(FIGNAME, clf_name) if monfru == "mon": TITLE = TITLE + str('Monash') + ', ' + str(set) elif monfru == "fru": TITLE = TITLE + str('FRUITY') +', ' + str(set) else: raise Exception("Give mon or fru") TITLE = 'Statistics of the residuals of features, comparison, FRUITY' figname = figname + '-' + str(monfru) + '-' + str(set) if not os.path.exists(pathn): os.makedirs(pathn) # Define all the directories cwd = os.getcwd() dir_data = cwd+"/Ba_star_classification_data" fruity_mods = "models_fruity_dec" monash_mods = "models_monash" data_file = "all_data_w_err.dat" fruity_dir = os.path.join(dir_data, fruity_mods) monash_dir = os.path.join(dir_data, monash_mods) data_file = os.path.join(dir_data, data_file) # Load the stellar abundances dict_data = get_data_values(data_file) df_obs = conv_dict_to_df(dict_data) obs_elems = df_obs.columns.values.tolist() df_abunds = df_obs[[i for i in obs_elems if "err" not in i]] # Subtractions df_err = feature_subtract(df_obs[[i for i in obs_elems if "err" in i]], 1, plus=True) df_err = df_err[[i for i in df_err.columns if "Fe_err" not in i]] df_obs = feature_subtract(df_obs[[i for i in obs_elems if "err" not in i]], 1) df_obs = df_obs[[i for i in df_obs.columns if "/Fe" not in i]] ratio_names = df_obs.columns.values.tolist() # The fruity and monash models obs_elems = [i for i in obs_elems if "err" not in i] # observed elements fruity_models_dict = get_data_fruity(fruity_dir) df_fruity = conv_dict_to_df(fruity_models_dict).loc[:, obs_elems] monash_models_dict = get_data_monash(monash_dir) df_monash = conv_dict_to_df(monash_models_dict).loc[:, obs_elems] # Uncomment if necessary: calculating [Ce/Eu] # df_monash["Ce/Eu"] = df_monash["Ce/Fe"] - df_monash["Eu/Fe"] # delta = 1 # df_monash["Ce/Eu_mod"] = np.log10(delta * (10**df_monash["Ce/Eu"] + (1-delta))) # df_monash.to_excel("monash_ce_eu.xlsx") # plt.hist(df_monash["Ce/Eu_mod"], bins=25) # #plt.hist(df_obs["Ce/Eu"], bins=25, alpha=0.5) # #plt.hist(df_abunds["Eu/Fe"], bins=25, alpha=0.5) # plt.hist(df_monash["Eu/Fe"], bins=25, alpha=0.5, label="Eu/Fe, models") # # plt.legend() # plt.show() cm = False if clf_name == "CM": cm = True predicted_models_dict = get_dict_predicted(files, cm) predicted_fru = predicted_models_dict['fruity'] predicted_mon = predicted_models_dict['monash'] # Load the red elements with open(os.path.join("../A_data_processing_and_plotting", "element_set.dat"), "r") as fread: for line in fread: lnlst = line.split() # Skip comments and empty lines if len(lnlst) == 0 or "#" in lnlst[0]: continue red_elements = lnlst break # Remove "/Fe" red_elements = [elem.split("/")[0] for elem in red_elements] red_elements.remove("Fe") peak1 = ['Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Ru'] #peak1 = [val for val in peak1 if val in red_elements] peak2 = ['La', 'Ce', 'Nd', 'Sm', 'Eu'] #peak2 = [val for val in peak2 if val in red_elements] stars_lst = df_obs.index.tolist()#[:10] resids = defaultdict(list) resids_abunds = defaultdict(list) stars_and_models = defaultdict(list) feh_lst = [] mass_lst = [] dil_lst = [] stars_alllst = [] # For each star, calcualte residuals print("Reading ratios in") for nstar in range(len(stars_lst)): print(nstar) starname = stars_lst[nstar] rowstar = df_obs.loc[starname] rowstar_abunds = df_abunds.loc[starname] rowstar_err = df_err.loc[starname] feh_obs = rowstar.pop('Fe/H') peak1p1_obs, peak1p2_obs, peak2p1_obs, peak2p2_obs, peak2p2_obs_r = peakfilter(rowstar, peak1, peak2) # peak1p1_err, peak1p2_err, peak2p2_err = peakfilter(rowstar_err, peak1, peak2) for file_now in files: # for each input file if "mon" in file_now: mode = "mon" possible_models = predicted_mon[starname] elif "fru" in file_now: mode = "fru" possible_models = predicted_fru[starname] for modelname, dil in [i[:2] for i in possible_models]: if mode == "mon": model_now = df_monash.loc[modelname] mass = float(modelname[modelname.find('_m') + 2:modelname.find('_m') + 6]) elif mode == "fru": model_now = df_fruity.loc[modelname] mass = float(modelname[modelname.find('_m') + 2]) + float(modelname[modelname.find('_m') + 4]) / 10 feh_model = model_now['Fe/H'] stars_and_models['star'].append(starname) stars_and_models['model'].append(modelname) Eu_obs = df_abunds.loc[starname]['Eu/Fe'] Eu_model = model_now.loc['Eu/Fe'] Ce_Eu_obs = df_obs.loc[starname]["Ce/Eu"] model_dil_abunds = pd.DataFrame(apply_dilution_df(model_now, dil)) model_dil = subtract_and_exclude(model_dil_abunds).iloc[0] peak1p1_mod, peak1p2_mod, peak2p1_mod, peak2p2_mod, peak2p2_mod_r = peakfilter(model_dil, peak1, peak2) model_dil_abunds = pd.Series(apply_dilution_df(model_now, dil)) # as series resid_now = rowstar - model_dil resid_abunds_now = rowstar_abunds - model_dil_abunds # Uncomment if you want to filter for models with specific residuals or abundances #if abs(feh_obs-feh_model) < 0.3 : #if Eu_obs < 0.3 : for key in model_dil.keys(): resids[key].append(resid_now[key]) for key in model_dil_abunds.keys(): resids_abunds[key].append(resid_abunds_now[key]) feh_lst.append(feh_obs-feh_model) mass_lst.append(mass) dil_lst.append(dil) stars_alllst.append(starname) # DF for model residuals resids_abunds_df = pd.DataFrame.from_dict(resids_abunds) resids_abunds_df['Fe/H'] = feh_lst print("LEN") print(len(feh_lst)) resids_df = pd.DataFrame.from_dict(resids) p1p1_abund, p1p2_abund, p2p1_abund, p2p2_abund, p2p2_abund_r = peakfilter(pd.Series(resids), peak1, peak2) df_all_resids = pd.concat([resids_abunds_df, pd.DataFrame(dict(p1p1_abund)), pd.DataFrame(dict(p1p2_abund)), pd.DataFrame(dict(p2p2_abund))], sort=False, axis=1) if allthree: df_all_resids = pd.concat([resids_abunds_df, pd.DataFrame(dict(p1p1_abund)), pd.DataFrame(dict(p2p1_abund)), pd.DataFrame(dict(p2p2_abund))], sort=False, axis=1) df_all_resids.replace(to_replace='nan', value=np.nan, inplace=True) print(df_all_resids) # Save to a spreadsheet df_all_resids.to_excel('df_all_resids_filter.xlsx') df_median = df_all_resids.median() # Uncomment if necessary: Dropping out bad stars # df_cols = df_all_resids.columns.values.tolist() # bad_elems = ['Nb', 'Mo', 'Ru'] # for elem in bad_elems: # lst_features = [x for x in df_cols if ((x[:x.find('/')] == elem) or (x[x.find('/')+1:] == elem)) and ('Fe' not in x)] # for nstar in range(len(df_all_resids['Fe/H'])): # count = 0 # for feature in lst_features: # f = df_all_resids.iloc[nstar][feature] # med = df_median.loc[feature] # if f < med: count += 1 # if count >= (len(lst_features)-1): # print("feature") # df_all_resids.drop(labels=[nstar], axis=0, inplace=True) # print("") # PLOTTING # --------------------------------------------------------------------------------------- ax = plt.gca() if clf_name == 'CM': c = (0.86,0.07,0.24, 1) h = '.o' w = 0.8 elif clf_name == 'NN': c = (0.3,0.45,0.87, 1) h = '\\' w = 0.6 elif clf_name == 'RF': c = (0.19,0.8,0.19, 0.8) h = '/' w = 0.4 else: print('Wrong clf name!') cols = df_all_resids.columns num_cols = len(cols.tolist()) #df_all_resids = df_all_resids.apply(pd.to_numeric, errors='coerce') #df_all_resids = pd.DataFrame(df_all_resids, dtype='float') #df_all_resids = df_all_resids.astype(float) #df_all_resids.dropna(inplace=True) #df_all_resids[cols[1:]] = df_all_resids[cols[1:]].apply(pd.to_numeric, errors='coerce') color_median = matplotlib.colors.ColorConverter.to_rgb(boxcolor) color_median = tuple(i*0.7 for i in color_median) ax, bp_nice = df_all_resids.boxplot(grid=False, notch=True, patch_artist=True, showfliers=False, return_type="both", boxprops=dict(facecolor=boxcolor, color=color_median, alpha=alph), capprops=dict(color=boxcolor, linewidth=2), whiskerprops=dict(color=boxcolor, linewidth=2), medianprops=dict(color=color_median), widths=[w for i in range(num_cols)]) red_elements.append('Fe') red_elements.append('H') #lst_reds = [x for x in df_cols if ((x[:x.find('/')] in red_elements) and (x[x.find('/')+1:] in red_elements))] #df_red_resids = df_all_resids[lst_reds] lst_nonreds = [x for x in cols if ((x[:x.find('/')] not in red_elements) or (x[x.find('/')+1:] not in red_elements))] df_red_resids = df_all_resids.copy() df_red_resids[lst_nonreds] = np.nan c = boxcolor # df_red_resids.boxplot(patch_artist=True, boxprops=dict(facecolor=c, alpha=alph), capprops=dict(color=c), # whiskerprops=dict(color=c), flierprops=dict(color=c, markeredgecolor=c), medianprops=dict(color=c), # notch=True, showfliers=False) toplim = ax.get_ylim()[1] toplim = 1.25 botlim = ax.get_ylim()[0] botlim = -1.5 #resids_df.boxplot() box_params = dict(boxstyle="round,pad=0.3", fc="lightcyan", ec="black", lw=2) vline_pos = len(resids_abunds)+0.5 ax.text((1+vline_pos)/2, toplim, "[X/Fe]", ha="center", va="center", rotation=0, size=30, bbox=box_params) plt.axvline(vline_pos, color="black", lw=3) ax.text(vline_pos+len(p1p1_abund)/2, toplim, "[Peak 1 / Peak 1]", ha="center", va="center", rotation=0, size=30, bbox=box_params) vline_pos += len(p1p1_abund) plt.axvline(vline_pos, color="black", lw=2) ax.text(vline_pos+len(p1p2_abund)/2, toplim, "[Peak 2 / Peak 1]", ha="center", va="center", rotation=0, size=30, bbox=box_params) vline_pos += len(p1p2_abund) plt.axvline(vline_pos, color="black", lw=2) ax.text(vline_pos+len(p2p2_abund)/2, toplim, "[Peak 2 / Peak 2]", ha="center", va="center", rotation=0, size=30, bbox=box_params) plt.axhline(0, color='black', lw=1) plt.title(TITLE, size=42, weight='bold', y=1.06) plt.xticks(rotation=75) ax.set_ylim(botlim, toplim) plt.ylabel(r'[X/Y]$_{\mathbf{obs}}$ - [X/Y]$_{\mathbf{mod}}$', size=30, weight='bold') plt.tight_layout() resids_df.to_excel(r'./resids_ord.xlsx', index=False) df_all_resids['Fe/H'] = feh_lst df_all_resids['mass'] = mass_lst df_all_resids['star'] = stars_alllst df_all_resids['dil'] = dil_lst print('WRITE IT OUT') df_all_resids.to_csv('boxplot_resids.dat', index=False) df_all_resids.pop('mass') df_all_resids.pop('star') df_all_resids.pop('dil') #plt.close() # TABLE ------------ df_all_resids.replace(to_replace='nan', value=np.nan, inplace=True) ax, bp = df_all_resids.boxplot(showmeans=True, return_type='both', showfliers=False, showcaps=True, showbox=True, boxprops=dict(alpha=0), whiskerprops=dict(color=(0,0,0,0), alpha=0), capprops=dict(alpha=0), flierprops=dict(alpha=0), medianprops=dict(alpha=0), meanprops=dict(alpha=0)) categories = list(df_all_resids.columns) # to be updated medians = [round(item.get_ydata()[0], 2) for item in bp['medians']] means = [round(item.get_ydata()[0], 2) for item in bp['means']] minimums = [round(item.get_ydata()[0], 2) for item in bp['caps']][::2] maximums = [round(item.get_ydata()[0], 2) for item in bp['caps']][1::2] q1 = [round(min(item.get_ydata()), 2) for item in bp['boxes']] q3 = [round(max(item.get_ydata()), 2) for item in bp['boxes']] fliers = [item.get_ydata() for item in bp['fliers']] stats = [medians, means, q1, q3, minimums, maximums] zipped = list(zip(*stats)) df_boxpl = pd.DataFrame(zipped, columns=['Median', 'Mean', 'Q1', 'Q3', 'Min.', 'Max.']) df_boxpl.index = categories #df_boxpl = df_boxpl.T df_boxpl.to_excel(r'./boxpl-data.xlsx') print(df_boxpl) tot_len = len(peak1p1_obs) + len(peak1p2_obs) + len(peak2p2_obs) + len(resids_abunds) def peakplot(series_toplot, pnpm_obs, boxtit, savename_end): '''A small plot containing only one peak / peak''' df_toplot = pd.DataFrame(dict(series_toplot)) if "p2p2" in savename_end: fig = plt.figure(figsize=[70*(len(df_toplot.columns)/tot_len), 12]) elif "abund" in savename_end: fig = plt.figure(figsize=[70*(len(df_toplot.columns)/tot_len), 12]) else: fig = plt.figure(figsize=[70 * (len(df_toplot.columns) / tot_len), 12]) ax = plt.gca() plt.axhline(0, color='black', lw=1) c='teal' df_toplot.columns = [r'$\Delta$['+x+']' for x in df_toplot.columns] sns.violinplot(data=df_toplot) sns.boxplot(data=df_toplot, boxprops={"zorder": 2, "alpha": 1}, width=0.2, color='black', showfliers=False, whis=0, notch=True) # Uncomment if necessary: used elements have red boxplots # lst_nonreds = [x for x in df_cols if # ((x[:x.find('/')] not in red_elements) or (x[x.find('/') + 1:] not in red_elements))] # df_red_resids = df_all_resids.copy() # df_red_resids[lst_nonreds] = np.nan # c = "crimson" # # df_red_resids.boxplot(patch_artist=True, # boxprops=dict(facecolor=c, color=c), # capprops=dict(color=c), # whiskerprops=dict(color=c), # flierprops=dict(color=c, markeredgecolor=c), # medianprops=dict(color=c)) ax.text((len(df_toplot.columns)-1) / 2, 1.3, boxtit, ha="center", va="center", rotation=0, size=30, bbox=box_params) ax.set_ylim(-1.5, 1.25) plt.title('{:} FRUITY'.format(clf_name), weight='bold', y=1.08) plt.xticks(rotation=75) plt.ylabel(r'[X/Y]$_{\mathbf{obs}}$ - [X/Y]$_{\mathbf{mod}}$', size=30, weight='bold') plt.tight_layout() savename = figname + savename_end #+ '-' + clf_name plt.savefig(os.path.join(pathn, savename), bbox_inches='tight') plt.close() peakplot(resids_abunds_df, peak1p1_obs, "[X/Fe]", "-abunds") peakplot(p1p1_abund, peak1p1_obs, "[Peak 1 / Peak 1]", "-p1p1") peakplot(p1p2_abund, peak1p2_obs, "[Peak 1 / Peak 2]", "-p1p2") peakplot(p2p2_abund, peak2p2_obs, "[Peak 2 / Peak 2]", "-p2p2") peakplot(p2p1_abund, peak2p1_obs, "[Peak 2 / Peak 1]", "-p2p1") return bp_nice if allthree: bp_cm = boxplot_main([files[2]], 'CM', pathn, set, monfru, FIGNAME, fig, boxcolor="crimson") # plt.tick_params( # axis='x', # changes apply to the x-axis # which='both', # both major and minor ticks are affected # bottom=True, # ticks along the bottom edge are off # top=False, # ticks along the top edge are off # labelbottom=True) # labels along the bottom edge are off bp_nn = boxplot_main([files[1]], 'NN', pathn, set, monfru, FIGNAME, fig, alph=0.7) bp_rf = boxplot_main([files[0]], 'RF', pathn, set, monfru, FIGNAME, fig, boxcolor="lime", alph=0.5) ax = plt.gca() plt.xticks(rotation=75) ax.tick_params(axis="x", direction="in", length=20) ax.grid(False) labels = ['CM', 'NN', 'RF'] plt.tight_layout() if allthree: ax.legend([bp_cm["boxes"][0], bp_nn["boxes"][0], bp_rf["boxes"][0]], ['CM', 'NN', 'RF'], loc='lower right') plt.savefig(os.path.join(pathn, FIGNAME))
vblanka24REPO_NAMEBa_star_classification_PaperIIIPATH_START.@Ba_star_classification_PaperIII_extracted@Ba_star_classification_PaperIII-main@plotting_resids_correls@plot_violin.py@.PATH_END.py
{ "filename": "_maxpoints.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/scattergl/stream/_maxpoints.py", "type": "Python" }
import _plotly_utils.basevalidators class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="maxpoints", parent_name="scattergl.stream", **kwargs ): super(MaxpointsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), max=kwargs.pop("max", 10000), min=kwargs.pop("min", 0), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@scattergl@stream@_maxpoints.py@.PATH_END.py
{ "filename": "compiler.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py", "type": "Python" }
r""" Compiler for a regular grammar. Example usage:: # Create and compile grammar. p = compile('add \s+ (?P<var1>[^\s]+) \s+ (?P<var2>[^\s]+)') # Match input string. m = p.match('add 23 432') # Get variables. m.variables().get('var1') # Returns "23" m.variables().get('var2') # Returns "432" Partial matches are possible:: # Create and compile grammar. p = compile(''' # Operators with two arguments. ((?P<operator1>[^\s]+) \s+ (?P<var1>[^\s]+) \s+ (?P<var2>[^\s]+)) | # Operators with only one arguments. ((?P<operator2>[^\s]+) \s+ (?P<var1>[^\s]+)) ''') # Match partial input string. m = p.match_prefix('add 23') # Get variables. (Notice that both operator1 and operator2 contain the # value "add".) This is because our input is incomplete, and we don't know # yet in which rule of the regex we we'll end up. It could also be that # `operator1` and `operator2` have a different autocompleter and we want to # call all possible autocompleters that would result in valid input.) m.variables().get('var1') # Returns "23" m.variables().get('operator1') # Returns "add" m.variables().get('operator2') # Returns "add" """ from __future__ import annotations import re from typing import Callable, Dict, Iterable, Iterator, Pattern, TypeVar, overload from typing import Match as RegexMatch from .regex_parser import ( AnyNode, Lookahead, Node, NodeSequence, Regex, Repeat, Variable, parse_regex, tokenize_regex, ) __all__ = ["compile", "Match", "Variables"] # Name of the named group in the regex, matching trailing input. # (Trailing input is when the input contains characters after the end of the # expression has been matched.) _INVALID_TRAILING_INPUT = "invalid_trailing" EscapeFuncDict = Dict[str, Callable[[str], str]] class _CompiledGrammar: """ Compiles a grammar. This will take the parse tree of a regular expression and compile the grammar. :param root_node: :class~`.regex_parser.Node` instance. :param escape_funcs: `dict` mapping variable names to escape callables. :param unescape_funcs: `dict` mapping variable names to unescape callables. """ def __init__( self, root_node: Node, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> None: self.root_node = root_node self.escape_funcs = escape_funcs or {} self.unescape_funcs = unescape_funcs or {} #: Dictionary that will map the regex names to Node instances. self._group_names_to_nodes: dict[ str, str ] = {} # Maps regex group names to varnames. counter = [0] def create_group_func(node: Variable) -> str: name = f"n{counter[0]}" self._group_names_to_nodes[name] = node.varname counter[0] += 1 return name # Compile regex strings. self._re_pattern = f"^{self._transform(root_node, create_group_func)}$" self._re_prefix_patterns = list( self._transform_prefix(root_node, create_group_func) ) # Compile the regex itself. flags = re.DOTALL # Note that we don't need re.MULTILINE! (^ and $ # still represent the start and end of input text.) self._re = re.compile(self._re_pattern, flags) self._re_prefix = [re.compile(t, flags) for t in self._re_prefix_patterns] # We compile one more set of regexes, similar to `_re_prefix`, but accept any trailing # input. This will ensure that we can still highlight the input correctly, even when the # input contains some additional characters at the end that don't match the grammar.) self._re_prefix_with_trailing_input = [ re.compile( r"(?:{})(?P<{}>.*?)$".format(t.rstrip("$"), _INVALID_TRAILING_INPUT), flags, ) for t in self._re_prefix_patterns ] def escape(self, varname: str, value: str) -> str: """ Escape `value` to fit in the place of this variable into the grammar. """ f = self.escape_funcs.get(varname) return f(value) if f else value def unescape(self, varname: str, value: str) -> str: """ Unescape `value`. """ f = self.unescape_funcs.get(varname) return f(value) if f else value @classmethod def _transform( cls, root_node: Node, create_group_func: Callable[[Variable], str] ) -> str: """ Turn a :class:`Node` object into a regular expression. :param root_node: The :class:`Node` instance for which we generate the grammar. :param create_group_func: A callable which takes a `Node` and returns the next free name for this node. """ def transform(node: Node) -> str: # Turn `AnyNode` into an OR. if isinstance(node, AnyNode): return "(?:{})".format("|".join(transform(c) for c in node.children)) # Concatenate a `NodeSequence` elif isinstance(node, NodeSequence): return "".join(transform(c) for c in node.children) # For Regex and Lookahead nodes, just insert them literally. elif isinstance(node, Regex): return node.regex elif isinstance(node, Lookahead): before = "(?!" if node.negative else "(=" return before + transform(node.childnode) + ")" # A `Variable` wraps the children into a named group. elif isinstance(node, Variable): return f"(?P<{create_group_func(node)}>{transform(node.childnode)})" # `Repeat`. elif isinstance(node, Repeat): if node.max_repeat is None: if node.min_repeat == 0: repeat_sign = "*" elif node.min_repeat == 1: repeat_sign = "+" else: repeat_sign = "{%i,%s}" % ( node.min_repeat, ("" if node.max_repeat is None else str(node.max_repeat)), ) return "(?:{}){}{}".format( transform(node.childnode), repeat_sign, ("" if node.greedy else "?"), ) else: raise TypeError(f"Got {node!r}") return transform(root_node) @classmethod def _transform_prefix( cls, root_node: Node, create_group_func: Callable[[Variable], str] ) -> Iterable[str]: """ Yield all the regular expressions matching a prefix of the grammar defined by the `Node` instance. For each `Variable`, one regex pattern will be generated, with this named group at the end. This is required because a regex engine will terminate once a match is found. For autocompletion however, we need the matches for all possible paths, so that we can provide completions for each `Variable`. - So, in the case of an `Any` (`A|B|C)', we generate a pattern for each clause. This is one for `A`, one for `B` and one for `C`. Unless some groups don't contain a `Variable`, then these can be merged together. - In the case of a `NodeSequence` (`ABC`), we generate a pattern for each prefix that ends with a variable, and one pattern for the whole sequence. So, that's one for `A`, one for `AB` and one for `ABC`. :param root_node: The :class:`Node` instance for which we generate the grammar. :param create_group_func: A callable which takes a `Node` and returns the next free name for this node. """ def contains_variable(node: Node) -> bool: if isinstance(node, Regex): return False elif isinstance(node, Variable): return True elif isinstance(node, (Lookahead, Repeat)): return contains_variable(node.childnode) elif isinstance(node, (NodeSequence, AnyNode)): return any(contains_variable(child) for child in node.children) return False def transform(node: Node) -> Iterable[str]: # Generate separate pattern for all terms that contain variables # within this OR. Terms that don't contain a variable can be merged # together in one pattern. if isinstance(node, AnyNode): # If we have a definition like: # (?P<name> .*) | (?P<city> .*) # Then we want to be able to generate completions for both the # name as well as the city. We do this by yielding two # different regular expressions, because the engine won't # follow multiple paths, if multiple are possible. children_with_variable = [] children_without_variable = [] for c in node.children: if contains_variable(c): children_with_variable.append(c) else: children_without_variable.append(c) for c in children_with_variable: yield from transform(c) # Merge options without variable together. if children_without_variable: yield "|".join( r for c in children_without_variable for r in transform(c) ) # For a sequence, generate a pattern for each prefix that ends with # a variable + one pattern of the complete sequence. # (This is because, for autocompletion, we match the text before # the cursor, and completions are given for the variable that we # match right before the cursor.) elif isinstance(node, NodeSequence): # For all components in the sequence, compute prefix patterns, # as well as full patterns. complete = [cls._transform(c, create_group_func) for c in node.children] prefixes = [list(transform(c)) for c in node.children] variable_nodes = [contains_variable(c) for c in node.children] # If any child is contains a variable, we should yield a # pattern up to that point, so that we are sure this will be # matched. for i in range(len(node.children)): if variable_nodes[i]: for c_str in prefixes[i]: yield "".join(complete[:i]) + c_str # If there are non-variable nodes, merge all the prefixes into # one pattern. If the input is: "[part1] [part2] [part3]", then # this gets compiled into: # (complete1 + (complete2 + (complete3 | partial3) | partial2) | partial1 ) # For nodes that contain a variable, we skip the "|partial" # part here, because thees are matched with the previous # patterns. if not all(variable_nodes): result = [] # Start with complete patterns. for i in range(len(node.children)): result.append("(?:") result.append(complete[i]) # Add prefix patterns. for i in range(len(node.children) - 1, -1, -1): if variable_nodes[i]: # No need to yield a prefix for this one, we did # the variable prefixes earlier. result.append(")") else: result.append("|(?:") # If this yields multiple, we should yield all combinations. assert len(prefixes[i]) == 1 result.append(prefixes[i][0]) result.append("))") yield "".join(result) elif isinstance(node, Regex): yield f"(?:{node.regex})?" elif isinstance(node, Lookahead): if node.negative: yield f"(?!{cls._transform(node.childnode, create_group_func)})" else: # Not sure what the correct semantics are in this case. # (Probably it's not worth implementing this.) raise Exception("Positive lookahead not yet supported.") elif isinstance(node, Variable): # (Note that we should not append a '?' here. the 'transform' # method will already recursively do that.) for c_str in transform(node.childnode): yield f"(?P<{create_group_func(node)}>{c_str})" elif isinstance(node, Repeat): # If we have a repetition of 8 times. That would mean that the # current input could have for instance 7 times a complete # match, followed by a partial match. prefix = cls._transform(node.childnode, create_group_func) if node.max_repeat == 1: yield from transform(node.childnode) else: for c_str in transform(node.childnode): if node.max_repeat: repeat_sign = "{,%i}" % (node.max_repeat - 1) else: repeat_sign = "*" yield "(?:{}){}{}{}".format( prefix, repeat_sign, ("" if node.greedy else "?"), c_str, ) else: raise TypeError(f"Got {node!r}") for r in transform(root_node): yield f"^(?:{r})$" def match(self, string: str) -> Match | None: """ Match the string with the grammar. Returns a :class:`Match` instance or `None` when the input doesn't match the grammar. :param string: The input string. """ m = self._re.match(string) if m: return Match( string, [(self._re, m)], self._group_names_to_nodes, self.unescape_funcs ) return None def match_prefix(self, string: str) -> Match | None: """ Do a partial match of the string with the grammar. The returned :class:`Match` instance can contain multiple representations of the match. This will never return `None`. If it doesn't match at all, the "trailing input" part will capture all of the input. :param string: The input string. """ # First try to match using `_re_prefix`. If nothing is found, use the patterns that # also accept trailing characters. for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]: matches = [(r, r.match(string)) for r in patterns] matches2 = [(r, m) for r, m in matches if m] if matches2 != []: return Match( string, matches2, self._group_names_to_nodes, self.unescape_funcs ) return None class Match: """ :param string: The input string. :param re_matches: List of (compiled_re_pattern, re_match) tuples. :param group_names_to_nodes: Dictionary mapping all the re group names to the matching Node instances. """ def __init__( self, string: str, re_matches: list[tuple[Pattern[str], RegexMatch[str]]], group_names_to_nodes: dict[str, str], unescape_funcs: dict[str, Callable[[str], str]], ): self.string = string self._re_matches = re_matches self._group_names_to_nodes = group_names_to_nodes self._unescape_funcs = unescape_funcs def _nodes_to_regs(self) -> list[tuple[str, tuple[int, int]]]: """ Return a list of (varname, reg) tuples. """ def get_tuples() -> Iterable[tuple[str, tuple[int, int]]]: for r, re_match in self._re_matches: for group_name, group_index in r.groupindex.items(): if group_name != _INVALID_TRAILING_INPUT: regs = re_match.regs reg = regs[group_index] node = self._group_names_to_nodes[group_name] yield (node, reg) return list(get_tuples()) def _nodes_to_values(self) -> list[tuple[str, str, tuple[int, int]]]: """ Returns list of (Node, string_value) tuples. """ def is_none(sl: tuple[int, int]) -> bool: return sl[0] == -1 and sl[1] == -1 def get(sl: tuple[int, int]) -> str: return self.string[sl[0] : sl[1]] return [ (varname, get(slice), slice) for varname, slice in self._nodes_to_regs() if not is_none(slice) ] def _unescape(self, varname: str, value: str) -> str: unwrapper = self._unescape_funcs.get(varname) return unwrapper(value) if unwrapper else value def variables(self) -> Variables: """ Returns :class:`Variables` instance. """ return Variables( [(k, self._unescape(k, v), sl) for k, v, sl in self._nodes_to_values()] ) def trailing_input(self) -> MatchVariable | None: """ Get the `MatchVariable` instance, representing trailing input, if there is any. "Trailing input" is input at the end that does not match the grammar anymore, but when this is removed from the end of the input, the input would be a valid string. """ slices: list[tuple[int, int]] = [] # Find all regex group for the name _INVALID_TRAILING_INPUT. for r, re_match in self._re_matches: for group_name, group_index in r.groupindex.items(): if group_name == _INVALID_TRAILING_INPUT: slices.append(re_match.regs[group_index]) # Take the smallest part. (Smaller trailing text means that a larger input has # been matched, so that is better.) if slices: slice = (max(i[0] for i in slices), max(i[1] for i in slices)) value = self.string[slice[0] : slice[1]] return MatchVariable("<trailing_input>", value, slice) return None def end_nodes(self) -> Iterable[MatchVariable]: """ Yields `MatchVariable` instances for all the nodes having their end position at the end of the input string. """ for varname, reg in self._nodes_to_regs(): # If this part goes until the end of the input string. if reg[1] == len(self.string): value = self._unescape(varname, self.string[reg[0] : reg[1]]) yield MatchVariable(varname, value, (reg[0], reg[1])) _T = TypeVar("_T") class Variables: def __init__(self, tuples: list[tuple[str, str, tuple[int, int]]]) -> None: #: List of (varname, value, slice) tuples. self._tuples = tuples def __repr__(self) -> str: return "{}({})".format( self.__class__.__name__, ", ".join(f"{k}={v!r}" for k, v, _ in self._tuples), ) @overload def get(self, key: str) -> str | None: ... @overload def get(self, key: str, default: str | _T) -> str | _T: ... def get(self, key: str, default: str | _T | None = None) -> str | _T | None: items = self.getall(key) return items[0] if items else default def getall(self, key: str) -> list[str]: return [v for k, v, _ in self._tuples if k == key] def __getitem__(self, key: str) -> str | None: return self.get(key) def __iter__(self) -> Iterator[MatchVariable]: """ Yield `MatchVariable` instances. """ for varname, value, slice in self._tuples: yield MatchVariable(varname, value, slice) class MatchVariable: """ Represents a match of a variable in the grammar. :param varname: (string) Name of the variable. :param value: (string) Value of this variable. :param slice: (start, stop) tuple, indicating the position of this variable in the input string. """ def __init__(self, varname: str, value: str, slice: tuple[int, int]) -> None: self.varname = varname self.value = value self.slice = slice self.start = self.slice[0] self.stop = self.slice[1] def __repr__(self) -> str: return f"{self.__class__.__name__}({self.varname!r}, {self.value!r})" def compile( expression: str, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> _CompiledGrammar: """ Compile grammar (given as regex string), returning a `CompiledGrammar` instance. """ return _compile_from_parse_tree( parse_regex(tokenize_regex(expression)), escape_funcs=escape_funcs, unescape_funcs=unescape_funcs, ) def _compile_from_parse_tree( root_node: Node, escape_funcs: EscapeFuncDict | None = None, unescape_funcs: EscapeFuncDict | None = None, ) -> _CompiledGrammar: """ Compile grammar (given as parse tree), returning a `CompiledGrammar` instance. """ return _CompiledGrammar( root_node, escape_funcs=escape_funcs, unescape_funcs=unescape_funcs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@prompt-toolkit@py3@prompt_toolkit@contrib@regular_languages@compiler.py@.PATH_END.py
{ "filename": "driver.py", "repo_name": "EmmanuelSchaan/HaloGen", "repo_path": "HaloGen_extracted/HaloGen-master/driver.py", "type": "Python" }
import universe reload(universe) from universe import * import mass_function reload(mass_function) from mass_function import * import profile reload(profile) from profile import * import i_halo_model reload(i_halo_model) from i_halo_model import * import p3d reload(p3d) from p3d import * import projection_kernel reload(projection_kernel) from projection_kernel import * import p2d reload(p2d) from p2d import * ################################################################################## # Basic functions and parameters, for background and fluctuations u = UnivPlanck15() ################################################################################## # Several mass functions implemented: Press-Schechter, Sheth-Tormen, Tinker #massFunc = MassFuncPS(u, save=False) #massFunc = MassFuncST(u, save=False) massFunc = MassFuncTinker(u, save=False) ''' massFunc.plotMassFunc() massFunc.plotB1() massFunc.testInterp(z=0.) massFunc.plotMassFunc() massFunc.plotIntegralConstraintsZ() massFunc.plotMassCounterTerms() massFunc.plotMassConstraintMMin() massFunc.plotBiasConstraintMMin() ''' ################################################################################## # 3d profiles for matter density, Compton y, and HOD for CIB galaxies profNFW = ProfNFW(u) profY = ProfY(u) profHODPenin12_353 = ProfHODPenin12(u, massFunc, nu=353) # for CIB # plot the Fourier transform of any profile: # here, the NFW profile ''' profNFW.plotU() ''' ################################################################################## # 3d power spectra, auto and cross import p3d reload(p3d) from p3d import * # Matter density, Compton y, and CIB galaxies p3d_d = P3dAuto(u, massFunc, profNFW, save=False) p3d_y = P3dAuto(u, massFunc, profY, save=False) p3d_dy = P3dCross(u, massFunc, profNFW, profY, save=False) p3d_galPenin12_353 = P3dAuto(u, massFunc, profHODPenin12_353, pNoise=profHODPenin12_353.fPshotNoise, name="galpenin353", save=False) ''' p3d_d.plotP2hCorrections() p3d_d.plotPInt(z=0.) p3d_d.plotP1hMMinDependence(k=0.01) p3d_d.plotP2hMMinDependence(k=0.01) p3d_y.plotP2hCorrections() p3d_y.plotPInt(z=0.) p3d_y.plotP1hMMinDependence(k=0.01) p3d_y.plotP2hMMinDependence(k=0.01) p3d_dy.plotP2hCorrections() p3d_dy.plotPInt(z=0.) p3d_dy.plotP1hMMinDependence(k=0.01) p3d_dy.plotP2hMMinDependence(k=0.01) p3d_galPenin12_353.plotP2hCorrections() p3d_galPenin12_353.plotPInt(z=0.) p3d_galPenin12_353.plotP1hMMinDependence(k=0.01) p3d_galPenin12_353.plotP2hMMinDependence(k=0.01) ''' ################################################################################## # projection kernels to get 2d power spectra # from 3d power spectra, # for various tracers, for lensing convergence, for tSZ w_cmblens = WeightLensSingle(u, z_source=1100., name="cmblens") w_gallens = WeightLensSingle(u, z_source=1., name="gallens") w_y = WeightY(u) w_cmass = WeightTracerCMASS(u) w_wise = WeightTracerWISE(u) w_cib353 = WeightCIBPenin12(u, nu=353.e9, fluxCut=315.e-3, name='cibpenin12') w_qso = WeightTracerDESIQSO(u) w_lsstgold = WeightTracerLSSTGold(u) ''' # plot any projection kernel: # here, the galaxy lensing kernel, and the CMB lensing kernel w_gallens.plotW() w_cmblens.plotW() ''' ################################################################################## # 2d power spectra, in the Limber and flat sky approximations import p2d reload(p2d) from p2d import * # auto p2d_cmblenshalofit = P2dAuto(u, u, w_cmblens, nProc=3, name='halofit', save=False) p2d_cmblens = P2dAuto(u, p3d_d, w_cmblens, nProc=3, save=True) p2d_y = P2dAuto(u, p3d_y, w_y, nProc=3, save=False) p2d_gallens = P2dAuto(u, p3d_d, w_gallens, nProc=3, save=False) p2d_cmass = P2dAuto(u, p3d_d, w_cmass, pNoise=lambda l:1./w_cmass.ngal, nProc=3, save=False) p2d_wise = P2dAuto(u, p3d_d, w_wise, pNoise=lambda l:1./w_wise.ngal, nProc=3, save=False) p2d_lsstgold = P2dAuto(u, p3d_d, w_lsstgold, pNoise=lambda l:1./w_lsstgold.ngal, nProc=3, save=False) p2d_qso = P2dAuto(u, p3d_d, w_qso, pNoise=lambda l:1./w_qso.ngal, nProc=3, save=False) p2d_cib353 = P2dAuto(u, p3d_galPenin12_353, w_cib353, pNoise=w_cib353.fPshotNoise, save=False, nProc=3) # cross p2d_cmblensgallens = P2dCross(u, p3d_d, w_cmblens, w_gallens, nProc=3, save=False) p2d_cmasscmblens = P2dCross(u, p3d_d, w_cmass, w_cmblens, nProc=3, save=False) p2d_cmassgallens = P2dCross(u, p3d_d, w_cmass, w_gallens, nProc=3, save=False) p2d_wisegallens = P2dCross(u, p3d_d, w_wise, w_gallens, nProc=3, save=False) p2d_wisecmblens = P2dCross(u, p3d_d, w_wise, w_cmblens, nProc=3, save=False) p2d_lsstgoldcmblens = P2dCross(u, p3d_d, w_lsstgold, w_cmblens, nProc=3, save=False) ''' p2d_cmblens.plotP() p2d_y.plotP() p2d_cib353.plotP() p2d_cmblens.plotPCounterTerms() p2d_y.plotPCounterTerms() p2d_cmass.plotPCounterTerms() p2d_cib353.plotPCounterTerms() '''
EmmanuelSchaanREPO_NAMEHaloGenPATH_START.@HaloGen_extracted@HaloGen-master@driver.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "astropy/reproject", "repo_path": "reproject_extracted/reproject-main/reproject/adaptive/tests/__init__.py", "type": "Python" }
astropyREPO_NAMEreprojectPATH_START.@reproject_extracted@reproject-main@reproject@adaptive@tests@__init__.py@.PATH_END.py
{ "filename": "test_stub.py", "repo_name": "gotsunami/Youpi", "repo_path": "Youpi_extracted/Youpi-master/terapix/unittesting/test_stub.py", "type": "Python" }
""" Tests for the Condor Stub library """ import unittest, types, time import base64, marshal, sys from mock import Mock # from terapix.lib.cluster import condor from terapix.lib.cluster.stub import StubCondorQueue, StubCondorClient from terapix.lib.cluster.condor import CondorJob # class StubCondorQueueTest(unittest.TestCase): """ Tests the StubCondorQueue class """ def setUp(self): self.jobs, self.count = StubCondorQueue().getJobs() def test_getJobs_length(self): self.assertTrue(len(self.jobs) == 2) def test_getJobs_count(self): self.assertTrue(self.count == 2) def test_getJobs_type(self): for j in self.jobs: self.assertTrue(isinstance(j, CondorJob)) class StubCondorClientTest(unittest.TestCase): """ Tests the StubCondorClient class """ def setUp(self): self.c = StubCondorClient() def test_submit_return_type(self): self.assertEqual(type(self.c.submit(1,2)), types.TupleType) def test_getStatus_return_type(self): self.assertEqual(type(self.c.getStatus()), types.ListType) def test_getStatus_return_members(self): s = self.c.getStatus() for node in s: self.assertEqual(type(node), types.ListType) self.assertTrue(len(node) == 2) if __name__ == '__main__': if len(sys.argv) == 2: try: unittest.main(defaultTest = sys.argv[1]) except AttributeError: print "Error. No test with that name: %s" % sys.argv[1] else: unittest.main()
gotsunamiREPO_NAMEYoupiPATH_START.@Youpi_extracted@Youpi-master@terapix@unittesting@test_stub.py@.PATH_END.py
{ "filename": "_itertools.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/setuptools/py3/pkg_resources/_vendor/importlib_resources/_itertools.py", "type": "Python" }
from itertools import filterfalse from typing import ( Callable, Iterable, Iterator, Optional, Set, TypeVar, Union, ) # Type and type variable definitions _T = TypeVar('_T') _U = TypeVar('_U') def unique_everseen( iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None ) -> Iterator[_T]: "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen: Set[Union[_T, _U]] = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@setuptools@py3@pkg_resources@_vendor@importlib_resources@_itertools.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "rennehan/yt-swift", "repo_path": "yt-swift_extracted/yt-swift-main/yt/geometry/__init__.py", "type": "Python" }
rennehanREPO_NAMEyt-swiftPATH_START.@yt-swift_extracted@yt-swift-main@yt@geometry@__init__.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "gotsunami/Youpi", "repo_path": "Youpi_extracted/Youpi-master/terapix/youpi/templatetags/__init__.py", "type": "Python" }
gotsunamiREPO_NAMEYoupiPATH_START.@Youpi_extracted@Youpi-master@terapix@youpi@templatetags@__init__.py@.PATH_END.py
{ "filename": "test_spectrum.py", "repo_name": "gammapy/gammapy", "repo_path": "gammapy_extracted/gammapy-main/gammapy/datasets/tests/test_spectrum.py", "type": "Python" }
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_allclose, assert_equal import astropy.units as u from astropy.io import fits from astropy.table import Table from astropy.time import Time from astropy.utils.exceptions import AstropyUserWarning from gammapy.data import GTI from gammapy.datasets import Datasets, SpectrumDataset, SpectrumDatasetOnOff from gammapy.irf import EDispKernelMap, EffectiveAreaTable2D from gammapy.makers.utils import make_map_exposure_true_energy from gammapy.maps import LabelMapAxis, MapAxis, RegionGeom, RegionNDMap, WcsGeom from gammapy.modeling import Fit from gammapy.modeling.models import ( ConstantSpectralModel, ExpCutoffPowerLawSpectralModel, Models, PowerLawSpectralModel, SkyModel, ) from gammapy.utils.random import get_random_state from gammapy.utils.regions import compound_region_to_regions from gammapy.utils.testing import assert_time_allclose, mpl_plot_check, requires_data def test_data_shape(spectrum_dataset): assert spectrum_dataset.data_shape[0] == 30 def test_str(spectrum_dataset): assert "SpectrumDataset" in str(spectrum_dataset) def test_energy_range(spectrum_dataset): e_min, e_max = spectrum_dataset.energy_range assert e_min.unit == u.TeV assert e_max.unit == u.TeV assert_allclose(e_min, 0.1) assert_allclose(e_max, 10.0) def test_info_dict(spectrum_dataset): info_dict = spectrum_dataset.info_dict() assert_allclose(info_dict["counts"], 907010) assert_allclose(info_dict["background"], 3000.0) assert_allclose(info_dict["sqrt_ts"], 2924.522174) assert_allclose(info_dict["excess"], 904010) assert_allclose(info_dict["ontime"].value, 216000) assert info_dict["name"] == "test" def test_set_model(spectrum_dataset): spectrum_dataset = spectrum_dataset.copy() spectral_model = PowerLawSpectralModel() model = SkyModel(spectral_model=spectral_model, name="test") spectrum_dataset.models = model assert spectrum_dataset.models["test"] is model models = Models([model]) spectrum_dataset.models = models assert spectrum_dataset.models["test"] is model def test_spectrum_dataset_fits_io(spectrum_dataset, tmp_path): spectrum_dataset.meta_table = Table( data=[[1.0 * u.h], [111]], names=["livetime", "obs_id"] ) hdulist = spectrum_dataset.to_hdulist() actual = [hdu.name for hdu in hdulist] desired = [ "PRIMARY", "COUNTS", "COUNTS_BANDS", "COUNTS_REGION", "EXPOSURE", "EXPOSURE_BANDS", "EXPOSURE_REGION", "BACKGROUND", "BACKGROUND_BANDS", "BACKGROUND_REGION", "GTI", "META_TABLE", ] assert actual == desired spectrum_dataset.write(tmp_path / "test.fits") dataset_new = SpectrumDataset.read(tmp_path / "test.fits", name="test") assert_allclose(spectrum_dataset.counts.data, dataset_new.counts.data) assert_allclose( spectrum_dataset.npred_background().data, dataset_new.npred_background().data ) assert dataset_new.edisp is None assert dataset_new.edisp is None assert dataset_new.name == "test" assert_allclose(spectrum_dataset.exposure.data, dataset_new.exposure.data) assert spectrum_dataset.counts.geom == dataset_new.counts.geom assert_allclose(dataset_new.meta_table["obs_id"], 111) def test_npred_models(): e_reco = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=3) geom = RegionGeom(region=None, axes=[e_reco]) spectrum_dataset = SpectrumDataset.create(geom=geom) spectrum_dataset.exposure.quantity = 1e10 * u.Unit("cm2 h") pwl_1 = PowerLawSpectralModel(index=2) pwl_2 = PowerLawSpectralModel(index=2) model_1 = SkyModel(spectral_model=pwl_1) model_2 = SkyModel(spectral_model=pwl_2) spectrum_dataset.models = Models([model_1, model_2]) npred = spectrum_dataset.npred() assert_allclose(npred.data.sum(), 64.8) npred_sig = spectrum_dataset.npred_signal() assert_allclose(npred_sig.data.sum(), 64.8) npred_sig_model1 = spectrum_dataset.npred_signal(model_names=[model_1.name]) assert_allclose(npred_sig_model1.data.sum(), 32.4) assert_allclose( spectrum_dataset.npred_signal( model_names=[model_1.name, model_2.name] ).data.sum(), 64.8, ) npred_model1_not_stack = spectrum_dataset.npred_signal( model_names=[model_1.name], stack=False ) assert_allclose(npred_model1_not_stack.geom.data_shape, (1, 3, 1, 1)) assert_allclose(npred_model1_not_stack.data.sum(), 32.4) assert isinstance(npred_model1_not_stack.geom.axes[-1], LabelMapAxis) assert npred_model1_not_stack.geom.axes[-1].name == "models" assert_equal(npred_model1_not_stack.geom.axes[-1].center, [model_1.name]) npred_all_models_not_stack = spectrum_dataset.npred_signal( model_names=[model_1.name, model_2.name], stack=False ) assert_allclose(npred_all_models_not_stack.geom.data_shape, (2, 3, 1, 1)) assert_allclose( npred_all_models_not_stack.sum_over_axes(["models"]).data.sum(), 64.8 ) def test_npred_spatial_model(spectrum_dataset): model = SkyModel.create("pl", "gauss", name="test") spectrum_dataset.models = [model] npred = spectrum_dataset.npred() model.spatial_model.sigma.value = 1.0 npred_large_sigma = spectrum_dataset.npred() assert_allclose(npred.data.sum(), 3000) assert_allclose(npred_large_sigma.data.sum(), 3000) assert spectrum_dataset.evaluators["test"].psf is None def test_fit(spectrum_dataset): """Simple CASH fit to the on vector""" fit = Fit() result = fit.run(datasets=[spectrum_dataset]) assert result.success assert "minuit" in str(result) npred = spectrum_dataset.npred().data.sum() assert_allclose(npred, 907012.186399, rtol=1e-3) assert_allclose(result.total_stat, -18087404.624, rtol=1e-3) pars = spectrum_dataset.models.parameters assert_allclose(pars["index"].value, 2.1, rtol=1e-2) assert_allclose(pars["index"].error, 0.001276, rtol=1e-2) assert_allclose(pars["amplitude"].value, 1e5, rtol=1e-3) assert_allclose(pars["amplitude"].error, 153.450825, rtol=1e-2) def test_spectrum_dataset_create(): e_reco = MapAxis.from_edges(u.Quantity([0.1, 1, 10.0], "TeV"), name="energy") e_true = MapAxis.from_edges( u.Quantity([0.05, 0.5, 5, 20.0], "TeV"), name="energy_true" ) geom = RegionGeom(region=None, axes=[e_reco]) empty_spectrum_dataset = SpectrumDataset.create( geom, energy_axis_true=e_true, name="test" ) assert empty_spectrum_dataset.name == "test" assert empty_spectrum_dataset.counts.data.sum() == 0 assert empty_spectrum_dataset.data_shape[0] == 2 assert empty_spectrum_dataset.background.data.sum() == 0 assert empty_spectrum_dataset.background.geom.axes[0].nbin == 2 assert empty_spectrum_dataset.exposure.geom.axes[0].nbin == 3 assert empty_spectrum_dataset.edisp.edisp_map.geom.axes["energy"].nbin == 2 assert empty_spectrum_dataset.gti.time_sum.value == 0 assert len(empty_spectrum_dataset.gti.table) == 0 assert np.isnan(empty_spectrum_dataset.energy_range[0]) assert_allclose(empty_spectrum_dataset.mask_safe, 0) def test_spectrum_dataset_stack_diagonal_safe_mask(spectrum_dataset): geom = spectrum_dataset.counts.geom energy = MapAxis.from_energy_bounds("0.1 TeV", "10 TeV", nbin=30) energy_true = MapAxis.from_energy_bounds( "0.1 TeV", "10 TeV", nbin=30, name="energy_true" ) aeff = EffectiveAreaTable2D.from_parametrization( energy_axis_true=energy_true, instrument="HESS" ) livetime = 100 * u.s gti = GTI.create(start=0 * u.s, stop=livetime) geom_true = geom.as_energy_true exposure = make_map_exposure_true_energy( geom=geom_true, livetime=livetime, pointing=geom_true.center_skydir, aeff=aeff ) edisp = EDispKernelMap.from_diagonal_response( energy, energy_true, geom=geom.to_image() ) edisp.exposure_map.data = exposure.data[:, :, np.newaxis, :] background = spectrum_dataset.background mask_safe = RegionNDMap.from_geom(geom=geom, dtype=bool) mask_safe.data += True spectrum_dataset1 = SpectrumDataset( name="ds1", counts=spectrum_dataset.counts.copy(), exposure=exposure.copy(), edisp=edisp.copy(), background=background.copy(), gti=gti.copy(), mask_safe=mask_safe, ) livetime2 = 0.5 * livetime gti2 = GTI.create(start=200 * u.s, stop=200 * u.s + livetime2) bkg2 = RegionNDMap.from_geom(geom=geom, data=2 * background.data) geom = spectrum_dataset.counts.geom data = np.ones(spectrum_dataset.data_shape, dtype="bool") data[0] = False safe_mask2 = RegionNDMap.from_geom(geom=geom, data=data) exposure2 = exposure.copy() edisp = edisp.copy() edisp.exposure_map.data = exposure2.data[:, :, np.newaxis, :] spectrum_dataset2 = SpectrumDataset( name="ds2", counts=spectrum_dataset.counts.copy(), exposure=exposure2, edisp=edisp, background=bkg2, mask_safe=safe_mask2, gti=gti2, ) spectrum_dataset1.stack(spectrum_dataset2) reference = spectrum_dataset.counts.data assert_allclose(spectrum_dataset1.counts.data[1:], reference[1:] * 2) assert_allclose(spectrum_dataset1.counts.data[0], 141363) assert_allclose( spectrum_dataset1.exposure.quantity[0], 4.755644e09 * u.Unit("cm2 s") ) assert_allclose(spectrum_dataset1.background.data[1:], 3 * background.data[1:]) assert_allclose(spectrum_dataset1.background.data[0], background.data[0]) kernel = edisp.get_edisp_kernel() kernel_stacked = spectrum_dataset1.edisp.get_edisp_kernel() assert_allclose(kernel_stacked.pdf_matrix[1:], kernel.pdf_matrix[1:]) assert_allclose(kernel_stacked.pdf_matrix[0], 0.5 * kernel.pdf_matrix[0]) def test_spectrum_dataset_stack_nondiagonal_no_bkg(spectrum_dataset): energy = spectrum_dataset.counts.geom.axes["energy"] geom = spectrum_dataset.counts.geom edisp1 = EDispKernelMap.from_gauss( energy_axis=energy, energy_axis_true=energy.copy(name="energy_true"), sigma=0.1, bias=0, geom=geom.to_image(), ) edisp1.exposure_map.data += 1 aeff = EffectiveAreaTable2D.from_parametrization( energy_axis_true=energy.copy(name="energy_true"), instrument="HESS" ) livetime = 100 * u.s geom_true = geom.as_energy_true exposure = make_map_exposure_true_energy( geom=geom_true, livetime=livetime, pointing=geom_true.center_skydir, aeff=aeff ) geom = spectrum_dataset.counts.geom counts = RegionNDMap.from_geom(geom=geom) gti = GTI.create(start=0 * u.s, stop=livetime) spectrum_dataset1 = SpectrumDataset( counts=counts, exposure=exposure, edisp=edisp1, meta_table=Table({"OBS_ID": [0]}), gti=gti.copy(), ) edisp2 = EDispKernelMap.from_gauss( energy_axis=energy, energy_axis_true=energy.copy(name="energy_true"), sigma=0.2, bias=0.0, geom=geom, ) edisp2.exposure_map.data += 1 gti2 = GTI.create(start=100 * u.s, stop=200 * u.s) spectrum_dataset2 = SpectrumDataset( counts=counts, exposure=exposure.copy(), edisp=edisp2, meta_table=Table({"OBS_ID": [1]}), gti=gti2, ) spectrum_dataset1.stack(spectrum_dataset2) assert_allclose(spectrum_dataset1.meta_table["OBS_ID"][0], [0, 1]) assert spectrum_dataset1.background_model is None assert_allclose(spectrum_dataset1.gti.time_sum.to_value("s"), 200) assert_allclose( spectrum_dataset1.exposure.quantity[2].to_value("m2 s"), 1573851.079861 ) kernel = edisp1.get_edisp_kernel() assert_allclose(kernel.get_bias(1 * u.TeV), 0.0, atol=1.2e-3) assert_allclose(kernel.get_resolution(1 * u.TeV), 0.1581, atol=1e-2) def test_peek(spectrum_dataset): with mpl_plot_check(): spectrum_dataset.peek() with mpl_plot_check(): spectrum_dataset.plot_fit() spectrum_dataset.edisp = None with mpl_plot_check(): spectrum_dataset.peek() class TestSpectrumOnOff: """Test ON OFF SpectrumDataset""" def setup_method(self): etrue = np.logspace(-1, 1, 10) * u.TeV self.e_true = MapAxis.from_energy_edges(etrue, name="energy_true") ereco = np.logspace(-1, 1, 5) * u.TeV elo = ereco[:-1] self.e_reco = MapAxis.from_energy_edges(ereco, name="energy") start = u.Quantity([0], "s") stop = u.Quantity([1000], "s") time_ref = Time("2010-01-01 00:00:00.0") self.gti = GTI.create(start, stop, time_ref) self.livetime = self.gti.time_sum self.wcs = WcsGeom.create(npix=300, binsz=0.01, frame="icrs").wcs self.aeff = RegionNDMap.create( region="icrs;circle(0.,1.,0.1)", wcs=self.wcs, axes=[self.e_true], unit="cm2", ) self.aeff.data += 1 data = np.ones(elo.shape) data[-1] = 0 # to test stats calculation with empty bins axis = MapAxis.from_edges(ereco, name="energy", interp="log") self.on_counts = RegionNDMap.create( region="icrs;circle(0.,1.,0.1)", wcs=self.wcs, axes=[axis], meta={"EXPOSURE": self.livetime.to_value("s")}, ) self.on_counts.data += 1 self.on_counts.data[-1] = 0 self.off_counts = RegionNDMap.create( region="icrs;box(0.,1.,0.1, 0.2,30);box(-1.,-1.,0.1, 0.2,150)", wcs=self.wcs, axes=[axis], ) self.off_counts.data += 10 acceptance = RegionNDMap.from_geom(self.on_counts.geom) acceptance.data += 1 data = np.ones(elo.shape) data[-1] = 0 acceptance_off = RegionNDMap.from_geom(self.off_counts.geom) acceptance_off.data += 10 self.edisp = EDispKernelMap.from_diagonal_response( self.e_reco, self.e_true, self.on_counts.geom.to_image() ) exposure = self.aeff * self.livetime exposure.meta["livetime"] = self.livetime mask_safe = RegionNDMap.from_geom(self.on_counts.geom, dtype=bool) mask_safe.data += True self.dataset = SpectrumDatasetOnOff( counts=self.on_counts, counts_off=self.off_counts, exposure=exposure, edisp=self.edisp, acceptance=acceptance, acceptance_off=acceptance_off, name="test", gti=self.gti, mask_safe=mask_safe, ) def test_spectrum_dataset_on_off_create(self): e_reco = MapAxis.from_edges(u.Quantity([0.1, 1, 10.0], "TeV"), name="energy") e_true = MapAxis.from_edges( u.Quantity([0.05, 0.5, 5, 20.0], "TeV"), name="energy_true" ) geom = RegionGeom(region=None, axes=[e_reco]) empty_dataset = SpectrumDatasetOnOff.create(geom=geom, energy_axis_true=e_true) assert empty_dataset.counts.data.sum() == 0 assert empty_dataset.data_shape[0] == 2 assert empty_dataset.counts_off.data.sum() == 0 assert empty_dataset.counts_off.geom.axes[0].nbin == 2 assert_allclose(empty_dataset.acceptance_off, 0) assert_allclose(empty_dataset.acceptance, 0) assert empty_dataset.acceptance.data.shape[0] == 2 assert empty_dataset.acceptance_off.data.shape[0] == 2 assert empty_dataset.gti.time_sum.value == 0 assert len(empty_dataset.gti.table) == 0 assert np.isnan(empty_dataset.energy_range[0]) def test_create_stack(self): geom = RegionGeom(region=None, axes=[self.e_reco]) stacked = SpectrumDatasetOnOff.create(geom=geom, energy_axis_true=self.e_true) stacked.mask_safe.data += True stacked.stack(self.dataset) e_min_stacked, e_max_stacked = stacked.energy_range e_min_dataset, e_max_dataset = self.dataset.energy_range assert_allclose(e_min_stacked, e_min_dataset) assert_allclose(e_max_stacked, e_max_dataset) def test_alpha(self): assert self.dataset.alpha.data.shape == (4, 1, 1) assert_allclose(self.dataset.alpha.data, 0.1) def test_npred_no_edisp(self): const = 1 * u.Unit("cm-2 s-1 TeV-1") model = SkyModel(spectral_model=ConstantSpectralModel(const=const)) livetime = 1 * u.s aeff = RegionNDMap.create( region=self.aeff.geom.region, unit="cm2", axes=[self.e_reco.copy(name="energy_true")], ) aeff.data += 1 dataset = SpectrumDatasetOnOff( counts=self.on_counts, counts_off=self.off_counts, exposure=aeff * livetime, models=model, ) energy = aeff.geom.axes[0].edges expected = aeff.data[0] * (energy[-1] - energy[0]) * const * livetime assert_allclose(dataset.npred_signal().data.sum(), expected.value) def test_to_spectrum_dataset(self): ds = self.dataset.to_spectrum_dataset() assert isinstance(ds, SpectrumDataset) assert_allclose(ds.background.data.sum(), 4) def test_peek(self): dataset = self.dataset.copy() dataset.models = SkyModel(spectral_model=PowerLawSpectralModel()) with mpl_plot_check(): dataset.peek() def test_plot_fit(self): dataset = self.dataset.copy() dataset.models = SkyModel(spectral_model=PowerLawSpectralModel()) with mpl_plot_check(): dataset.plot_fit() def test_to_from_ogip_files(self, tmp_path): dataset = self.dataset.copy(name="test") dataset.write(tmp_path / "test.fits") newdataset = SpectrumDatasetOnOff.read(tmp_path / "test.fits") expected_regions = compound_region_to_regions(self.off_counts.geom.region) regions = compound_region_to_regions(newdataset.counts_off.geom.region) assert newdataset.counts.meta["RESPFILE"] == "test_rmf.fits" assert newdataset.counts.meta["BACKFILE"] == "test_bkg.fits" assert newdataset.counts.meta["ANCRFILE"] == "test_arf.fits" assert_allclose(self.on_counts.data, newdataset.counts.data) assert_allclose(self.off_counts.data, newdataset.counts_off.data) assert_allclose(self.edisp.edisp_map.data, newdataset.edisp.edisp_map.data) assert_time_allclose(newdataset.gti.time_start, dataset.gti.time_start) assert len(regions) == len(expected_regions) assert regions[0].center.is_equivalent_frame(expected_regions[0].center) assert_allclose(regions[1].angle, expected_regions[1].angle) def test_to_from_ogip_files_no_mask(self, tmp_path): dataset = self.dataset.copy(name="test") dataset.mask_safe = None dataset.write(tmp_path / "test.fits") newdataset = SpectrumDatasetOnOff.read(tmp_path / "test.fits") assert_allclose(newdataset.mask_safe.data, True) def test_to_from_ogip_files_zip(self, tmp_path): dataset = self.dataset.copy(name="test") dataset.write(tmp_path / "test.fits.gz") newdataset = SpectrumDatasetOnOff.read(tmp_path / "test.fits.gz") assert newdataset.counts.meta["RESPFILE"] == "test_rmf.fits.gz" assert newdataset.counts.meta["BACKFILE"] == "test_bkg.fits.gz" assert newdataset.counts.meta["ANCRFILE"] == "test_arf.fits.gz" def test_to_from_ogip_files_no_edisp(self, tmp_path): mask_safe = RegionNDMap.from_geom(self.on_counts.geom, dtype=bool) mask_safe.data += True acceptance = RegionNDMap.from_geom(self.on_counts.geom, data=1.0) exposure = self.aeff * self.livetime exposure.meta["livetime"] = self.livetime dataset = SpectrumDatasetOnOff( counts=self.on_counts, exposure=exposure, mask_safe=mask_safe, acceptance=acceptance, name="test", ) dataset.write(tmp_path / "pha_obstest.fits") newdataset = SpectrumDatasetOnOff.read(tmp_path / "pha_obstest.fits") assert_allclose(self.on_counts.data, newdataset.counts.data) assert newdataset.counts_off is None assert newdataset.edisp is None assert newdataset.gti is None def test_to_ogip_files_checksum(self, tmp_path): dataset = self.dataset.copy(name="test") dataset.write(tmp_path / "test.fits", format="ogip", checksum=True) for name in ["test.fits", "test_arf.fits", "test_rmf.fits", "test_bkg.fits"]: # TODO: this should not emit AstropyUserWarning with fits.open(tmp_path / name, checksum=True) as hdul: for hdu in hdul: assert "CHECKSUM" in hdu.header assert "DATASUM" in hdu.header def replace_in_fits_header(filename, string): with open(filename, "r+b") as file: chunk = file.read(10000) index = chunk.find(string.encode("ascii")) file.seek(index) file.write("bad".encode("ascii")) path = tmp_path / "test.fits" replace_in_fits_header(path, "unknown") with pytest.warns(AstropyUserWarning): SpectrumDatasetOnOff.read(path, checksum=True) def test_spectrum_dataset_onoff_fits_io(self, tmp_path): self.dataset.write(tmp_path / "test.fits", format="gadf") d1 = SpectrumDatasetOnOff.read(tmp_path / "test.fits", format="gadf") assert isinstance(d1.counts.geom, RegionGeom) assert d1.exposure == self.dataset.exposure assert_allclose(d1.counts_off.data, self.dataset.counts_off.data) def test_energy_mask(self): mask = self.dataset.counts.geom.energy_mask( energy_min=0.3 * u.TeV, energy_max=6 * u.TeV ) desired = [False, True, True, False] assert_allclose(mask.data[:, 0, 0], desired) mask = self.dataset.counts.geom.energy_mask(energy_max=6 * u.TeV) desired = [True, True, True, False] assert_allclose(mask.data[:, 0, 0], desired) mask = self.dataset.counts.geom.energy_mask(energy_min=1 * u.TeV) desired = [False, False, True, True] assert_allclose(mask.data[:, 0, 0], desired) def test_str(self): model = SkyModel(spectral_model=PowerLawSpectralModel()) dataset = SpectrumDatasetOnOff( counts=self.on_counts, counts_off=self.off_counts, models=model, exposure=self.aeff * self.livetime, edisp=self.edisp, acceptance=RegionNDMap.from_geom(geom=self.on_counts.geom, data=1), acceptance_off=RegionNDMap.from_geom(geom=self.off_counts.geom, data=10), ) assert "SpectrumDatasetOnOff" in str(dataset) assert "wstat" in str(dataset) def test_fake(self): """Test the fake dataset""" source_model = SkyModel(spectral_model=PowerLawSpectralModel()) dataset = SpectrumDatasetOnOff( name="test", counts=self.on_counts, counts_off=self.off_counts, models=source_model, exposure=self.aeff * self.livetime, edisp=self.edisp, acceptance=RegionNDMap.from_geom(geom=self.on_counts.geom, data=1), acceptance_off=RegionNDMap.from_geom(geom=self.off_counts.geom, data=10), ) real_dataset = dataset.copy() background = RegionNDMap.from_geom(dataset.counts.geom) background.data += 1 dataset.fake(npred_background=background, random_state=314) assert real_dataset.counts.data.shape == dataset.counts.data.shape assert real_dataset.counts_off.data.shape == dataset.counts_off.data.shape assert dataset.counts_off.data.sum() == 39 assert dataset.counts.data.sum() == 5 def test_info_dict(self): info_dict = self.dataset.info_dict() assert_allclose(info_dict["counts"], 3) assert_allclose(info_dict["counts_off"], 40) assert_allclose(info_dict["acceptance"], 4) assert_allclose(info_dict["acceptance_off"], 40) assert_allclose(info_dict["alpha"], 0.1) assert_allclose(info_dict["excess"], -1, rtol=1e-2) assert_allclose(info_dict["ontime"].value, 1e3) assert_allclose(info_dict["sqrt_ts"], -0.501005, rtol=1e-2) assert info_dict["name"] == "test" def test_resample_energy_axis(self): axis = MapAxis.from_edges([0.1, 1, 10] * u.TeV, name="energy", interp="log") grouped = self.dataset.resample_energy_axis(energy_axis=axis) assert grouped.counts.data.shape == (2, 1, 1) # exposure should be untouched assert_allclose(grouped.exposure.data, 1000) assert_allclose(np.squeeze(grouped.counts), [2, 1]) assert_allclose(np.squeeze(grouped.counts_off), [20, 20]) assert grouped.edisp.edisp_map.data.shape == (9, 2, 1, 1) assert_allclose(np.squeeze(grouped.acceptance), [2, 2]) assert_allclose(np.squeeze(grouped.acceptance_off), [20, 20]) def test_to_image(self): grouped = self.dataset.to_image() assert grouped.counts.data.shape == (1, 1, 1) # exposure should be untouched assert_allclose(grouped.exposure.data, 1000) assert_allclose(np.squeeze(grouped.counts), 3) assert_allclose(np.squeeze(grouped.counts_off), 40) assert grouped.edisp.edisp_map.data.shape == (9, 1, 1, 1) assert_allclose(np.squeeze(grouped.acceptance), 4) assert_allclose(np.squeeze(grouped.acceptance_off), 40) @requires_data() class TestSpectralFit: """Test fit in astrophysical scenario""" def setup_method(self): path = "$GAMMAPY_DATA/joint-crab/spectra/hess/" self.datasets = Datasets( [ SpectrumDatasetOnOff.read(path + "pha_obs23523.fits"), SpectrumDatasetOnOff.read(path + "pha_obs23592.fits"), ] ) self.pwl = SkyModel( spectral_model=PowerLawSpectralModel( index=2, amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV ) ) self.ecpl = SkyModel( spectral_model=ExpCutoffPowerLawSpectralModel( index=2, amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV, lambda_=0.1 / u.TeV, ) ) # Example fit for one observation self.datasets[0].models = self.pwl self.fit = Fit() def set_model(self, model): for obs in self.datasets: obs.models = model def test_basic_results(self): self.set_model(self.pwl) result = self.fit.run([self.datasets[0]]) pars = self.datasets.parameters assert self.pwl is self.datasets[0].models[0] assert_allclose(result.total_stat, 38.343, rtol=1e-3) assert_allclose(pars["index"].value, 2.817, rtol=1e-3) assert pars["amplitude"].unit == "cm-2 s-1 TeV-1" assert_allclose(pars["amplitude"].value, 5.142e-11, rtol=1e-3) assert_allclose(self.datasets[0].npred().data[60], 0.6102, rtol=1e-3) pars.to_table() def test_basic_errors(self): self.set_model(self.pwl) self.fit.run([self.datasets[0]]) pars = self.pwl.parameters assert_allclose(pars["index"].error, 0.149633, rtol=1e-3) assert_allclose(pars["amplitude"].error, 6.423139e-12, rtol=1e-3) pars.to_table() def test_ecpl_fit(self): self.set_model(self.ecpl) fit = Fit() fit.run([self.datasets[0]]) actual = self.datasets.parameters["lambda_"].quantity assert actual.unit == "TeV-1" assert_allclose(actual.value, 0.145215, rtol=1e-2) def test_joint_fit(self): self.set_model(self.pwl) fit = Fit() fit.run(self.datasets) actual = self.datasets.parameters["index"].value assert_allclose(actual, 2.7806, rtol=1e-3) actual = self.datasets.parameters["amplitude"].quantity assert actual.unit == "cm-2 s-1 TeV-1" assert_allclose(actual.value, 5.200e-11, rtol=1e-3) def test_stats(self): dataset = self.datasets[0].copy() dataset.models = self.pwl fit = Fit() result = fit.run(datasets=[dataset]) stats = dataset.stat_array() actual = np.sum(stats[dataset.mask_safe]) desired = result.total_stat assert_allclose(actual, desired) def test_fit_range(self): # Fit range not restricted fit range should be the thresholds obs = self.datasets[0] actual = obs.energy_range[0] assert actual.unit == "keV" assert_allclose(actual, 8.912509e08) def test_no_edisp(self): dataset = self.datasets[0].copy() dataset.edisp = None dataset.models = self.pwl fit = Fit() fit.run(datasets=[dataset]) assert_allclose(self.pwl.spectral_model.index.value, 2.7961, atol=0.02) def test_stacked_fit(self): dataset = self.datasets[0].copy() dataset.stack(self.datasets[1]) dataset.models = SkyModel(PowerLawSpectralModel()) fit = Fit() fit.run(datasets=[dataset]) pars = dataset.models.parameters assert_allclose(pars["index"].value, 2.7767, rtol=1e-3) assert u.Unit(pars["amplitude"].unit) == "cm-2 s-1 TeV-1" assert_allclose(pars["amplitude"].value, 5.191e-11, rtol=1e-3) def _read_hess_obs(): path = "$GAMMAPY_DATA/joint-crab/spectra/hess/" obs1 = SpectrumDatasetOnOff.read(path + "pha_obs23523.fits") obs2 = SpectrumDatasetOnOff.read(path + "pha_obs23592.fits") return [obs1, obs2] def make_gti(times, time_ref="2010-01-01"): return GTI.create(times["START"], times["STOP"], time_ref) @requires_data("gammapy-data") def make_observation_list(): """obs with dummy IRF""" nbin = 3 energy = np.logspace(-1, 1, nbin + 1) * u.TeV livetime = 2 * u.h data_on = np.arange(nbin) dataoff_1 = np.ones(3) dataoff_2 = np.ones(3) * 3 dataoff_1[1] = 0 dataoff_2[1] = 0 axis = MapAxis.from_edges(energy, name="energy", interp="log") axis_true = axis.copy(name="energy_true") geom = RegionGeom(region=None, axes=[axis]) geom_true = RegionGeom(region=None, axes=[axis_true]) on_vector = RegionNDMap.from_geom(geom=geom, data=data_on) off_vector1 = RegionNDMap.from_geom(geom=geom, data=dataoff_1) off_vector2 = RegionNDMap.from_geom(geom=geom, data=dataoff_2) mask_safe = RegionNDMap.from_geom(geom, dtype=bool) mask_safe.data += True acceptance = RegionNDMap.from_geom(geom=geom, data=1) acceptance_off_1 = RegionNDMap.from_geom(geom=geom, data=2) acceptance_off_2 = RegionNDMap.from_geom(geom=geom, data=4) aeff = RegionNDMap.from_geom(geom_true, data=1, unit="m2") edisp = EDispKernelMap.from_gauss( energy_axis=axis, energy_axis_true=axis_true, sigma=0.2, bias=0, geom=geom ) time_ref = Time("2010-01-01") gti1 = make_gti( {"START": [5, 6, 1, 2] * u.s, "STOP": [8, 7, 3, 4] * u.s}, time_ref=time_ref ) gti2 = make_gti({"START": [14] * u.s, "STOP": [15] * u.s}, time_ref=time_ref) exposure = aeff * livetime exposure.meta["livetime"] = livetime obs1 = SpectrumDatasetOnOff( counts=on_vector, counts_off=off_vector1, exposure=exposure, edisp=edisp, mask_safe=mask_safe, acceptance=acceptance.copy(), acceptance_off=acceptance_off_1, name="1", gti=gti1, ) obs2 = SpectrumDatasetOnOff( counts=on_vector, counts_off=off_vector2, exposure=exposure.copy(), edisp=edisp, mask_safe=mask_safe, acceptance=acceptance.copy(), acceptance_off=acceptance_off_2, name="2", gti=gti2, ) obs_list = [obs1, obs2] return obs_list @requires_data("gammapy-data") class TestSpectrumDatasetOnOffStack: def setup_method(self): self.datasets = _read_hess_obs() # Change threshold to make stuff more interesting geom = self.datasets[0]._geom self.datasets[0].mask_safe = geom.energy_mask( energy_min=1.2 * u.TeV, energy_max=50 * u.TeV ) mask = geom.energy_mask(energy_max=20 * u.TeV) self.datasets[1].mask_safe &= mask self.stacked_dataset = self.datasets[0].to_masked() self.stacked_dataset.stack(self.datasets[1]) def test_basic(self): obs_1, obs_2 = self.datasets counts1 = obs_1.counts.data[obs_1.mask_safe].sum() counts2 = obs_2.counts.data[obs_2.mask_safe].sum() summed_counts = counts1 + counts2 stacked_counts = self.stacked_dataset.counts.data.sum() off1 = obs_1.counts_off.data[obs_1.mask_safe].sum() off2 = obs_2.counts_off.data[obs_2.mask_safe].sum() summed_off = off1 + off2 stacked_off = self.stacked_dataset.counts_off.data.sum() assert summed_counts == stacked_counts assert summed_off == stacked_off def test_thresholds(self): energy_min, energy_max = self.stacked_dataset.energy_range assert energy_min.unit == "keV" assert_allclose(energy_min, 8.912509e08, rtol=1e-3) assert energy_max.unit == "keV" assert_allclose(energy_max, 4.466836e10, rtol=1e-3) def test_verify_npred(self): """Verifying npred is preserved during the stacking""" pwl = SkyModel( spectral_model=PowerLawSpectralModel( index=2, amplitude=2e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV ) ) self.stacked_dataset.models = pwl npred_stacked = self.stacked_dataset.npred_signal().data npred_stacked[~self.stacked_dataset.mask_safe.data] = 0 npred_summed = np.zeros_like(npred_stacked) for dataset in self.datasets: dataset.models = pwl npred_summed[dataset.mask_safe] += dataset.npred_signal().data[ dataset.mask_safe ] assert_allclose(npred_stacked, npred_summed, rtol=1e-6) def test_stack_backscal(self): """Verify backscal stacking""" obs1, obs2 = make_observation_list() obs1.stack(obs2) assert_allclose(obs1.alpha.data[0], 1.25 / 4.0) # When the OFF stack observation counts=0, the alpha is averaged on the # total OFF counts for each run. assert_allclose(obs1.alpha.data[1], 2.5 / 8.0) def test_stack_gti(self): obs1, obs2 = make_observation_list() obs1.stack(obs2) assert_allclose(obs1.gti.met_start.value, [1.0, 5.0, 14.0]) assert_allclose(obs1.gti.met_stop.value, [4.0, 8.0, 15.0]) @requires_data("gammapy-data") def test_datasets_stack_reduce(): datasets = Datasets() obs_ids = [23523, 23526, 23559, 23592] for obs_id in obs_ids: filename = f"$GAMMAPY_DATA/joint-crab/spectra/hess/pha_obs{obs_id}.fits" ds = SpectrumDatasetOnOff.read(filename) datasets.append(ds) stacked = datasets.stack_reduce(name="stacked") assert_allclose(stacked.exposure.meta["livetime"].to_value("s"), 6313.8116406202325) info_table = datasets.info_table() assert_allclose(info_table["counts"], [124, 126, 119, 90]) info_table_cum = datasets.info_table(cumulative=True) assert_allclose(info_table_cum["counts"], [124, 250, 369, 459]) assert stacked.name == "stacked" @requires_data("gammapy-data") def test_datasets_stack_reduce_no_off(): datasets = Datasets() obs_ids = [23523, 23526, 23559, 23592] for obs_id in obs_ids: filename = f"$GAMMAPY_DATA/joint-crab/spectra/hess/pha_obs{obs_id}.fits" ds = SpectrumDatasetOnOff.read(filename) datasets.append(ds) datasets[-1].counts_off = None with pytest.raises(ValueError): stacked = datasets.stack_reduce(name="stacked") datasets[-1].mask_safe.data[...] = False stacked = datasets.stack_reduce(name="stacked") assert_allclose(stacked.exposure.meta["livetime"].to_value("s"), 4732.5469999) assert stacked.counts == 369 datasets[0].mask_safe.data[...] = False stacked = datasets.stack_reduce(name="stacked") assert_allclose(stacked.exposure.meta["livetime"].to_value("s"), 3150.81024152) assert stacked.counts == 245 @requires_data("gammapy-data") def test_stack_livetime(): dataset_ref = SpectrumDatasetOnOff.read( "$GAMMAPY_DATA/joint-crab/spectra/hess/pha_obs23523.fits" ) energy_axis = dataset_ref.counts.geom.axes["energy"] energy_axis_true = dataset_ref.exposure.geom.axes["energy_true"] geom = RegionGeom(region=None, axes=[energy_axis]) dataset = SpectrumDatasetOnOff.create(geom=geom, energy_axis_true=energy_axis_true) dataset.stack(dataset_ref) assert_allclose(dataset.exposure.meta["livetime"], 1581.736758 * u.s) dataset.stack(dataset_ref) assert_allclose(dataset.exposure.meta["livetime"], 2 * 1581.736758 * u.s) def test_spectrum_dataset_on_off_to_yaml(tmpdir): spectrum_datasets_on_off = make_observation_list() datasets = Datasets(spectrum_datasets_on_off) datasets.write( filename=tmpdir / "datasets.yaml", filename_models=tmpdir / "models.yaml" ) datasets_read = Datasets.read( filename=tmpdir / "datasets.yaml", filename_models=tmpdir / "models.yaml" ) assert len(datasets_read) == len(datasets) assert datasets_read[0].name == datasets[0].name assert datasets_read[1].name == datasets[1].name assert datasets_read[1].counts.data.sum() == datasets[1].counts.data.sum() class TestFit: """Test fit on counts spectra without any IRFs""" def setup_method(self): self.nbins = 30 energy = np.logspace(-1, 1, self.nbins + 1) * u.TeV self.source_model = SkyModel( spectral_model=PowerLawSpectralModel( index=2, amplitude=1e5 * u.Unit("cm-2 s-1 TeV-1"), reference=0.1 * u.TeV ) ) bkg_model = PowerLawSpectralModel( index=3, amplitude=1e4 * u.Unit("cm-2 s-1 TeV-1"), reference=0.1 * u.TeV ) self.alpha = 0.1 random_state = get_random_state(23) npred = self.source_model.spectral_model.integral(energy[:-1], energy[1:]).value source_counts = random_state.poisson(npred) axis = MapAxis.from_edges(energy, name="energy", interp="log") geom = RegionGeom(region=None, axes=[axis]) self.src = RegionNDMap.from_geom(geom=geom, data=source_counts) self.exposure = RegionNDMap.from_geom(geom.as_energy_true, data=1, unit="cm2 s") npred_bkg = bkg_model.integral(energy[:-1], energy[1:]).value bkg_counts = random_state.poisson(npred_bkg) off_counts = random_state.poisson(npred_bkg * 1.0 / self.alpha) self.bkg = RegionNDMap.from_geom(geom=geom, data=bkg_counts) self.off = RegionNDMap.from_geom(geom=geom, data=off_counts) def test_cash(self): """Simple CASH fit to the on vector""" dataset = SpectrumDataset( models=self.source_model, counts=self.src, exposure=self.exposure, ) npred = dataset.npred().data assert_allclose(npred[5], 660.5171, rtol=1e-5) stat_val = dataset.stat_sum() assert_allclose(stat_val, -107346.5291, rtol=1e-5) self.source_model.parameters["index"].value = 1.12 fit = Fit() fit.run(datasets=[dataset]) # These values are check with sherpa fits, do not change pars = self.source_model.parameters assert_allclose(pars["index"].value, 1.995525, rtol=1e-3) assert_allclose(pars["amplitude"].value, 100245.9, rtol=1e-3) def test_wstat(self): """WStat with on source and background spectrum""" on_vector = self.src.copy() on_vector.data += self.bkg.data acceptance = RegionNDMap.from_geom(self.src.geom, data=1) acceptance_off = RegionNDMap.from_geom(self.bkg.geom, data=1 / self.alpha) dataset = SpectrumDatasetOnOff( counts=on_vector, counts_off=self.off, exposure=self.exposure, acceptance=acceptance, acceptance_off=acceptance_off, ) dataset.models = self.source_model self.source_model.parameters.index = 1.12 fit = Fit() result = fit.run(datasets=[dataset]) pars = self.source_model.parameters assert_allclose(pars["index"].value, 1.997342, rtol=1e-3) assert_allclose(pars["amplitude"].value, 100245.187067, rtol=1e-3) assert_allclose(result.total_stat, 30.022316, rtol=1e-3) def test_fit_range(self): """Test fit range without complication of thresholds""" geom = self.src.geom mask_safe = RegionNDMap.from_geom(geom, dtype=bool) mask_safe.data += True dataset = SpectrumDatasetOnOff(counts=self.src, mask_safe=mask_safe) assert np.sum(dataset.mask_safe) == self.nbins energy_min, energy_max = dataset.energy_range assert_allclose(energy_max, 10) assert_allclose(energy_min, 0.1) def test_stat_profile(self): geom = self.src.geom mask_safe = RegionNDMap.from_geom(geom, dtype=bool) mask_safe.data += True dataset = SpectrumDataset( models=self.source_model, exposure=self.exposure, counts=self.src, mask_safe=mask_safe, ) fit = Fit() fit.run(datasets=[dataset]) true_idx = self.source_model.parameters["index"].value values = np.linspace(0.95 * true_idx, 1.05 * true_idx, 100) self.source_model.spectral_model.index.scan_values = values profile = fit.stat_profile(datasets=[dataset], parameter="index") actual = values[np.argmin(profile["stat_scan"])] assert_allclose(actual, true_idx, rtol=0.01) def test_stat_sum(): axis = MapAxis.from_energy_bounds(0.1, 10, 5, unit="TeV") geom = RegionGeom.create(None, axes=[axis]) dataset = SpectrumDatasetOnOff.create(geom) dataset.counts_off = None stat = dataset.stat_sum() assert stat == 0 dataset.mask_safe.data[0] = True with pytest.raises(AttributeError): dataset.stat_sum()
gammapyREPO_NAMEgammapyPATH_START.@gammapy_extracted@gammapy-main@gammapy@datasets@tests@test_spectrum.py@.PATH_END.py
{ "filename": "_data.py", "repo_name": "scipy/scipy", "repo_path": "scipy_extracted/scipy-main/scipy/sparse/_data.py", "type": "Python" }
"""Base class for sparse matrice with a .data attribute subclasses must provide a _with_data() method that creates a new matrix with the same sparsity pattern as self but with a different data array """ import math import numpy as np from ._base import _spbase, sparray, _ufuncs_with_fixed_point_at_zero from ._sputils import isscalarlike, validateaxis __all__ = [] # TODO implement all relevant operations # use .data.__methods__() instead of /=, *=, etc. class _data_matrix(_spbase): def __init__(self, arg1, *, maxprint=None): _spbase.__init__(self, arg1, maxprint=maxprint) @property def dtype(self): return self.data.dtype @dtype.setter def dtype(self, newtype): self.data.dtype = newtype def _deduped_data(self): if hasattr(self, 'sum_duplicates'): self.sum_duplicates() return self.data def __abs__(self): return self._with_data(abs(self._deduped_data())) def __round__(self, ndigits=0): return self._with_data(np.around(self._deduped_data(), decimals=ndigits)) def _real(self): return self._with_data(self.data.real) def _imag(self): return self._with_data(self.data.imag) def __neg__(self): if self.dtype.kind == 'b': raise NotImplementedError('negating a boolean sparse array is not ' 'supported') return self._with_data(-self.data) def __imul__(self, other): # self *= other if isscalarlike(other): self.data *= other return self return NotImplemented def __itruediv__(self, other): # self /= other if isscalarlike(other): recip = 1.0 / other self.data *= recip return self else: return NotImplemented def astype(self, dtype, casting='unsafe', copy=True): dtype = np.dtype(dtype) if self.dtype != dtype: matrix = self._with_data( self.data.astype(dtype, casting=casting, copy=True), copy=True ) return matrix._with_data(matrix._deduped_data(), copy=False) elif copy: return self.copy() else: return self astype.__doc__ = _spbase.astype.__doc__ def conjugate(self, copy=True): if np.issubdtype(self.dtype, np.complexfloating): return self._with_data(self.data.conjugate(), copy=copy) elif copy: return self.copy() else: return self conjugate.__doc__ = _spbase.conjugate.__doc__ def copy(self): return self._with_data(self.data.copy(), copy=True) copy.__doc__ = _spbase.copy.__doc__ def power(self, n, dtype=None): """ This function performs element-wise power. Parameters ---------- n : scalar n is a non-zero scalar (nonzero avoids dense ones creation) If zero power is desired, special case it to use `np.ones` dtype : If dtype is not specified, the current dtype will be preserved. Raises ------ NotImplementedError : if n is a zero scalar If zero power is desired, special case it to use ``np.ones(A.shape, dtype=A.dtype)`` """ if not isscalarlike(n): raise NotImplementedError("input is not scalar") if not n: raise NotImplementedError( "zero power is not supported as it would densify the matrix.\n" "Use `np.ones(A.shape, dtype=A.dtype)` for this case." ) data = self._deduped_data() if dtype is not None: data = data.astype(dtype) return self._with_data(data ** n) ########################### # Multiplication handlers # ########################### def _mul_scalar(self, other): return self._with_data(self.data * other) # Add the numpy unary ufuncs for which func(0) = 0 to _data_matrix. for npfunc in _ufuncs_with_fixed_point_at_zero: name = npfunc.__name__ def _create_method(op): def method(self): result = op(self._deduped_data()) return self._with_data(result, copy=True) method.__doc__ = (f"Element-wise {name}.\n\n" f"See `numpy.{name}` for more information.") method.__name__ = name return method setattr(_data_matrix, name, _create_method(npfunc)) def _find_missing_index(ind, n): for k, a in enumerate(ind): if k != a: return k k += 1 if k < n: return k else: return -1 class _minmax_mixin: """Mixin for min and max methods. These are not implemented for dia_matrix, hence the separate class. """ def _min_or_max_axis(self, axis, min_or_max, explicit): N = self.shape[axis] if N == 0: raise ValueError("zero-size array to reduction operation") M = self.shape[1 - axis] idx_dtype = self._get_index_dtype(maxval=M) mat = self.tocsc() if axis == 0 else self.tocsr() mat.sum_duplicates() major_index, value = mat._minor_reduce(min_or_max) if not explicit: not_full = np.diff(mat.indptr)[major_index] < N value[not_full] = min_or_max(value[not_full], 0) mask = value != 0 major_index = np.compress(mask, major_index).astype(idx_dtype, copy=False) value = np.compress(mask, value) if isinstance(self, sparray): coords = (major_index,) shape = (M,) return self._coo_container((value, coords), shape=shape, dtype=self.dtype) if axis == 0: return self._coo_container( (value, (np.zeros(len(value), dtype=idx_dtype), major_index)), dtype=self.dtype, shape=(1, M) ) else: return self._coo_container( (value, (major_index, np.zeros(len(value), dtype=idx_dtype))), dtype=self.dtype, shape=(M, 1) ) def _min_or_max(self, axis, out, min_or_max, explicit): if out is not None: raise ValueError("Sparse arrays do not support an 'out' parameter.") validateaxis(axis) if self.ndim == 1: if axis not in (None, 0, -1): raise ValueError("axis out of range") axis = None # avoid calling special axis case. no impact on 1d if axis is None: if 0 in self.shape: raise ValueError("zero-size array to reduction operation") zero = self.dtype.type(0) if self.nnz == 0: return zero m = min_or_max.reduce(self._deduped_data().ravel()) if self.nnz != math.prod(self.shape) and not explicit: m = min_or_max(zero, m) return m if axis < 0: axis += 2 if (axis == 0) or (axis == 1): return self._min_or_max_axis(axis, min_or_max, explicit) else: raise ValueError("axis out of range") def _arg_min_or_max_axis(self, axis, argmin_or_argmax, compare, explicit): if self.shape[axis] == 0: raise ValueError("Cannot apply the operation along a zero-sized dimension.") if axis < 0: axis += 2 zero = self.dtype.type(0) mat = self.tocsc() if axis == 0 else self.tocsr() mat.sum_duplicates() ret_size, line_size = mat._swap(mat.shape) ret = np.zeros(ret_size, dtype=int) nz_lines, = np.nonzero(np.diff(mat.indptr)) for i in nz_lines: p, q = mat.indptr[i:i + 2] data = mat.data[p:q] indices = mat.indices[p:q] extreme_index = argmin_or_argmax(data) extreme_value = data[extreme_index] if explicit: if q - p > 0: ret[i] = indices[extreme_index] else: if compare(extreme_value, zero) or q - p == line_size: ret[i] = indices[extreme_index] else: zero_ind = _find_missing_index(indices, line_size) if extreme_value == zero: ret[i] = min(extreme_index, zero_ind) else: ret[i] = zero_ind if isinstance(self, sparray): return ret if axis == 1: ret = ret.reshape(-1, 1) return self._ascontainer(ret) def _arg_min_or_max(self, axis, out, argmin_or_argmax, compare, explicit): if out is not None: raise ValueError("Sparse types do not support an 'out' parameter.") validateaxis(axis) if self.ndim == 1: if axis not in (None, 0, -1): raise ValueError("axis out of range") axis = None # avoid calling special axis case. no impact on 1d if axis is not None: return self._arg_min_or_max_axis(axis, argmin_or_argmax, compare, explicit) if 0 in self.shape: raise ValueError("Cannot apply the operation to an empty matrix.") if self.nnz == 0: if explicit: raise ValueError("Cannot apply the operation to zero matrix " "when explicit=True.") return 0 zero = self.dtype.type(0) mat = self.tocoo() # Convert to canonical form: no duplicates, sorted indices. mat.sum_duplicates() extreme_index = argmin_or_argmax(mat.data) if explicit: return extreme_index extreme_value = mat.data[extreme_index] num_col = mat.shape[-1] # If the min value is less than zero, or max is greater than zero, # then we do not need to worry about implicit zeros. if compare(extreme_value, zero): # cast to Python int to avoid overflow and RuntimeError return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index]) # Cheap test for the rare case where we have no implicit zeros. size = math.prod(self.shape) if size == mat.nnz: return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index]) # At this stage, any implicit zero could be the min or max value. # After sum_duplicates(), the `row` and `col` arrays are guaranteed to # be sorted in C-order, which means the linearized indices are sorted. linear_indices = mat.row * num_col + mat.col first_implicit_zero_index = _find_missing_index(linear_indices, size) if extreme_value == zero: return min(first_implicit_zero_index, extreme_index) return first_implicit_zero_index def max(self, axis=None, out=None, *, explicit=False): """Return the maximum of the array/matrix or maximum along an axis. By default, all elements are taken into account, not just the non-zero ones. But with `explicit` set, only the stored elements are considered. Parameters ---------- axis : {-2, -1, 0, 1, None} optional Axis along which the sum is computed. The default is to compute the maximum over all elements, returning a scalar (i.e., `axis` = `None`). out : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used. explicit : {False, True} optional (default: False) When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column. .. versionadded:: 1.15.0 Returns ------- amax : coo_array or scalar Maximum of `a`. If `axis` is None, the result is a scalar value. If `axis` is given, the result is a sparse.coo_array of dimension ``a.ndim - 1``. See Also -------- min : The minimum value of a sparse array/matrix along a given axis. numpy.max : NumPy's implementation of 'max' """ return self._min_or_max(axis, out, np.maximum, explicit) def min(self, axis=None, out=None, *, explicit=False): """Return the minimum of the array/matrix or maximum along an axis. By default, all elements are taken into account, not just the non-zero ones. But with `explicit` set, only the stored elements are considered. Parameters ---------- axis : {-2, -1, 0, 1, None} optional Axis along which the sum is computed. The default is to compute the minimum over all elements, returning a scalar (i.e., `axis` = `None`). out : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used. explicit : {False, True} optional (default: False) When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column. .. versionadded:: 1.15.0 Returns ------- amin : coo_matrix or scalar Minimum of `a`. If `axis` is None, the result is a scalar value. If `axis` is given, the result is a sparse.coo_array of dimension ``a.ndim - 1``. See Also -------- max : The maximum value of a sparse array/matrix along a given axis. numpy.min : NumPy's implementation of 'min' """ return self._min_or_max(axis, out, np.minimum, explicit) def nanmax(self, axis=None, out=None, *, explicit=False): """Return the maximum, ignoring any Nans, along an axis. Return the maximum, ignoring any Nans, of the array/matrix along an axis. By default this takes all elements into account, but with `explicit` set, only stored elements are considered. .. versionadded:: 1.11.0 Parameters ---------- axis : {-2, -1, 0, 1, None} optional Axis along which the maximum is computed. The default is to compute the maximum over all elements, returning a scalar (i.e., `axis` = `None`). out : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used. explicit : {False, True} optional (default: False) When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column. .. versionadded:: 1.15.0 Returns ------- amax : coo_array or scalar Maximum of `a`. If `axis` is None, the result is a scalar value. If `axis` is given, the result is a sparse.coo_array of dimension ``a.ndim - 1``. See Also -------- nanmin : The minimum value of a sparse array/matrix along a given axis, ignoring NaNs. max : The maximum value of a sparse array/matrix along a given axis, propagating NaNs. numpy.nanmax : NumPy's implementation of 'nanmax'. """ return self._min_or_max(axis, out, np.fmax, explicit) def nanmin(self, axis=None, out=None, *, explicit=False): """Return the minimum, ignoring any Nans, along an axis. Return the minimum, ignoring any Nans, of the array/matrix along an axis. By default this takes all elements into account, but with `explicit` set, only stored elements are considered. .. versionadded:: 1.11.0 Parameters ---------- axis : {-2, -1, 0, 1, None} optional Axis along which the minimum is computed. The default is to compute the minimum over all elements, returning a scalar (i.e., `axis` = `None`). out : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used. explicit : {False, True} optional (default: False) When set to True, only the stored elements will be considered. If a row/column is empty, the sparse.coo_array returned has no stored element (i.e. an implicit zero) for that row/column. .. versionadded:: 1.15.0 Returns ------- amin : coo_array or scalar Minimum of `a`. If `axis` is None, the result is a scalar value. If `axis` is given, the result is a sparse.coo_array of dimension ``a.ndim - 1``. See Also -------- nanmax : The maximum value of a sparse array/matrix along a given axis, ignoring NaNs. min : The minimum value of a sparse array/matrix along a given axis, propagating NaNs. numpy.nanmin : NumPy's implementation of 'nanmin'. """ return self._min_or_max(axis, out, np.fmin, explicit) def argmax(self, axis=None, out=None, *, explicit=False): """Return indices of maximum elements along an axis. By default, implicit zero elements are taken into account. If there are several minimum values, the index of the first occurrence is returned. If `explicit` is set, only explicitly stored elements will be considered. Parameters ---------- axis : {-2, -1, 0, 1, None}, optional Axis along which the argmax is computed. If None (default), index of the maximum element in the flatten data is returned. out : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used. explicit : {False, True} optional (default: False) When set to True, only explicitly stored elements will be considered. If axis is not None and a row/column has no stored elements, argmax is undefined, so the index ``0`` is returned for that row/column. .. versionadded:: 1.15.0 Returns ------- ind : numpy.matrix or int Indices of maximum elements. If matrix, its size along `axis` is 1. """ return self._arg_min_or_max(axis, out, np.argmax, np.greater, explicit) def argmin(self, axis=None, out=None, *, explicit=False): """Return indices of minimum elements along an axis. By default, implicit zero elements are taken into account. If there are several minimum values, the index of the first occurrence is returned. If `explicit` is set, only explicitly stored elements will be considered. Parameters ---------- axis : {-2, -1, 0, 1, None}, optional Axis along which the argmin is computed. If None (default), index of the minimum element in the flatten data is returned. out : None, optional This argument is in the signature *solely* for NumPy compatibility reasons. Do not pass in anything except for the default value, as this argument is not used. explicit : {False, True} optional (default: False) When set to True, only explicitly stored elements will be considered. If axis is not None and a row/column has no stored elements, argmin is undefined, so the index ``0`` is returned for that row/column. .. versionadded:: 1.15.0 Returns ------- ind : numpy.matrix or int Indices of minimum elements. If matrix, its size along `axis` is 1. """ return self._arg_min_or_max(axis, out, np.argmin, np.less, explicit)
scipyREPO_NAMEscipyPATH_START.@scipy_extracted@scipy-main@scipy@sparse@_data.py@.PATH_END.py
{ "filename": "_traceref.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/histogram/error_y/_traceref.py", "type": "Python" }
import _plotly_utils.basevalidators class TracerefValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="traceref", parent_name="histogram.error_y", **kwargs ): super(TracerefValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), min=kwargs.pop("min", 0), role=kwargs.pop("role", "info"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@histogram@error_y@_traceref.py@.PATH_END.py
{ "filename": "paper.md", "repo_name": "steven-murray/powerbox", "repo_path": "powerbox_extracted/powerbox-main/paper/paper.md", "type": "Markdown" }
--- title: 'powerbox: A Python package for creating structured fields with isotropic power spectra' tags: - Python - astronomy - power spectrum - signal analysis authors: - name: Steven G. Murray orcid: 0000-0003-3059-3823 affiliation: 1, 2 affiliations: - name: International Centre for Radio Astronomy Research (ICRAR), Curtin University, Bentley, WA 6102, Australia index: 1 - name: ARC Centre of Excellence for All-Sky Astrophysics in 3 Dimensions (ASTRO 3D) index: 2 date: 19 July 2018 bibliography: paper.bib --- # Summary The power spectrum is a cornerstone of both signal analysis and spatial statistics, encoding the variance of a signal or field on different scales. Its common usage is in no small part attributable to the fact that it is a *full* description of a purely Gaussian process -- for such statistical processes, no information is contained in higher-order statistics. The prevalence of such processes (or close approximations to them) in physical systems serves to justify the popularity of the power spectrum as a key descriptive statistic in various physical sciences, eg. cosmology [@Peacock1999] and fluid mechanics [@Monin2007]. It furthermore readily avails itself to efficient numerical evaluation, being the absolute square of the Fourier Transform. Another feature of many approximate physical systems, especially those already mentioned, is that they are both homogeneous and isotropic (at least in some local sample). In this case, the *n*-dimensional power spectrum may be losslessly compressed into a single dimension, which is radial in Fourier-space. Such processes approximately describe for example the over-density field of the early Universe and locally isotropic turbulent flows. Thus it is of great use to have a numerical code which simplifies the dual operations of; (i) producing random homogeneous/isotropic fields (of arbitrary dimensionality) consistent with a given 1D radial power spectrum, and (ii) determination of the 1D radial power spectrum of random fields (or a sample of tracers of that field). ``powerbox`` exists to perform these duals tasks with both simplicity and efficiency. Performing the first of these tasks is especially non-trivial. While the power spectrum can be evaluated on any field (though it may not fully describe the given field), the precise machinery for *creating* a field from a given power spectrum depends on the probability density function (PDF) of the process itself. The machinery for creating a Gaussian field is well-known. However, other PDF's -- especially those that are positively bounded -- are extremely useful for describing such physical entities as density fields. In these cases, the *log-normal* PDF has become a standard approximation [@Coles1991], and ``powerbox`` makes a point of supporting the machinery for generating log-normal fields [@Beutler2011] for this purpose. Indeed, ``powerbox`` is *primarily* geared towards supporting cosmological applications, such as measuring and and producing samples of galaxy positions in a log-normal density field (while account for standard effects such as shot-noise and standard normalisation conventions). It is nevertheless flexible enough to support research in any field (with its own particular conventions) that is based on the homogeneous and isotropic power spectrum. ``Powerbox`` is a pure-Python package devoted to the simple and efficient solution of the previous considerations. As the most popular language for astronomy, Python is the natural language of choice for ``powerbox``, with its focus on cosmological applications, and it also provides for great ease-of-use and extensibility. As an example of the former, all functions/classes within ``powerbox`` are able to work in arbitrary numbers of dimensions (memory permitting), simply by setting a single parameter *n*. As an example of the latter, the class-based structure of the field-generator may be used to extend the generation to fields with PDF's other than either Gaussian or log-normal (indeed, the log-normal class is itself sub-classed from the Gaussian one). ``powerbox`` does not sacrifice efficiency for its high-level interface. By default, the underlying FFT's are performed by ``numpy``, which uses underlying fast C code. In addition, if the ``pyFFTW`` package is installed, ``powerbox`` will seamlessly switch to using its optimized C code for up to double the efficiency. It is also written with an eye for conserving memory, which is important for the often very large fields that may be required. ``Powerbox`` was written due to research-demand, and as such it is highly likely to be suited to the requirements of research of a similar nature. Furthermore, as previously stated, every effort has been made to sufficiently generalize its scope to be of use in related fields of research. It has already been instrumental in several publications [@Murray2017; @Wolz2018], and we hope it will be a useful tool for approximate theoretical simulations by many others. # Acknowledgements The author acknowledges helpful discussions and contributions from Cathryn Trott, Chris Jordan and Laura Wolz during the initial development of this project. Parts of this research were supported by the Australian Research Council Centre of Excellence for All Sky Astrophysics in 3 Dimensions (ASTRO 3D), through project number CE170100013 # References
steven-murrayREPO_NAMEpowerboxPATH_START.@powerbox_extracted@powerbox-main@paper@paper.md@.PATH_END.py
{ "filename": "copy_injection_recovery.py", "repo_name": "ThibeauWouters/TurboPE-BNS", "repo_path": "TurboPE-BNS_extracted/TurboPE-BNS-main/injections/outdir_NRTv2/injection_42/copy_injection_recovery.py", "type": "Python" }
""" Idea: try different learning rate schemes to try and fix the injections """ import psutil p = psutil.Process() p.cpu_affinity([0]) import os os.environ['CUDA_VISIBLE_DEVICES'] = "3" os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.10" import numpy as np import argparse # Regular imports import argparse import copy import numpy as np from astropy.time import Time import time import shutil import json import jax jax.config.update("jax_enable_x64", True) import jax.numpy as jnp from jimgw.jim import Jim from jimgw.single_event.detector import H1, L1, V1 from jimgw.single_event.likelihood import HeterodynedTransientLikelihoodFD, TransientLikelihoodFD from jimgw.single_event.waveform import RippleTaylorF2, RippleIMRPhenomD_NRTidalv2, RippleIMRPhenomD_NRTidalv2_no_taper from jimgw.prior import Uniform, Composite import utils # our plotting and postprocessing utilities script import optax # Names of the parameters and their ranges for sampling parameters for the injection NAMING = ['M_c', 'q', 's1_z', 's2_z', 'lambda_1', 'lambda_2', 'd_L', 't_c', 'phase_c', 'cos_iota', 'psi', 'ra', 'sin_dec'] PRIOR = { "M_c": [0.8759659737275101, 2.6060030916165484], "q": [0.5, 1.0], "s1_z": [-0.05, 0.05], "s2_z": [-0.05, 0.05], "lambda_1": [0.0, 5000.0], "lambda_2": [0.0, 5000.0], "d_L": [30.0, 300.0], "t_c": [-0.1, 0.1], "phase_c": [0.0, 2 * jnp.pi], "cos_iota": [-1.0, 1.0], "psi": [0.0, jnp.pi], "ra": [0.0, 2 * jnp.pi], "sin_dec": [-1, 1] } ################ ### ARGPARSE ### ################ # TODO save these into a new file def get_parser(**kwargs): add_help = kwargs.get("add_help", True) parser = argparse.ArgumentParser( description="Perform an injection recovery.", add_help=add_help, ) # TODO os does not use them # parser.add_argument( # "--GPU-device", # type=int, # default=0, # help="Select GPU index to use.", # ) # parser.add_argument( # "--GPU-memory-fraction", # type=float, # default=0.5, # help="Select percentage of GPU memory to use.", # ) parser.add_argument( "--outdir", type=str, default="./outdir/", help="Output directory for the injection.", ) parser.add_argument( "--load-existing-config", type=bool, default=False, help="Whether to load and redo an existing injection (True) or to generate a new set of parameters (False).", ) parser.add_argument( "--N", type=str, default="", help="Number (or generically, a custom identifier) of this injection, used to locate the output directory. If an empty string is passed (default), we generate a new injection.", ) parser.add_argument( "--SNR-threshold", type=float, default=12, help="Skip injections with SNR below this threshold.", ) parser.add_argument( "--waveform-approximant", type=str, default="TaylorF2", help="Which waveform approximant to use. Recommended to use TaylorF2 for now, NRTidalv2 might still be a bit unstable.", ) parser.add_argument( "--relative-binning-binsize", type=int, default=100, help="Number of bins for the relative binning.", ) parser.add_argument( "--relative-binning-ref-params-equal-true-params", type=bool, default=True, help="Whether to set the reference parameters in the relative binning code to injection parameters.", ) parser.add_argument( "--save-training-chains", type=bool, default=False, help="Whether to save training chains or not (can be very large!)", ) parser.add_argument( "--eps-mass-matrix", type=float, default=1e-6, help="Overall scale factor to rescale the step size of the local sampler.", ) parser.add_argument( "--which-local-sampler", type=str, default="MALA", help="Which local sampler to use.", ) parser.add_argument( "--smart-initial-guess", type=bool, default=False, help="Distribute the walkers around the injected parameters. TODO change this to reference parameters found by the relative binning code.", ) parser.add_argument( "--use-scheduler", type=bool, default=True, help="Use a learning rate scheduler instead of a fixed learning rate.", ) parser.add_argument( "--stopping-criterion-global-acc", type=float, default=1.0, help="Stop the run once we reach this global acceptance rate.", ) parser.add_argument( "--save-likelihood", type=bool, default=False, help="Whether to save the likelihood object", ) parser.add_argument( "--tight-Mc-prior", type=bool, default=False, help="Whether to use a tight prior on the Mc values or not", ) # # TODO this has to be implemented # parser.add_argument( # "--autotune_local_sampler", # type=bool, # default=False, # help="TODO Still has to be implemented! Specify whether to use autotuning for the local sampler.", # ) return parser #################### ### Script setup ### #################### def body(args): """ Run an injection and recovery. To get an explanation of the hyperparameters, go to: - jim hyperparameters: https://github.com/ThibeauWouters/jim/blob/8cb4ef09fefe9b353bfb89273a4bc0ee52060d72/src/jimgw/jim.py#L26 - flowMC hyperparameters: https://github.com/ThibeauWouters/flowMC/blob/ad1a32dcb6984b2e178d7204a53d5da54b578073/src/flowMC/sampler/Sampler.py#L40 """ start_time = time.time() # TODO move and get these as arguments # Deal with the hyperparameters naming = NAMING HYPERPARAMETERS = { "flowmc": { "n_loop_training": 400, "n_loop_production": 50, "n_local_steps": 5, "n_global_steps": 400, "n_epochs": 50, "n_chains": 1000, "learning_rate": 0.001, # using a scheduler below "max_samples": 50000, "momentum": 0.9, "batch_size": 50000, "use_global": True, "logging": True, "keep_quantile": 0.0, "local_autotune": None, "train_thinning": 10, "output_thinning": 30, "n_sample_max": 10000, "precompile": False, "verbose": False, "outdir": args.outdir, "stopping_criterion_global_acc": args.stopping_criterion_global_acc, "which_local_sampler": "MALA" }, "jim": { "seed": 0, "n_chains": 1000, "num_layers": 10, "hidden_size": [128, 128], "num_bins": 8, } } flowmc_hyperparameters = HYPERPARAMETERS["flowmc"] jim_hyperparameters = HYPERPARAMETERS["jim"] hyperparameters = {**flowmc_hyperparameters, **jim_hyperparameters} # TODO can I just replace this with update dict? for key, value in args.__dict__.items(): if key in hyperparameters: hyperparameters[key] = value ### POLYNOMIAL SCHEDULER if args.use_scheduler: print("Using polynomial learning rate scheduler") total_epochs = hyperparameters["n_epochs"] * hyperparameters["n_loop_training"] start = int(total_epochs / 10) start_lr = 1e-3 end_lr = 1e-5 power = 4.0 schedule_fn = optax.polynomial_schedule(start_lr, end_lr, power, total_epochs-start, transition_begin=start) hyperparameters["learning_rate"] = schedule_fn print(f"Saving output to {args.outdir}") # Fetch waveform used supported_waveforms = ["TaylorF2", "NRTidalv2", "IMRPhenomD_NRTidalv2"] if args.waveform_approximant not in supported_waveforms: print(f"Waveform approximant {args.waveform_approximant} not supported. Supported waveforms are {supported_waveforms}. Changing to TaylorF2.") args.waveform_approximant = "TaylorF2" if args.waveform_approximant == "TaylorF2": ripple_waveform_fn = RippleTaylorF2 elif args.waveform_approximant in ["IMRPhenomD_NRTidalv2", "NRTv2", "NRTidalv2"]: ripple_waveform_fn = RippleIMRPhenomD_NRTidalv2 else: raise ValueError(f"Waveform approximant {args.waveform_approximant} not supported.") # Before main code, check if outdir is correct dir format TODO improve with sys? if args.outdir[-1] != "/": args.outdir += "/" outdir = f"{args.outdir}injection_{args.N}/" # Get the prior bounds, both as 1D and 2D arrays prior_ranges = jnp.array([PRIOR[name] for name in naming]) prior_low, prior_high = prior_ranges[:, 0], prior_ranges[:, 1] bounds = np.array(list(PRIOR.values())) # Now go over to creating parameters, and potentially check SNR cutoff network_snr = 0.0 print(f"The SNR threshold parameter is set to {args.SNR_threshold}") while network_snr < args.SNR_threshold: # Generate the parameters or load them from an existing file if args.load_existing_config: config_path = f"{outdir}config.json" print(f"Loading existing config, path: {config_path}") config = json.load(open(config_path)) else: print(f"Generating new config") config = utils.generate_config(prior_low, prior_high, naming, args.N, args.outdir) key = jax.random.PRNGKey(config["seed"]) # Save the given script hyperparams with open(f"{outdir}script_args.json", 'w') as json_file: json.dump(args.__dict__, json_file) # Start injections print("Injecting signals . . .") waveform = ripple_waveform_fn(f_ref=config["fref"]) # Create frequency grid freqs = jnp.arange( config["fmin"], config["f_sampling"] / 2, # maximum frequency being halved of sampling frequency 1. / config["duration"] ) # convert injected mass ratio to eta, and apply arccos and arcsin q = config["q"] eta = q / (1 + q) ** 2 iota = float(jnp.arccos(config["cos_iota"])) dec = float(jnp.arcsin(config["sin_dec"])) # Setup the timing setting for the injection epoch = config["duration"] - config["post_trigger_duration"] gmst = Time(config["trigger_time"], format='gps').sidereal_time('apparent', 'greenwich').rad # Array of injection parameters true_param = { 'M_c': config["M_c"], # chirp mass 'eta': eta, # symmetric mass ratio 0 < eta <= 0.25 's1_z': config["s1_z"], # aligned spin of priminary component s1_z. 's2_z': config["s2_z"], # aligned spin of secondary component s2_z. 'lambda_1': config["lambda_1"], # tidal deformability of priminary component lambda_1. 'lambda_2': config["lambda_2"], # tidal deformability of secondary component lambda_2. 'd_L': config["d_L"], # luminosity distance 't_c': config["t_c"], # timeshift w.r.t. trigger time 'phase_c': config["phase_c"], # merging phase 'iota': iota, # inclination angle 'psi': config["psi"], # polarization angle 'ra': config["ra"], # right ascension 'dec': dec # declination } # Get the true parameter values for the plots truths = copy.deepcopy(true_param) truths["eta"] = q truths = np.fromiter(truths.values(), dtype=float) detector_param = { 'ra': config["ra"], 'dec': dec, 'gmst': gmst, 'psi': config["psi"], 'epoch': epoch, 't_c': config["t_c"], } print(f"The injected parameters are {true_param}") # Generating the geocenter waveform h_sky = waveform(freqs, true_param) # Setup interferometers ifos = [H1, L1, V1] psd_files = ["./psds/psd.txt", "./psds/psd.txt", "./psds/psd_virgo.txt"] # inject signal into ifos for idx, ifo in enumerate(ifos): key, subkey = jax.random.split(key) ifo.inject_signal( subkey, freqs, h_sky, detector_param, psd_file=psd_files[idx] # note: the function load_psd actaully loads the asd ) print("Signal injected") # Compute the SNR h1_snr = utils.compute_snr(H1, h_sky, detector_param) l1_snr = utils.compute_snr(L1, h_sky, detector_param) v1_snr = utils.compute_snr(V1, h_sky, detector_param) network_snr = np.sqrt(h1_snr**2 + l1_snr**2 + v1_snr**2) # If the SNR is too low, we need to generate new parameters if network_snr < args.SNR_threshold: print(f"Network SNR is less than {args.SNR_threshold}, generating new parameters") if args.load_existing_config: raise ValueError("SNR is less than threshold, but loading existing config. This should not happen!") print("H1 SNR:", h1_snr) print("L1 SNR:", l1_snr) print("V1 SNR:", v1_snr) print("Network SNR:", network_snr) print(f"Saving network SNR") with open(outdir + 'network_snr.txt', 'w') as file: file.write(str(network_snr)) print("Start prior setup") # Priors without transformation if args.tight_Mc_prior: print("INFO: Using a tight chirp mass prior") true_mc = true_param["M_c"] Mc_prior = Uniform(true_mc - 0.1, true_mc + 0.1, naming=['M_c']) else: Mc_prior = Uniform(prior_low[0], prior_high[0], naming=['M_c']) q_prior = Uniform(prior_low[1], prior_high[1], naming=['q'], transforms={ 'q': ( 'eta', lambda params: params['q'] / (1 + params['q']) ** 2 ) } ) s1z_prior = Uniform(prior_low[2], prior_high[2], naming=['s1_z']) s2z_prior = Uniform(prior_low[3], prior_high[3], naming=['s2_z']) lambda_1_prior = Uniform(prior_low[4], prior_high[4], naming=['lambda_1']) lambda_2_prior = Uniform(prior_low[5], prior_high[5], naming=['lambda_2']) dL_prior = Uniform(prior_low[6], prior_high[6], naming=['d_L']) tc_prior = Uniform(prior_low[7], prior_high[7], naming=['t_c']) phic_prior = Uniform(prior_low[8], prior_high[8], naming=['phase_c']) cos_iota_prior = Uniform(prior_low[9], prior_high[9], naming=["cos_iota"], transforms={ "cos_iota": ( "iota", lambda params: jnp.arccos( jnp.arcsin(jnp.sin(params["cos_iota"] / 2 * jnp.pi)) * 2 / jnp.pi ), ) }, ) psi_prior = Uniform(prior_low[10], prior_high[10], naming=["psi"]) ra_prior = Uniform(prior_low[11], prior_high[11], naming=["ra"]) sin_dec_prior = Uniform(prior_low[12], prior_high[12], naming=["sin_dec"], transforms={ "sin_dec": ( "dec", lambda params: jnp.arcsin( jnp.arcsin(jnp.sin(params["sin_dec"] / 2 * jnp.pi)) * 2 / jnp.pi ), ) }, ) # Save the prior bounds print("Saving prior bounds") utils.save_prior_bounds(prior_low, prior_high, outdir) # Compose the prior prior_list = [ Mc_prior, q_prior, s1z_prior, s2z_prior, lambda_1_prior, lambda_2_prior, dL_prior, tc_prior, phic_prior, cos_iota_prior, psi_prior, ra_prior, sin_dec_prior, ] complete_prior = Composite(prior_list) bounds = jnp.array([[p.xmin, p.xmax] for p in complete_prior.priors]) print("Finished prior setup") print("Initializing likelihood") if args.relative_binning_ref_params_equal_true_params: ref_params = true_param print("Using the true parameters as reference parameters for the relative binning") else: ref_params = None print("Will search for reference waveform for relative binning") # ### TODO remove # # Explicitly fix relative binning for NRTidalv2 # if args.waveform_approximant in ["IMRPhenomD_NRTidalv2", "NRTidalv2"]: # # ## TODO this might be broken? # # # # Explicitly set the f_min and f_max used there # # # relbin_kwargs = {"f_min": config["fmin"], "f_max": config["f_sampling"] / 2} # # relbin_kwargs = {} # # # Set the reference parameters at the ideal location for not breaking relative binning # # print("Setting the reference parameters to not break the relative binning for NRTidalv2") # # ref_params = true_param # # ref_params["lambda_1"] = 1.0 # # ref_params["lambda_2"] = 1.0 # print("Now, the reference parameters are: ") # print(ref_params) # else: # relbin_kwargs = {} relbin_kwargs = {} if args.waveform_approximant == "IMRPhenomD_NRTidalv2": print("Using IMRPhenomD_NRTidalv2 no taper as the reference waveform for the likelihood") reference_waveform = RippleIMRPhenomD_NRTidalv2_no_taper(f_ref=config["fref"]) else: reference_waveform = waveform likelihood = HeterodynedTransientLikelihoodFD( ifos, prior=complete_prior, bounds=bounds, n_bins = args.relative_binning_binsize, waveform=waveform, reference_waveform=reference_waveform, trigger_time=config["trigger_time"], duration=config["duration"], post_trigger_duration=config["post_trigger_duration"], ref_params=ref_params, **relbin_kwargs ) if args.save_likelihood: print(f"INFO: Saving the likelihood to {outdir}") import pickle with open(f'{outdir}likelihood.pickle', 'wb') as handle: pickle.dump(likelihood, handle, protocol=pickle.HIGHEST_PROTOCOL) # Save the ref params utils.save_relative_binning_ref_params(likelihood, outdir) # Generate arguments for the local samplercd mass_matrix = jnp.eye(len(prior_list)) for idx, prior in enumerate(prior_list): mass_matrix = mass_matrix.at[idx, idx].set(prior.xmax - prior.xmin) # fetch the prior range local_sampler_arg = {'step_size': mass_matrix * args.eps_mass_matrix} # set the overall step size hyperparameters["local_sampler_arg"] = local_sampler_arg # Create jim object jim = Jim( likelihood, complete_prior, **hyperparameters ) if args.smart_initial_guess: n_chains = hyperparameters["n_chains"] n_dim = len(prior_list) initial_guess = utils.generate_smart_initial_guess(gmst, [H1, L1, V1], true_param, n_chains, n_dim, prior_low, prior_high) # Plot it utils.plot_chains(initial_guess, "initial_guess", outdir, truths = truths) else: initial_guess = jnp.array([]) ### Finally, do the sampling jim.sample(jax.random.PRNGKey(24), initial_guess = initial_guess) # === Show results, save output === # Print a summary to screen: jim.print_summary() # Save and plot the results of the run # - training phase name = outdir + f'results_training.npz' print(f"Saving samples to {name}") state = jim.Sampler.get_sampler_state(training = True) chains, log_prob, local_accs, global_accs, loss_vals = state["chains"], state["log_prob"], state["local_accs"], state["global_accs"], state["loss_vals"] local_accs = jnp.mean(local_accs, axis=0) global_accs = jnp.mean(global_accs, axis=0) if args.save_training_chains: np.savez(name, log_prob=log_prob, local_accs=local_accs, global_accs=global_accs, loss_vals=loss_vals, chains=chains) else: np.savez(name, log_prob=log_prob, local_accs=local_accs, global_accs=global_accs, loss_vals=loss_vals) utils.plot_accs(local_accs, "Local accs (training)", "local_accs_training", outdir) utils.plot_accs(global_accs, "Global accs (training)", "global_accs_training", outdir) utils.plot_loss_vals(loss_vals, "Loss", "loss_vals", outdir) utils.plot_log_prob(log_prob, "Log probability (training)", "log_prob_training", outdir) # - production phase name = outdir + f'results_production.npz' state = jim.Sampler.get_sampler_state(training = False) chains, log_prob, local_accs, global_accs = state["chains"], state["log_prob"], state["local_accs"], state["global_accs"] local_accs = jnp.mean(local_accs, axis=0) global_accs = jnp.mean(global_accs, axis=0) np.savez(name, chains=chains, log_prob=log_prob, local_accs=local_accs, global_accs=global_accs) utils.plot_accs(local_accs, "Local accs (production)", "local_accs_production", outdir) utils.plot_accs(global_accs, "Global accs (production)", "global_accs_production", outdir) utils.plot_log_prob(log_prob, "Log probability (production)", "log_prob_production", outdir) # Plot the chains as corner plots utils.plot_chains(chains, "chains_production", outdir, truths = truths) # Save the NF and show a plot of samples from the flow print("Saving the NF") jim.Sampler.save_flow(outdir + "nf_model") name = outdir + 'results_NF.npz' chains = jim.Sampler.sample_flow(10_000) np.savez(name, chains = chains) # Finally, copy over this script to the outdir for reproducibility shutil.copy2(__file__, outdir + "copy_injection_recovery.py") print("Saving the jim hyperparameters") jim.save_hyperparameters(outdir = outdir) end_time = time.time() runtime = end_time - start_time print(f"Time taken: {runtime} seconds ({(runtime)/60} minutes)") print(f"Saving runtime") with open(outdir + 'runtime.txt', 'w') as file: file.write(str(runtime)) print("Finished injection recovery successfully!") ############ ### MAIN ### ############ def main(given_args = None): parser = get_parser() args = parser.parse_args() print(given_args) # Update with given args if given_args is not None: args.__dict__.update(given_args) if args.load_existing_config and args.N == "": raise ValueError("If load_existing_config is True, you need to specify the N argument to locate the existing injection. ") print("------------------------------------") print("Arguments script:") for key, value in args.__dict__.items(): print(f"{key}: {value}") print("------------------------------------") print("Starting main code") # If no N is given, fetch N from the structure of outdir if len(args.N) == 0: N = utils.get_N(args.outdir) args.N = N # TODO fix that os uses these # import os # os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = str(args.GPU_memory_fraction) # os.environ['CUDA_VISIBLE_DEVICES'] = str(args.GPU_device) # print(f"Running on GPU {args.GPU_device}") # Execute the script body(args) if __name__ == "__main__": main()
ThibeauWoutersREPO_NAMETurboPE-BNSPATH_START.@TurboPE-BNS_extracted@TurboPE-BNS-main@injections@outdir_NRTv2@injection_42@copy_injection_recovery.py@.PATH_END.py
{ "filename": "test_apply_background.py", "repo_name": "spacetelescope/jwst", "repo_path": "jwst_extracted/jwst-main/jwst/mrs_imatch/tests/test_apply_background.py", "type": "Python" }
""" Unit test for mrs_imatch apply background """ import pytest from stdatamodels.jwst import datamodels from jwst.datamodels import ModelContainer from jwst.assign_wcs import AssignWcsStep from jwst.mrs_imatch.mrs_imatch_step import apply_background_2d import numpy as np wcsinfo = { 'dec_ref': 0.0, 'ra_ref': 10.0, 'roll_ref': 0.0, 'v2_ref': -503.65447, 'v3_ref': -318.74246, 'v3yangle': 0.0, 'vparity': -1 } mirifushort_short = { 'detector': 'MIRIFUSHORT', 'channel': '12', 'band': 'SHORT', 'name': 'MIRI' } observation = { 'date': '2019-01-01', 'time': '17:00:00'} subarray = { 'fastaxis': 1, 'name': 'FULL', 'slowaxis': 2, 'xsize': 1032, 'xstart': 1, 'ysize': 1024, 'ystart': 1 } @pytest.fixture(scope='function') def miri_dither_ch12(): """ Generate 4 dithered channel 12 data """ input_model1 = datamodels.IFUImageModel((30, 30)) input_model1.meta.wcsinfo._instance.update(wcsinfo) input_model1.meta.instrument._instance.update(mirifushort_short) input_model1.meta.observation._instance.update(observation) input_model1.meta.subarray._instance.update(subarray) input_model1.meta.exposure.type = 'MIR_MRS' input_model1.data[:, :] = 10 input_model2 = datamodels.IFUImageModel((30, 30)) input_model2.meta.wcsinfo._instance.update(wcsinfo) input_model2.meta.instrument._instance.update(mirifushort_short) input_model2.meta.observation._instance.update(observation) input_model2.meta.subarray._instance.update(subarray) input_model2.meta.exposure.type = 'MIR_MRS' input_model2.data[:, :] = 10 input_model3 = datamodels.IFUImageModel((30, 30)) input_model3.meta.wcsinfo._instance.update(wcsinfo) input_model3.meta.instrument._instance.update(mirifushort_short) input_model3.meta.observation._instance.update(observation) input_model3.meta.subarray._instance.update(subarray) input_model3.meta.exposure.type = 'MIR_MRS' input_model3.data[:, :] = 20 input_model4 = datamodels.IFUImageModel((30, 30)) input_model4.meta.wcsinfo._instance.update(wcsinfo) input_model4.meta.instrument._instance.update(mirifushort_short) input_model4.meta.observation._instance.update(observation) input_model4.meta.subarray._instance.update(subarray) input_model4.meta.exposure.type = 'MIR_MRS' input_model4.data[:, :] = 10 # stuff in model container input_models = [] input_models.append(input_model1) input_models.append(input_model2) input_models.append(input_model3) input_models.append(input_model4) return input_models def test_apply_background_2d(tmp_cwd, miri_dither_ch12): """ Test if background polynomial is set it is subtracted correctly""" all_models = ModelContainer(miri_dither_ch12) # test if given a background polynomial - apply_background_2d gives the correct answer # Polynomial information was created by running a faked full array data set to determine # what the polynomial values should be new_container = [] degree = (1, 1, 1,) center = (9.99999408089876, -4.668612949274985e-06, 4.889999912818894) poly = np.ndarray(9) # run AssignWcsStep on first file and set wcs of other files to this channel = '1' for im, m in enumerate(all_models): if im == 0: m = AssignWcsStep.call(m) wcs1 = m.meta.wcs poly = [-2.50000000e+00, -6.66518331e-15, 5.67845589e-12, -1.23549218e-11, 3.26209108e-12, -5.43180357e-12, -2.54903452e-09, 6.21614553e-09] elif im == 1: m.meta.wcs = wcs1 poly = [-2.50000000e+00, -9.29031986e-15, 1.74437380e-12, -3.94894956e-12, 4.71729481e-13, 5.42031845e-13, -9.96151554e-10, 2.78281950e-09] elif im == 2: m.meta.wcs = wcs1 poly = [7.50000000e+00, 2.22921836e-14, -6.97131279e-12, 1.58336906e-11, -5.43704212e-12, 6.79109678e-12, 2.63515372e-09, -8.00226976e-09] else: m.meta.wcs = wcs1 poly = [-2.50000000e+00, -6.33668043e-15, -4.51516905e-13, 4.70180795e-13, 1.70322157e-12, -1.90132506e-12, 9.10032350e-10, -9.96695272e-10] poly = np.asarray(poly) m.meta.background.polynomial_info.append( { 'degree': degree, 'refpoint': center, 'coefficients': poly.ravel().tolist(), 'channel': channel } ) # input 10 output 12.5 for all images apply_background_2d(m, channel, subtract=True) new_container.append(m) # all the data should now be the same for the science pixels # the edge pixels are located in non-science region and no # background subtraction is done on these pixels data1 = new_container[0].data[:, 16:] data2 = new_container[1].data[:, 16:] data3 = new_container[2].data[:, 16:] data4 = new_container[3].data[:, 16:] assert np.allclose(data1, data2, rtol=1e-6) assert np.allclose(data2, data3, rtol=1e-6) assert np.allclose(data3, data4, rtol=1e-6) assert np.allclose(data1, data4, rtol=1e-6)
spacetelescopeREPO_NAMEjwstPATH_START.@jwst_extracted@jwst-main@jwst@mrs_imatch@tests@test_apply_background.py@.PATH_END.py
{ "filename": "log.py", "repo_name": "purmortal/galcraft", "repo_path": "galcraft_extracted/galcraft-main/GalCraft/modules/log.py", "type": "Python" }
import logging class Logger: def __init__(self, logfile, logger=None, level=logging.INFO, mode='a'): self.logger = logging.getLogger(logger) self.logger.propagate = False self.logger.setLevel(level) fh = logging.FileHandler(logfile, mode=mode, encoding='utf-8') fh.setLevel(level) sh = logging.StreamHandler() sh.setLevel(level) formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s") fh.setFormatter(formatter) sh.setFormatter(formatter) self.logger.handlers.clear() self.logger.addHandler(fh) self.logger.addHandler(sh) fh.close() sh.close() def get_log(self): return self.logger
purmortalREPO_NAMEgalcraftPATH_START.@galcraft_extracted@galcraft-main@GalCraft@modules@log.py@.PATH_END.py
{ "filename": "profiler.py", "repo_name": "google/jax", "repo_path": "jax_extracted/jax-main/jax/experimental/mosaic/gpu/profiler.py", "type": "Python" }
# Copyright 2024 The JAX Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import contextlib import itertools import json import math from typing import Callable, ParamSpec, TypeVar import warnings import jax from jax._src.lib import xla_client from jax.extend import ffi import jax.numpy as jnp from jaxlib.mlir import ir from jaxlib.mlir.dialects import arith from jaxlib.mlir.dialects import gpu from jaxlib.mlir.dialects import memref from jaxlib.mlir.dialects import scf import numpy as np from .utils import * # noqa: F403 try: from jax._src.lib import mosaic_gpu as mosaic_gpu_lib except ImportError: has_registrations = False else: # TODO(slebedev): Remove the if once the minimum jaxlib is 0.4.36. has_registrations = hasattr(mosaic_gpu_lib._mosaic_gpu_ext, "registrations") if has_registrations: for name, handler in mosaic_gpu_lib._mosaic_gpu_ext.registrations(): xla_client.register_custom_call_target( name, handler, platform="CUDA", api_version=1 ) # ruff: noqa: F405 # mypy: ignore-errors T = TypeVar("T") P = ParamSpec("P") def _event_record(args, *, copy_before): flat_args, treedef = jax.tree.flatten(args) event, *flat_outs = ffi.ffi_call( "mgpu_event_record", result_shape_dtypes=(jax.core.ShapedArray((), jnp.uint64), *flat_args), input_output_aliases={i: i + 1 for i in range(len(flat_args))}, )(*flat_args, copy_before=copy_before) return event, treedef.unflatten(flat_outs) def _event_elapsed(start_event, end_event): return ffi.ffi_call( "mgpu_event_elapsed", result_shape_dtypes=jax.core.ShapedArray((), jnp.float32), )(start_event, end_event) def measure( f: Callable[P, T], *args: P.args, **kwargs: P.kwargs ) -> tuple[T, float]: """Measures the time it takes to execute the function on the GPU. Args: f: The function to measure. It must accept at least one argument and return at least one output to be measurable. *args: The arguments to pass to ``f``. **kwargs: The keyword arguments to pass to ``f``. Returns: The return value of ``f`` and the elapsed time in milliseconds. """ if not has_registrations: raise RuntimeError( "This function requires jaxlib >=0.4.36 with CUDA support." ) if not (args or kwargs): # We require at least one argument and at least one output to ensure # that there is a data dependency between `_event_record` calls in # the resulting HLO program. raise ValueError("Can only measure functions with arguments") @jax.jit def run(*args, **kwargs): start_event, (args, kwargs) = _event_record( (args, kwargs), copy_before=True ) end_event, outs = _event_record(f(*args, **kwargs), copy_before=False) if jax.tree.structure(outs).num_leaves == 0: raise ValueError("Can only measure functions with at least one output") return outs, _event_elapsed(start_event, end_event) jax.block_until_ready(run(*args, **kwargs)) # Warmup. outs, elapsed = run(*args, **kwargs) return outs, float(elapsed) class ProfilerSpec: ENTER = 0 EXIT = 1 << 31 def __init__(self, entries_per_warpgroup: int): self.entries_per_warpgroup = entries_per_warpgroup self.interned_names = {} def _num_warpgroups( self, grid: tuple[int, ...], block: tuple[int, ...] ) -> int: if math.prod(block) % WARPGROUP_SIZE: raise ValueError("Block size is not a multiple of warpgroup size") return math.prod(grid) * math.prod(block) // WARPGROUP_SIZE def mlir_buffer_type( self, grid: tuple[int, ...], block: tuple[int, ...] ) -> ir.Type: return ir.MemRefType.get( (self._num_warpgroups(grid, block) * self.entries_per_warpgroup,), ir.IntegerType.get_signless(32), ) def jax_buffer_type( self, grid: tuple[int, ...], block: tuple[int, ...] ) -> ir.Type: return jax.ShapeDtypeStruct( (self._num_warpgroups(grid, block) * self.entries_per_warpgroup,), jnp.uint32, ) def smem_i32_elements(self, block: tuple[int, ...]): num_warpgroups = self._num_warpgroups((), block) return int(num_warpgroups * self.entries_per_warpgroup) def smem_bytes(self, block: tuple[int, ...]): bytes_per_entry = 4 return self.smem_i32_elements(block) * bytes_per_entry def intern_name(self, name: str) -> int: if (name_id := self.interned_names.get(name, None)) is not None: return name_id name_id = self.interned_names[name] = len(self.interned_names) if name_id & self.EXIT: raise RuntimeError("Allocated too many names") return name_id def dump(self, buffer, f, grid: tuple[int, ...], block: tuple[int, ...]): buffer = np.asarray(buffer) num_blocks = math.prod(grid) warpgroups_per_block = self._num_warpgroups((), block) entries = buffer.reshape( num_blocks, warpgroups_per_block, self.entries_per_warpgroup ) start_times = entries[..., 0] sm_ids = entries[..., 1] entries_used = entries[..., 2] if np.any(entries_used > self.entries_per_warpgroup - 2): raise RuntimeError("Insufficient space to capture a full trace") traces = entries[..., 3:] unintern = {v: k for k, v in self.interned_names.items()} events = [] for block_idx, wg_idx in np.ndindex(num_blocks, warpgroups_per_block): valid_entries = entries_used[block_idx, wg_idx] - 3 local_clock_offset = None assert valid_entries % 2 == 0, valid_entries start_time = start_times[block_idx, wg_idx] block_events = [] last_time = float("-inf") for i in range(0, valid_entries, 2): tag = traces[block_idx, wg_idx, i] time = traces[block_idx, wg_idx, i + 1] if local_clock_offset is None: local_clock_offset = time time -= local_clock_offset time -= i * 6 # Account for the overhead of profiling. if time < 0: break # Detect a timer wraparound name_id = tag begin = True if name_id & ProfilerSpec.EXIT: name_id = name_id ^ ProfilerSpec.EXIT begin = False name = unintern[name_id] if last_time >= time: if last_time - time > 10: warnings.warn( "Profiler clock went significantly backwards for event" f" {'start' if begin else 'end'} `{name}`: {last_time} ->" f" {time}" ) time = last_time + 1 last_time = time block_events.append({ "name": name, "ph": "B" if begin else "E", "ts": float(start_time + time) / 1e3, "pid": 1 + int(sm_ids[block_idx, wg_idx]), "tid": 1 + wg_idx + warpgroups_per_block * block_idx, }) else: # If we didn't break if block_events: events.append(block_events) events = sorted(events, key=lambda x: x[0]["ts"]) flat_events = list(itertools.chain.from_iterable(events)) return json.dump({"displayTimeUnit": "ns", "traceEvents": flat_events}, f) class OnDeviceProfiler: def __init__(self, spec: ProfilerSpec, smem_buffer: ir.Value, gmem_buffer: ir.Value): self.spec = spec self.start = globaltimer("low") i32 = ir.IntegerType.get_signless(32) index = ir.IndexType.get() self.entries_per_wg = spec.entries_per_warpgroup wg_idx = warpgroup_idx(sync=False) self.smem_buffer = memref_slice( smem_buffer, ds( arith.index_cast( index, arith.muli(wg_idx, c(self.entries_per_wg, i32)) ), self.entries_per_wg, ), ) self.smem_buffer_ptr = memref_ptr(self.smem_buffer, memory_space=3) self.gmem_buffer = gmem_buffer self.is_profiling_thread = arith.cmpi( arith.CmpIPredicate.eq, arith.remui(thread_idx(), c(WARPGROUP_SIZE, i32)), c(0, i32), ) # Hopefully mem2reg will remove the allocation. self.offset = memref.alloca(ir.MemRefType.get((), i32), [], []) memref.store(c(0, i32), self.offset, []) @contextlib.contextmanager def record(self, name: str): i32 = ir.IntegerType.get_signless(32) name_id = self.spec.intern_name(name) def store(modifier): cur = memref.load(self.offset, []) i64 = ir.IntegerType.get_signless(64) base_addr = arith.addi( llvm.ptrtoint(i64, self.smem_buffer_ptr), arith.extui(i64, arith.muli(cur, c(4, i32))), ) llvm.inline_asm( ir.Type.parse("!llvm.void"), [self.is_profiling_thread, base_addr, c(modifier | name_id, i32)], """ @$0 st.shared.v2.u32 [$1], {$2, %clock}; """, "b,l,r", has_side_effects=True, ) memref.store( arith.addi(cur, c(2, cur.type)), self.offset, [], ) store(ProfilerSpec.ENTER) yield store(ProfilerSpec.EXIT) def finalize(self, grid: tuple[int, ...], block: tuple[int, ...]): index = ir.IndexType.get() i32 = ir.IntegerType.get_signless(32) gpu.barrier() # Make sure all warpgroups are done. block_idx = c(0, index) for dim in gpu.Dimension: # pytype: disable=wrong-arg-types block_idx = arith.addi( arith.muli(block_idx, gpu.grid_dim(dim)), gpu.block_id(dim) ) wg_idx = warpgroup_idx(sync=False) wg_per_block = math.prod(block) // WARPGROUP_SIZE global_wg_idx = arith.addi( arith.muli(block_idx, c(wg_per_block, index)), arith.index_cast(index, wg_idx), ) start_offset = arith.muli(global_wg_idx, c(self.entries_per_wg, index)) wg_gmem_buffer = memref.subview( self.gmem_buffer, [start_offset], [self.entries_per_wg], [1], result_type=ir.Type.parse( f"memref<{self.entries_per_wg}xi32, strided<[1], offset: ?>>" ), ) thread_in_wg = arith.remui(thread_idx(), c(128, i32)) if_first = scf.IfOp( arith.cmpi(arith.CmpIPredicate.eq, thread_in_wg, c(0, i32)) ) with ir.InsertionPoint(if_first.then_block): memref.store(self.start, wg_gmem_buffer, [c(0, index)]) memref.store(smid(), wg_gmem_buffer, [c(1, index)]) memref.store( arith.addi(memref.load(self.offset, []), c(3, i32)), wg_gmem_buffer, [c(2, index)], ) for_op = scf.ForOp( c(0, index), c(self.entries_per_wg - 3, index), c(1, index), ) with ir.InsertionPoint(for_op.body): x = memref.load(self.smem_buffer, [for_op.induction_variable]) memref.store( x, wg_gmem_buffer, [arith.addi(for_op.induction_variable, c(3, index))], ) scf.yield_([]) scf.yield_([])
googleREPO_NAMEjaxPATH_START.@jax_extracted@jax-main@jax@experimental@mosaic@gpu@profiler.py@.PATH_END.py
{ "filename": "multiprocessing.py", "repo_name": "adrn/schwimmbad", "repo_path": "schwimmbad_extracted/schwimmbad-main/src/schwimmbad/multiprocessing.py", "type": "Python" }
# type: ignore import functools import signal import multiprocess from multiprocess.pool import Pool __all__ = ["MultiPool"] def _initializer_wrapper(actual_initializer, *rest): """ We ignore SIGINT. It's up to our parent to kill us in the typical condition of this arising from ``^C`` on a terminal. If someone is manually killing us with that signal, well... nothing will happen. """ signal.signal(signal.SIGINT, signal.SIG_IGN) if actual_initializer is not None: actual_initializer(*rest) class CallbackWrapper: def __init__(self, callback): self.callback = callback def __call__(self, tasks): for task in tasks: self.callback(task) class MultiPool(Pool): """ A modified version of :class:`multiprocess.pool.Pool` that has better behavior with regard to ``KeyboardInterrupts`` in the :func:`map` method. NOTE: This is no longer built off of the standard library :class:`multiprocessing.pool.Pool` -- this uses the version from `multiprocess`, which uses `dill` to pickle objects instead of the standard library `pickle`. Parameters ---------- processes : int, optional The number of worker processes to use; defaults to the number of CPUs. initializer : callable, optional If specified, a callable that will be invoked by each worker process when it starts. initargs : iterable, optional Arguments for ``initializer``; it will be called as ``initializer(*initargs)``. kwargs: Extra arguments passed to the :class:`multiprocess.pool.Pool` superclass. """ wait_timeout = 3600 def __init__(self, processes=None, initializer=None, initargs=(), **kwargs): new_initializer = functools.partial(_initializer_wrapper, initializer) super().__init__(processes, new_initializer, initargs, **kwargs) self.size = self._processes @staticmethod def enabled(): return True def map(self, func, iterable, chunksize=None, callback=None): """ Equivalent to the built-in ``map()`` function and :meth:`multiprocessing.pool.Pool.map()`, without catching ``KeyboardInterrupt``. Parameters ---------- worker : callable A function or callable object that is executed on each element of the specified ``tasks`` iterable. This object must be picklable (i.e. it can't be a function scoped within a function or a ``lambda`` function). This should accept a single positional argument and return a single object. tasks : iterable A list or iterable of tasks. Each task can be itself an iterable (e.g., tuple) of values or data to pass in to the worker function. callback : callable, optional An optional callback function (or callable) that is called with the result from each worker run and is executed on the master process. This is useful for, e.g., saving results to a file, since the callback is only called on the master thread. Returns ------- results : list A list of results from the output of each ``worker()`` call. """ callbackwrapper = CallbackWrapper(callback) if callback is not None else None # The key magic is that we must call r.get() with a timeout, because # a Condition.wait() without a timeout swallows KeyboardInterrupts. r = self.map_async( func, iterable, chunksize=chunksize, callback=callbackwrapper ) while True: try: return r.get(self.wait_timeout) except multiprocess.TimeoutError: pass except KeyboardInterrupt: self.terminate() self.join() raise
adrnREPO_NAMEschwimmbadPATH_START.@schwimmbad_extracted@schwimmbad-main@src@schwimmbad@multiprocessing.py@.PATH_END.py
{ "filename": "bindata.py", "repo_name": "scottransom/presto", "repo_path": "presto_extracted/presto-master/python/binopttest/bindata.py", "type": "Python" }
from future import standard_library standard_library.install_aliases() from builtins import range def catvar(col): ret = [] global a, b, c, d, e for i in range(shape(a)[0]): ret.append(a[i][col]) for i in range(shape(b)[0]): ret.append(b[i][col]) for i in range(shape(c)[0]): ret.append(c[i][col]) for i in range(shape(d)[0]): ret.append(d[i][col]) for i in range(shape(e)[0]): ret.append(e[i][col]) return ret def readsaves(file='montebinopt_saves.txt'): f = open(file, 'r') result = [] while 1: try: result.append(load(f)) except ValueError: continue except EOFError: break f.close() return result def saveresults(file="testresults.txt"): from pickle import * global psrp, orbp, orbx, orbe, orbw, orbt global widthp, widthx, widtht, widthe, widthw global mf, z vars = ('psrp', 'orbp', 'orbx', 'orbe', 'orbw', 'orbt', 'widthp', 'widthx', 'widtht', 'widthe', 'widthw', 'mf', 'z') f = open(file, 'w') for var in vars: print('Saving ', var, '...') exec('dump(%s, f)' % (var)) f.close() print('Saved em.') def quadratic(parameters, x): a = parameters[0] b = parameters[1] c = parameters[2] return (a * x + b) * x + c def linear(parameters, x): m = parameters[0] b = parameters[1] return m * x + b def genfits(): from LeastSquares import leastSquaresFit global psrp, orbp, orbx, orbe, orbw, orbt global widthp, widthx, widtht, widthe, widthw global mf, z yvals = {'Orb p':widthp, 'Orb x':widthx, 'Orb t':widtht} xvals = {'Orb p':orbp/z, 'Orb x':1.0/z, 'Orb t':1.0/z} xtits = {'Orb p':'Orb p/z', 'Orb x':'1.0/z', 'Orb t':'1.0/z'} for fitvar in ['Orb p', 'Orb x', 'Orb t']: vals = [] for i in range(len(xvals[fitvar])): vals.append((xvals[fitvar][i], yvals[fitvar][i])) fit = leastSquaresFit(linear, (1.0, 0.0), vals) print('%s width = %10.7f * %s + %10.7f (Acc: %f)' % (fitvar, fit[0][0], xtits[fitvar], fit[0][1], fit[1])) plotxy(yvals[fitvar], xvals[fitvar], laby=fitvar+' Width (Fractional)', labx=xtits[fitvar], line=None, font=2, symbol=2, color='red', device='fits.ps/CPS') plotxy([fit[0][0]*min(xvals[fitvar])+fit[0][1], fit[0][0]*max(xvals[fitvar])+fit[0][1]], [min(xvals[fitvar]), max(xvals[fitvar])], line=1, symbol=None, color='blue') nextplotpage(1) closeplot() def genlogfits(): from LeastSquares import leastSquaresFit global psrp, orbp, orbx, orbe, orbw, orbt global widthp, widthx, widtht, widthe, widthw global mf, z yvals = {'Orb p':log(widthp), 'Orb x':log(widthx), 'Orb t':log(widtht)} xvals = {'Orb p':log(orbp/z), 'Orb x':log(1.0/z), 'Orb t':log(1.0/z)} xtits = {'Orb p':'log(Orb p/z)', 'Orb x':'log(1.0/z)', 'Orb t':'log(1.0/z)'} for fitvar in ['Orb p', 'Orb x', 'Orb t']: vals = [] for i in range(len(xvals[fitvar])): vals.append((xvals[fitvar][i], yvals[fitvar][i])) fit = leastSquaresFit(linear, (1.0, 0.0), vals) print('log(%s) width = %10.7f * %s + %10.7f (Acc: %f)' % (fitvar, fit[0][0], xtits[fitvar], fit[0][1], fit[1])) plotxy(yvals[fitvar], xvals[fitvar], laby='log('+fitvar+') Width (Fractional)', labx=xtits[fitvar], line=None, font=2, symbol=2, color='red', device='logfits.ps/CPS') plotxy([fit[0][0]*min(xvals[fitvar])+fit[0][1], fit[0][0]*max(xvals[fitvar])+fit[0][1]], [min(xvals[fitvar]), max(xvals[fitvar])], line=1, symbol=None, color='blue') nextplotpage(1) closeplot() if __name__ == '__main__': from math import * from Numeric import * from stats import * from Statistics import * from Pgplot import * from miscutils import * def help(funct): """ help(funct): Print the documentation string of a function or method. """ print(eval(funct + '.__doc__')) from pickle import * vars = ('psrp', 'orbp', 'orbx', 'orbe', 'orbw', 'orbt', 'widthp', 'widthx', 'widtht', 'widthe', 'widthw', 'mf', 'z') f = open("testresults.txt") for var in vars: print('Loading ', var, '...') exec(var + ' = asarray(load(f))') f.close() print('Got em.')
scottransomREPO_NAMEprestoPATH_START.@presto_extracted@presto-master@python@binopttest@bindata.py@.PATH_END.py
{ "filename": "hugging_face_model.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/document_loaders/hugging_face_model.py", "type": "Python" }
from typing import Iterator, List, Optional import requests from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader class HuggingFaceModelLoader(BaseLoader): """ Load model information from `Hugging Face Hub`, including README content. This loader interfaces with the Hugging Face Models API to fetch and load model metadata and README files. The API allows you to search and filter models based on specific criteria such as model tags, authors, and more. API URL: https://huggingface.co/api/models DOC URL: https://huggingface.co/docs/hub/en/api Examples: .. code-block:: python from langchain_community.document_loaders import HuggingFaceModelLoader # Initialize the loader with search criteria loader = HuggingFaceModelLoader(search="bert", limit=10) # Load models documents = loader.load() # Iterate through the fetched documents for doc in documents: print(doc.page_content) # README content of the model print(doc.metadata) # Metadata of the model """ BASE_URL: str = "https://huggingface.co/api/models" README_BASE_URL: str = "https://huggingface.co/{model_id}/raw/main/README.md" def __init__( self, *, search: Optional[str] = None, author: Optional[str] = None, filter: Optional[str] = None, sort: Optional[str] = None, direction: Optional[str] = None, limit: Optional[int] = 3, full: Optional[bool] = None, config: Optional[bool] = None, ): """Initialize the HuggingFaceModelLoader. Args: search: Filter based on substrings for repos and their usernames. author: Filter models by an author or organization. filter: Filter based on tags. sort: Property to use when sorting. direction: Direction in which to sort. limit: Limit the number of models fetched. full: Whether to fetch most model data. config: Whether to also fetch the repo config. """ self.params = { "search": search, "author": author, "filter": filter, "sort": sort, "direction": direction, "limit": limit, "full": full, "config": config, } def fetch_models(self) -> List[dict]: """Fetch model information from Hugging Face Hub.""" response = requests.get( self.BASE_URL, params={k: v for k, v in self.params.items() if v is not None}, ) response.raise_for_status() return response.json() def fetch_readme_content(self, model_id: str) -> str: """Fetch the README content for a given model.""" readme_url = self.README_BASE_URL.format(model_id=model_id) try: response = requests.get(readme_url) response.raise_for_status() return response.text except requests.RequestException: return "README not available for this model." def lazy_load(self) -> Iterator[Document]: """Load model information lazily, including README content.""" models = self.fetch_models() for model in models: model_id = model.get("modelId", "") readme_content = self.fetch_readme_content(model_id) yield Document( page_content=readme_content, metadata=model, )
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@document_loaders@hugging_face_model.py@.PATH_END.py
{ "filename": "mathutils.py", "repo_name": "cmbant/CAMB", "repo_path": "CAMB_extracted/CAMB-master/camb/mathutils.py", "type": "Python" }
""" This module contains some fast utility functions that are useful in the same contexts as camb. They are entirely independent of the main camb code. """ from ctypes import c_int, c_double, c_bool, POINTER from .baseconfig import camblib, numpy_1d, numpy_2d, numpy_3d import numpy as np _chi2 = camblib.__mathutils_MOD_getchisquared _chi2.argtypes = [numpy_2d, numpy_1d, POINTER(c_int)] _chi2.restype = c_double def chi_squared(covinv, x): """ Utility function to efficiently calculate x^T covinv x :param covinv: symmetric inverse covariance matrix :param x: vector :return: covinv.dot(x).dot(x), but parallelized and using symmetry """ if len(x) != covinv.shape[0] or covinv.shape[0] != covinv.shape[1]: raise ValueError('Wrong shape in chi_squared') return _chi2(covinv, x, c_int(len(x))) int_arg = POINTER(c_int) _3j = camblib.__mathutils_MOD_getthreejs _3j.argtypes = [numpy_1d, int_arg, int_arg, int_arg, int_arg] def threej(l2, l3, m2, m3): """ Convenience wrapper around standard 3j function, returning array for all allowed l1 values :param l2: L_2 :param l3: L_3 :param m2: M_2 :param m3: M_3 :return: array of 3j from max(abs(l2-l3),abs(m2+m3)) .. l2+l3 """ l1min = max(np.abs(l2 - l3), np.abs(m2 + m3)) result = np.zeros(int(l3 + l2 - l1min + 1)) l2in, l3in, m2in, m3in = c_int(l2), c_int(l3), c_int(m2), c_int(m3) _3j(result, l2in, l3in, m2in, m3in) return result def threej_pt(l1, l2, l3, m1, m2, m3): """ Convenience testing function to get 3j for specific arguments. Normally use threej to get an array at once for same cost. :param l1: L_1 :param l2: L_2 :param l3: L_3 :param m1: M_1 :param m2: M_2 :param m3: M_3 :return: Wigner 3j (integer zero if outside triangle constraints) """ if m1 + m2 + m3: return 0 l1min = max(np.abs(l2 - l3), np.abs(m1)) if l1 < l1min or l1 > l2 + l3: return 0 wigner = threej(l2, l3, m2, m3) return wigner[l1 - l1min] # Utils_3j_integrate(W,lmax_w, n, dopol, M, lmax) _coupling_3j = camblib.__mathutils_MOD_integrate_3j _coupling_3j.argtypes = [numpy_2d, POINTER(c_int), POINTER(c_int), POINTER(c_bool), numpy_3d, POINTER(c_int)] def threej_coupling(W, lmax, pol=False): r""" Calculate symmetric coupling matrix :math`\Xi` for given weights :math:`W_{\ell}`, where :math:`\langle\tilde{C}_\ell\rangle = \Xi_{\ell \ell'} (2\ell'+1) C_\ell`. The weights are related to the power spectrum of the mask P by :math:`W_\ell = (2 \ell + 1) P_\ell / 4 \pi`. See e.g. Eq D16 of `arxiv:0801.0554 <http://arxiv.org/abs/0801.0554>`_. If pol is False and W is an array of weights, produces array of temperature couplings, otherwise for pol is True produces set of TT, TE, EE, EB couplings (and weights must have one spectrum - for same masks - or three). Use :func:`scalar_coupling_matrix` or :func:`pcl_coupling_matrix` to get the coupling matrix directly from the mask power spectrum. :param W: 1d array of Weights for each L, or list of arrays of weights (zero based) :param lmax: lmax for the output matrix (assumed symmetric, though not in principle) :param pol: if pol, produce TT, TE, EE, EB couplings for three input mask weights (or one if assuming same mask) :return: symmetric coupling matrix or array of matrices """ if not isinstance(W, (list, tuple)): W = [W] if pol: n = 4 if len(W) == 1: W = W * 3 assert len(W) == 3 else: n = len(W) M = np.zeros((n, lmax + 1, lmax + 1)) nW = len(W) lmax_w = min(2 * lmax, len(W[0]) - 1) for m in W[1:]: assert lmax_w == min(2 * lmax, len(m) - 1) Wmat = np.empty((nW, lmax_w + 1)) for i, m in enumerate(W): Wmat[i, :] = m[:lmax_w + 1] _coupling_3j(Wmat, c_int(lmax_w), c_int(nW), c_bool(pol), M, c_int(lmax)) if n == 1: return M[0, :, :] else: return [M[i, :, :] for i in range(n)] def scalar_coupling_matrix(P, lmax): """ Get scalar Pseudo-Cl coupling matrix from power spectrum of mask, or array of power masks. Uses multiple threads. See Eq A31 of `astro-ph/0105302 <https://arxiv.org/abs/astro-ph/0105302>`_ :param P: power spectrum of mask, or list of mask power spectra :param lmax: lmax for the matrix (assumed square) :return: coupling matrix (square but not symmetric), or list of couplings for different masks """ if not isinstance(P, (list, tuple)): P = [P] elif any(x.size != P[0].size for x in P[1:]): raise ValueError('Mask power spectra must have same lmax') lmax_power = min(P[0].size - 1, 2 * lmax) if lmax_power < 2 * lmax: print('Warning: power spectrum lmax is less than 2*lmax') fac = (2 * np.arange(lmax_power + 1) + 1) / 4 / np.pi M = threej_coupling([fac * power for power in P], lmax) factor = 2 * np.arange(lmax + 1) + 1 if len(P) == 1: return M * factor else: return [m * factor for m in M] def pcl_coupling_matrix(P, lmax, pol=False): """ Get Pseudo-Cl coupling matrix from power spectrum of mask. Uses multiple threads. See Eq A31 of `astro-ph/0105302 <https://arxiv.org/abs/astro-ph/0105302>`_ :param P: power spectrum of mask :param lmax: lmax for the matrix :param pol: whether to calculate TE, EE, BB couplings :return: coupling matrix (square but not symmetric), or list of TT, TE, EE, BB if pol """ lmax_power = min(P.size - 1, 2 * lmax) if lmax_power < 2 * lmax: print('Warning: power spectrum lmax is less than 2*lmax') W = (2 * np.arange(lmax_power + 1) + 1) * P / (4 * np.pi) M = threej_coupling(W, lmax, pol=pol) factor = 2 * np.arange(lmax + 1) + 1 if pol: return [mat * factor for mat in M] else: return M * factor _gauss_legendre = camblib.__mathutils_MOD_gauss_legendre _gauss_legendre.argtypes = [numpy_1d, numpy_1d, int_arg] def gauss_legendre(xvals, weights, npoints): _gauss_legendre(xvals, weights, c_int(npoints))
cmbantREPO_NAMECAMBPATH_START.@CAMB_extracted@CAMB-master@camb@mathutils.py@.PATH_END.py
{ "filename": "_iconsize.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/layout/map/layer/symbol/_iconsize.py", "type": "Python" }
import _plotly_utils.basevalidators class IconsizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="iconsize", parent_name="layout.map.layer.symbol", **kwargs ): super(IconsizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@layout@map@layer@symbol@_iconsize.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/treemap/marker/colorbar/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._yref import YrefValidator from ._ypad import YpadValidator from ._yanchor import YanchorValidator from ._y import YValidator from ._xref import XrefValidator from ._xpad import XpadValidator from ._xanchor import XanchorValidator from ._x import XValidator from ._title import TitleValidator from ._tickwidth import TickwidthValidator from ._tickvalssrc import TickvalssrcValidator from ._tickvals import TickvalsValidator from ._ticktextsrc import TicktextsrcValidator from ._ticktext import TicktextValidator from ._ticksuffix import TicksuffixValidator from ._ticks import TicksValidator from ._tickprefix import TickprefixValidator from ._tickmode import TickmodeValidator from ._ticklen import TicklenValidator from ._ticklabelstep import TicklabelstepValidator from ._ticklabelposition import TicklabelpositionValidator from ._ticklabeloverflow import TicklabeloverflowValidator from ._tickformatstopdefaults import TickformatstopdefaultsValidator from ._tickformatstops import TickformatstopsValidator from ._tickformat import TickformatValidator from ._tickfont import TickfontValidator from ._tickcolor import TickcolorValidator from ._tickangle import TickangleValidator from ._tick0 import Tick0Validator from ._thicknessmode import ThicknessmodeValidator from ._thickness import ThicknessValidator from ._showticksuffix import ShowticksuffixValidator from ._showtickprefix import ShowtickprefixValidator from ._showticklabels import ShowticklabelsValidator from ._showexponent import ShowexponentValidator from ._separatethousands import SeparatethousandsValidator from ._outlinewidth import OutlinewidthValidator from ._outlinecolor import OutlinecolorValidator from ._orientation import OrientationValidator from ._nticks import NticksValidator from ._minexponent import MinexponentValidator from ._lenmode import LenmodeValidator from ._len import LenValidator from ._labelalias import LabelaliasValidator from ._exponentformat import ExponentformatValidator from ._dtick import DtickValidator from ._borderwidth import BorderwidthValidator from ._bordercolor import BordercolorValidator from ._bgcolor import BgcolorValidator else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name__, [], [ "._yref.YrefValidator", "._ypad.YpadValidator", "._yanchor.YanchorValidator", "._y.YValidator", "._xref.XrefValidator", "._xpad.XpadValidator", "._xanchor.XanchorValidator", "._x.XValidator", "._title.TitleValidator", "._tickwidth.TickwidthValidator", "._tickvalssrc.TickvalssrcValidator", "._tickvals.TickvalsValidator", "._ticktextsrc.TicktextsrcValidator", "._ticktext.TicktextValidator", "._ticksuffix.TicksuffixValidator", "._ticks.TicksValidator", "._tickprefix.TickprefixValidator", "._tickmode.TickmodeValidator", "._ticklen.TicklenValidator", "._ticklabelstep.TicklabelstepValidator", "._ticklabelposition.TicklabelpositionValidator", "._ticklabeloverflow.TicklabeloverflowValidator", "._tickformatstopdefaults.TickformatstopdefaultsValidator", "._tickformatstops.TickformatstopsValidator", "._tickformat.TickformatValidator", "._tickfont.TickfontValidator", "._tickcolor.TickcolorValidator", "._tickangle.TickangleValidator", "._tick0.Tick0Validator", "._thicknessmode.ThicknessmodeValidator", "._thickness.ThicknessValidator", "._showticksuffix.ShowticksuffixValidator", "._showtickprefix.ShowtickprefixValidator", "._showticklabels.ShowticklabelsValidator", "._showexponent.ShowexponentValidator", "._separatethousands.SeparatethousandsValidator", "._outlinewidth.OutlinewidthValidator", "._outlinecolor.OutlinecolorValidator", "._orientation.OrientationValidator", "._nticks.NticksValidator", "._minexponent.MinexponentValidator", "._lenmode.LenmodeValidator", "._len.LenValidator", "._labelalias.LabelaliasValidator", "._exponentformat.ExponentformatValidator", "._dtick.DtickValidator", "._borderwidth.BorderwidthValidator", "._bordercolor.BordercolorValidator", "._bgcolor.BgcolorValidator", ], )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@treemap@marker@colorbar@__init__.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "LSSTDESC/CCL", "repo_path": "CCL_extracted/CCL-master/pyccl/tests/__init__.py", "type": "Python" }
LSSTDESCREPO_NAMECCLPATH_START.@CCL_extracted@CCL-master@pyccl@tests@__init__.py@.PATH_END.py
{ "filename": "_ticklabelposition.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/barpolar/marker/colorbar/_ticklabelposition.py", "type": "Python" }
import _plotly_utils.basevalidators class TicklabelpositionValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="ticklabelposition", parent_name="barpolar.marker.colorbar", **kwargs ): super(TicklabelpositionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), role=kwargs.pop("role", "info"), values=kwargs.pop( "values", [ "outside", "inside", "outside top", "inside top", "outside bottom", "inside bottom", ], ), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@barpolar@marker@colorbar@_ticklabelposition.py@.PATH_END.py
{ "filename": "binomialFPEffectiveness.ipynb", "repo_name": "stevepur/DR25-occurrence-public", "repo_path": "DR25-occurrence-public_extracted/DR25-occurrence-public-main/GKbaseline/binomialFPEffectiveness.ipynb", "type": "Jupyter Notebook" }
Reliability is given by $$ R = \frac{N_{\mathrm{truePC}}}{N_{\mathrm{obsPC}}} = 1 - \frac{N_{\mathrm{obsFP}}}{N_{\mathrm{obsPC}}} \left( \frac{1 - E}{E} \right) = 1 - \frac{F_{\mathrm{obsFP}}}{F_{\mathrm{obsPC}}} \left( \frac{1 - E}{E} \right) $$ where $E = N_{\mathrm{obsFP}}/N_{\mathrm{trueFP}}$ is the false positive effectiveness, $F_{\mathrm{obsFP}} = N_{\mathrm{obsFP}}/N_{\mathrm{obsTCEs}}$ is the fraction of observed TCEs that are dispositioned as FP and $F_{\mathrm{obsPC}} = N_{\mathrm{obsPC}}/N_{\mathrm{obsTCEs}}$ is the fraction of TCEs dispositioned as PC. We will separately measure $E$ and $F_{\mathrm{obsFP}}$ as binomial point processes with probabilities that depend on period and MES. Once we have $F_{\mathrm{obsFP}}$ then $F_{\mathrm{obsPC}} = 1 - F_{\mathrm{obsFP}}$, assuming that $N_{\mathrm{obsTCEs}} = N_{\mathrm{obsPC}} + N_{\mathrm{obsFP}}$. We think of TCEs as consisting of two sets: those that are dispositioned as FP and those that are dispositioned as PC. We do this for both the observed TCEs, and for inverted/scrambled TCEs, where all TCEs are true false positives. Then we can think of the vetting process as drawing from the set of TCEs, with a probability $r$ of selecting either PCs or FPs. Then the probability distribution of selecting $c$ FPs from $n$ TCEs is given by the binomial distribution $$P\{c\} = \left( \begin{array}{c} n \\ c \end{array} \right) r^c (1-r)^{n-c}.$$ To measure $E$ we use the inverted and scrambled data sets, where all detected TCEs are by definition FPs. We define $E$ as the probability of drawing FPs from inverted/scrambled TCEs, found via the Bayesian inference $p(E|n, c) \propto p(c|E, n) p(E)$, where $$p(c|E, n) = \left( \begin{array}{c} n \\ c \end{array} \right) E^c (1-E)^{n-c}$$ and $p(E)$ is a prior distribution of the probability $E$. By putting the data on a grid indexed by $i,j$, we can fit effectiveness as a function parameterized by a vector $\theta$, $E(\theta,\mathrm{period},\mathrm{MES})$, as $p(\theta)|n_{i,j}, c_{i,j}, \mathrm{period}_{i,j},\mathrm{MES}_{i,j}) \propto p(c_{i,j}|\theta, n_{i,j}, \mathrm{period}_{i,j},\mathrm{MES}_{i,j}) p(\theta)$, where $p(\theta)$ is some prior distribution of the parameters. To measure $F_{\mathrm{obsFP}}$ we perform a similar inference using the set of observed TCEs, and inferring the probability of drawing c FPs from n observed TCEs. The inference in this case becomes $p(F_{\mathrm{obsFP}}|n, c) \propto p(c|F_{\mathrm{obsFP}}, n) p(F_{\mathrm{obsFP}})$, which we can parameterize interms of a function similar to effectiveness. ```python import numpy as np import matplotlib.pyplot as plt import scipy.special as spec import pandas as pd from astropy.io import ascii from astropy.table import Table, vstack import sys sys.path.insert(0, '..') import dr25Models as funcModels ``` First we set the parameters space for our analysis. ```python stellarType = "GK" scoreCut = 0.0; if False: periodMin = 200; periodMax = 400; # rpMin = 0.75; # rpMax = 2.0; rpMin = 0; rpMax = 100; mesMin = 7; mesMax = 15; else: periodMin = 50; periodMax = 600; rpMin = 0.5; rpMax = 15; mesMin = 7; mesMax = 30; ``` ```python def drawHeatMap(dataArray, imageSize, x, y, nData=[], colorBarLabel="", textOn=True, forceInt=True): dx = x[(1,0)] - x[(0,0)]; dy = y[(0,1)] - y[(0,0)]; extent = [x[(0,0)], x[(-1,0)]+dx,y[(0,0)],y[(0,-1)]+dy]; plt.figure(figsize=imageSize); # fig, ax = plt.subplots(figsize=imageSize); ax = plt.gca() da = np.transpose(dataArray); # im = ax.imshow(da, extent = extent, origin='lower'); im = ax.imshow(da, extent = extent, origin='lower', cmap="Greys"); ax.set_aspect(10); if len(nData) == 0: nData = np.ones(dataArray.shape) # ax.imshow(da, origin='lower'); arrayShape = da.shape; minda = np.min(da) maxda = np.max(da) daRange = maxda - minda; for i in range(arrayShape[0]): for j in range(arrayShape[1]): if da[i, j] > minda + daRange*0.5: # cstr = "k" cstr = "w" else: # cstr = "w" cstr = "k" if np.abs(da[i,j]) < 100: fsz = 9 else: fsz = 9 if textOn: if nData[(j,i)] > 0: if forceInt: ax.text(x[(j,i)]+dx/2, y[(j,i)]+dy/2, da[i, j].astype("int"), ha="center", va="center", color=cstr, fontsize=fsz) else: ax.text(x[(j,i)]+dx/2, y[(j,i)]+dy/2, da[i, j], ha="center", va="center", color=cstr, fontsize=fsz) else: ax.text(x[(j,i)]+dx/2, y[(j,i)]+dy/2, "-", ha="center", va="center", color=cstr, fontsize=fsz) ax.tick_params(axis = "both", labelsize = 12) im_ratio = float(da.shape[0])/da.shape[1] cbh = plt.colorbar(im,fraction=0.024*im_ratio, pad=0.02) cbh.ax.set_ylabel(colorBarLabel, fontSize = 16); # ax.invert_yaxis(); ``` Then we load our data, which consists of the stellar catalog, observed TCEs, inverted TCEs and scrambled TCEs. We convert the tables to Pandas for manipulation. ```python # not currently used # load skygroup maps for the FOV position dependence study # obsSkygroupMap = ascii.read("../data/obsTceToSkygroup.txt"); ``` ```python dataLoc = "../data/" # starlist = dataLoc + "dr25_stellar_updated_feh_" + stellarType + ".txt" starlist = "../stellarCatalogs/dr25_stellar_berger2019_clean_" + stellarType + ".txt" kic = pd.read_csv(starlist) invList = dataLoc + "kplr_dr25_inv_tces.txt" scr1List = dataLoc + "kplr_dr25_scr1_tces.txt" scr2List = dataLoc + "kplr_dr25_scr2_tces.txt" scr3List = dataLoc + "kplr_dr25_scr3_tces.txt" invTcesFull = ascii.read(invList); scr1TcesFull = ascii.read(scr1List); scr2TcesFull = ascii.read(scr2List); scr3TcesFull = ascii.read(scr3List); invTcesFullPd = invTcesFull.to_pandas(); scr1TcesFullPd = scr1TcesFull.to_pandas(); scr2TcesFullPd = scr2TcesFull.to_pandas(); scr3TcesFullPd = scr3TcesFull.to_pandas(); ``` We have to remove the TCEs that are on the drop lists ```python invDropList = ascii.read(dataLoc + "kplr_droplist_inv.txt"); scr1DropList = ascii.read(dataLoc + "kplr_droplist_scr1.txt"); scr2DropList = ascii.read(dataLoc + "kplr_droplist_scr2.txt"); scr3DropList = ascii.read(dataLoc + "kplr_droplist_scr3.txt"); invDropList = invDropList.to_pandas(); scr1DropList = scr1DropList.to_pandas(); scr2DropList = scr2DropList.to_pandas(); scr3DropList = scr3DropList.to_pandas(); invTcesPd = invTcesFullPd[~invTcesFullPd['TCE_ID'].isin(invDropList['TCE_ID'])]; scr1TcesPd = scr1TcesFullPd[~scr1TcesFullPd['TCE_ID'].isin(scr1DropList['TCE_ID'])]; scr2TcesPd = scr2TcesFullPd[~scr2TcesFullPd['TCE_ID'].isin(scr2DropList['TCE_ID'])]; scr3TcesPd = scr3TcesFullPd[~scr3TcesFullPd['TCE_ID'].isin(scr3DropList['TCE_ID'])]; print("length of invTcesFull = " + str(len(invTcesFullPd)) + ", length of invTces = " + str(len(invTcesPd))) print("length of scr1TcesFull = " + str(len(scr1TcesFullPd)) + ", length of scr1Tces = " + str(len(scr1TcesPd))) print("length of scr2TcesFull = " + str(len(scr2TcesFullPd)) + ", length of scr2Tces = " + str(len(scr2TcesPd))) print("length of scr3TcesFull = " + str(len(scr3TcesFullPd)) + ", length of scr3Tces = " + str(len(scr3TcesPd))) ``` length of invTcesFull = 19531, length of invTces = 14952 length of scr1TcesFull = 24209, length of scr1Tces = 13778 length of scr2TcesFull = 24217, length of scr2Tces = 13817 length of scr3TcesFull = 19811, length of scr3Tces = 9240 Now convert back to astropy tables, and combine the scrambled TCEs into one list ```python invTces = Table.from_pandas(invTcesPd) scr1Tces = Table.from_pandas(scr1TcesPd) scr2Tces = Table.from_pandas(scr2TcesPd) scr3Tces = Table.from_pandas(scr3TcesPd) # create a final set of scrambled TCEs scrTces = vstack([scr1Tces, scr2Tces, scr3Tces]) # scrTces = scr1Tces print("length of scrTces = " + str(len(scrTces))) ``` length of scrTces = 36835 Resstrict to the chosen stellar population ```python invTces = invTces[np.in1d(invTces['KIC'],kic.kepid)] scrTces = scrTces[np.in1d(scrTces['KIC'],kic.kepid)] print("length of invTces = " + str(len(invTces))) print("length of scrTces = " + str(len(scrTces))) ``` length of invTces = 1014 length of scrTces = 3238 There are three examples of TCEs compared to one set of inverted TCEs. So maybe subsample the scrTCEs by a factor of three. ```python subSample = np.random.rand(len(scrTces)) # scrTcesSub = scrTces[subSample < 1./3] scrTcesSub = scrTces print("length of scrTcesSub = " + str(len(scrTcesSub))) ``` length of scrTcesSub = 3238 Create the final list of synthetic FPs by concatanating the inverted and subset of the scrambled lists. ```python # syntheticTrueFps = vstack([invTces,scrTcesSub]) syntheticTrueFps = vstack([invTces,invTces,invTces,scrTcesSub]) print("length of syntheticTrueFps = " + str(len(syntheticTrueFps))) ``` length of syntheticTrueFps = 6280 Restrict to the desired radius and period range ```python ``` ```python spIndex = np.where(np.all([ syntheticTrueFps['Rp']>rpMin,syntheticTrueFps['Rp']<rpMax,\ syntheticTrueFps['period']>periodMin,syntheticTrueFps['period']<periodMax], axis=0)) spSyntheticTrueFps = syntheticTrueFps[spIndex] print("length of spSyntheticTrueFps = " + str(len(spSyntheticTrueFps))) ``` length of spSyntheticTrueFps = 5501 Separate out the dispositioned PC and FPs ```python # spSyntheticPcs = spSyntheticTrueFps[(spSyntheticTrueFps['NTL']==0) & (spSyntheticTrueFps['SS']==0) # & (spSyntheticTrueFps['CO']==0) & (spSyntheticTrueFps['Score']>=scoreCut)] # spSyntheticFps = spSyntheticTrueFps[(spSyntheticTrueFps['NTL']==1) | (spSyntheticTrueFps['SS']==1) # | (spSyntheticTrueFps['CO']==1) | (spSyntheticTrueFps['Score']<scoreCut)] spSyntheticPcs = spSyntheticTrueFps[(spSyntheticTrueFps['Disp']=='PC') & (spSyntheticTrueFps['Score']>=scoreCut)] spSyntheticFps = spSyntheticTrueFps[(spSyntheticTrueFps['Disp']=='FP') | (spSyntheticTrueFps['Score']<scoreCut)] print("length of spSyntheticPcs = " + str(len(spSyntheticPcs))) print("length of spSyntheticFps = " + str(len(spSyntheticFps))) ``` length of spSyntheticPcs = 73 length of spSyntheticFps = 5428 Let's see what this population looks like. ```python plt.figure(figsize=(10,5)); # plt.subplot(2,2,1); plt.plot(spSyntheticFps['period'], spSyntheticFps['MES'], ".", spSyntheticPcs['period'], spSyntheticPcs['MES'], "*"); plt.ylim(mesMin,mesMax); plt.xlim(periodMin,periodMax); plt.legend(("inv/scr FPs", "inv/scr PC")); plt.ylabel('MES'); plt.xlabel('Period'); ``` ![png](output_24_0.png) Bin the data so we have n TCEs and c FPs in each bin. ```python dPeriod = 20; dMes = 1; p0 = periodMin; pEnd = periodMax; m0 = mesMin; mEnd = mesMax; # make the period-mes grid NPeriod = int((pEnd - p0)/dPeriod); NMes = int((mEnd - m0)/dMes); tceGrid = np.zeros((NPeriod,NMes)); cellPeriod = np.zeros((NPeriod,NMes)); cellMes = np.zeros((NPeriod,NMes)); pcGrid = np.zeros((NPeriod,NMes)); fpGrid = np.zeros((NPeriod,NMes)); # count how many points are in each cell for p in range(NPeriod): for m in range(NMes): cellPeriod[(p,m)] = p0 + p*dPeriod; cellMes[(p,m)] = m0 + m*dMes; pointsInCell = np.where( (spSyntheticTrueFps['period'] > cellPeriod[(p,m)]) & (spSyntheticTrueFps['period'] <= cellPeriod[(p,m)]+dPeriod) & (spSyntheticTrueFps['MES'] > cellMes[(p,m)]) & (spSyntheticTrueFps['MES'] <= cellMes[(p,m)]+dMes)); tceGrid[(p,m)] = len(pointsInCell[0]); pointsInCell = np.where( (spSyntheticPcs['period'] > cellPeriod[(p,m)]) & (spSyntheticPcs['period'] <= cellPeriod[(p,m)]+dPeriod) & (spSyntheticPcs['MES'] > cellMes[(p,m)]) & (spSyntheticPcs['MES'] <= cellMes[(p,m)]+dMes)); pcGrid[(p,m)] = len(pointsInCell[0]); pointsInCell = np.where( (spSyntheticFps['period'] > cellPeriod[(p,m)]) & (spSyntheticFps['period'] <= cellPeriod[(p,m)]+dPeriod) & (spSyntheticFps['MES'] > cellMes[(p,m)]) & (spSyntheticFps['MES'] <= cellMes[(p,m)]+dMes)); fpGrid[(p,m)] = len(pointsInCell[0]); drawHeatMap(tceGrid, (15,15), cellPeriod, cellMes, colorBarLabel="# of TCEs"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); plt.savefig("fpEffNTces.pdf",bbox_inches='tight') plt.title("All Inverted/Scrambled TCEs"); drawHeatMap(pcGrid, (15,15), cellPeriod, cellMes); plt.title("Inverted/Scrambled PCs"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); drawHeatMap(fpGrid, (15,15), cellPeriod, cellMes); plt.title("Inverted/Scrambled FPs"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); ``` ![png](output_26_0.png) ![png](output_26_1.png) ![png](output_26_2.png) Compute the PC and FC fractions in each cell to get a sense of what the fractions look like. These are not used in the inference. ```python minTcePerCell = 0; pcFrac = np.zeros(np.shape(tceGrid)) pcFrac[tceGrid>minTcePerCell] = pcGrid[tceGrid>minTcePerCell]/tceGrid[tceGrid>minTcePerCell]; drawHeatMap(np.round(100*pcFrac), (10,10), cellPeriod, cellMes); plt.title("Inverted/Scrambled PC Fraction (%)"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); ``` ![png](output_28_0.png) ```python fpFrac = np.zeros(np.shape(tceGrid)) fpFrac[tceGrid>minTcePerCell] = fpGrid[tceGrid>minTcePerCell]/tceGrid[tceGrid>minTcePerCell]; drawHeatMap(np.round(100*fpFrac), (15,15), cellPeriod, cellMes, colorBarLabel="FP Fraction (%)", nData = tceGrid); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); plt.savefig("fpEffFPFrac.pdf",bbox_inches='tight') plt.title("Inverted/Scrambled FP Fraction (%)"); ``` ![png](output_29_0.png) Prepare the data for the call to emcee to do the Bayesian inference. ```python ``` ```python cFp = fpGrid.flatten(); nTce = tceGrid.flatten(); # convert to homogeneous coordinates on unit square [0,1] cellX, cellY = funcModels.normalizeRange(cellPeriod, cellMes, [periodMin, periodMax], [mesMin, mesMax]); gridShape = np.shape(cellX); dx = 1./gridShape[0]; dy = 1./gridShape[1]; print("gridShape = " + str(gridShape) + ", dx = " + str(dx) + ", dy = " + str(dy)) cellXFlat = cellX.flatten(); cellYFlat = cellY.flatten(); cFp[nTce<minTcePerCell] = 0; nTce[nTce<minTcePerCell] = 0; tceData = [cellXFlat, cellYFlat, nTce, cFp]; ``` gridShape = (27, 23), dx = 0.037037037037, dy = 0.0434782608696 We're ready to compute a Bayesian inference of the success probability $r$: $$p(r|c, n) \propto p(c|r, n) p(r).$$ But we're computing $r$ as a function of period $p$, MES $m$, and parameters $\theta$, $r(\theta, p, m)$. So our inference becomes $$p(\theta|c, n, p, m) \propto p(c|\theta, n, p, m) p(\theta).$$ Because each cell is independent, we linearize the array to a list of cells indexed by $k$. Then the likelihood for each cell is $$p(c_k|\theta, n_k, p_k, m_k) = \left( \begin{array}{c_k} n_k \\ c_k \end{array} \right) r(\theta, p_k , m_k )^{c_k} (1-r(\theta, p_k , m_k ))^{n_k-c_k}$$ Because the $N$ cells are independent, the likelihood for the collection of cells is $$p(c|\theta, n, p, m) \equiv p(c_1, \ldots, c_N|\theta, n_1, \ldots, n_N, p_1, \ldots, p_N, m_1, \ldots, m_N) = \prod_k \left( \begin{array}{c_k} n_k \\ c_k \end{array} \right) r(\theta, p_k , m_k )^{c_k} (1-r(\theta, p_k , m_k ))^{n_k-c_k}.$$ The log-likelihood is then $$\log p(c|\theta, n, p, m) = \sum_k \log \left(\left( \begin{array}{c_k} n_k \\ c_k \end{array} \right) r(\theta, p_k , m_k )^{c_k} (1-r(\theta, p_k , m_k ))^{n_k-c_k} \right)$$ $$= \sum_k \left[ \log \left(\begin{array}{c_k} n_k \\ c_k \end{array} \right) + c_k \log \left(r(\theta, p_k , m_k ) \right) + \left( n_k-c_k \right) \log(1-r(\theta, p_k , m_k )) \right] $$ Define a nice collection of models to play with. Define the likelihood and prior functions. ```python def lnBinlike(theta, data, model): x, y, n, c = data r = funcModels.rateModel(x,y,theta,model); clnr = c*np.log(r); clnr[c==0] = 0; lpl = np.sum(np.log(spec.comb(n,c)) + clnr + (n-c)*np.log(1-r)); return lpl def lnBinprior(theta, data, model): x, y, n, c = data # print(theta) if model == "constant": if 0.0 <= theta[0] <= 1: return 1.0 elif model == "linearX": if -5000.0 < theta[0] < 5000.0 and 0.0 < theta[1] < 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "linearXY": if -5000.0 < theta[0] < 5000.0 and -5000.0 < theta[1] < 5000.0 \ and 0.0 < theta[2] < 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "gaussian": if 0.45 < theta[0] < 1 and 0 <= theta[1] < 0.5 \ and 1e-2 < theta[2] < 10 and 1e-2 < theta[3] < 10 and -1 <= theta[4] <= 1 and 0 <= theta[5] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticX": if -1 < theta[0] < 2.0 \ and 1e-4 < theta[1] < 1e4 and 0 < theta[2] < 1e6 and 0 < theta[3] < 1e6 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticY": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 100 and 0 < theta[2] <= 0.1 and 0.9 < theta[3] <= 1 \ and 0 < theta[2] + theta[3] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticY": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 100 and -180 < theta[2] <= 180 \ and 0 < theta[3] <= 0.2 and 0.8 < theta[4] <= 1 \ and 0 < theta[3] + theta[4] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticY2": if -1 <= theta[0] <= 2 and 1e-4 < theta[1] < 100 \ and 0.1 < theta[2] <= 1000 and -180 < theta[3] <= 180 \ and 0 < theta[4] <= 0.2 and 0.8 < theta[5] <= 1 \ and 0 < theta[4] + theta[5] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticYXFixedLogisticY": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 100 and -180 < theta[2] <= 180 \ and 0 < theta[3] <= 0.2 and 0.8 < theta[4] <= 1 \ and 0 < theta[3] + theta[4] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticYXLogisticY": if -1 <= theta[0] <= 2 and 1e-4 < theta[1] < 100 \ and -1 <= theta[2] <= 2 and 1e-4 < theta[3] < 100 \ and -180 < theta[4] <= 180 \ and 0 < theta[5] <= 0.2 and 0.8 < theta[6] <= 1 \ and 0 < theta[5] + theta[6] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticY2": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 1e4 and 0.1 < theta[2] <= 1000 and 0 < theta[3] <= 0.1 and 0.9 < theta[4] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticX0": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 1e4 and 0 < theta[2] < 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticY0": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 1e4 and 0 < theta[2] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticY02": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 1e4 and 0.1 < theta[2] <= 1000 and 0 < theta[3] <= 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "logisticX0xlogisticY0": if 0 <= theta[0] <= 1e3 and 0 <= theta[1] <= 1e3 \ and 1e-4 < theta[2] < 1e4 and 1e-4 < theta[3] < 1e4 \ and 0 < theta[4] < 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticX0xlogisticY0": if -1 <= theta[0] <= 2 and -1 <= theta[1] <= 2 \ and 1e-4 < theta[2] < 1e4 and 1e-4 < theta[3] < 1e4 \ and -3 < theta[4] < 3 and -180 < theta[5] < 180 \ and 0 < theta[6] < 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticX0": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 100 and 0 < theta[2] <= 1 and -180 < theta[3] < 180 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticX02": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 100 and 0.1 < theta[2] <= 1000 and 0 < theta[3] <= 1 and -180 < theta[4] < 180 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "rotatedLogisticX0+gaussian": if -1 <= theta[0] <= 2 \ and 1e-4 < theta[1] < 100 and 0 < theta[2] <= 1 and -180 < theta[3] < 180 \ and 0.45 < theta[4] < 1 and 0 <= theta[5] < 0.5 \ and 1e-2 < theta[6] < 2 and 1e-2 < theta[7] < 2 and -1 <= theta[8] <= 0 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 elif model == "dualBrokenPowerLaw": # print(funcModels.rateModel(x, y, theta, model)) if 0 <= theta[0] <= 1 and 0 <= theta[1] <= 1 \ and -2 < theta[2] < 0 and -2 < theta[3] < 0 and 0 < theta[4] < 1e4 and 0 < theta[5] < 1e4 \ and 0 < theta[6] < 1 \ and np.min(funcModels.rateModel(x, y, theta, model)) >= 0 \ and np.max(funcModels.rateModel(x, y, theta, model)) <= 1: return 1.0 else: raise ValueError('Bad model name'); # print(theta) return -np.inf def lnBinprob(theta, data, model): lp = lnBinprior(theta, data, model) # print("lnPoisprior = " + str(lp)) if not np.isfinite(lp): return -np.inf # print(str(lnPoislike(theta, A, c))) return lp + lnBinlike(theta, data, model) ``` Fit the effectiveness. We perform the MCMC calculation of the log posterior. We use a manual three-part strategy to find the best seed point: first we use the initial values in the model definitions. This MCMC result is used to seed the second iterations, whose result is used to seed the third and final iteration. We then initialize the MCMC walkers with a small Gaussian distribution around these starting points. ```python model = "rotatedLogisticX0" if model == "constant": initialPos = funcModels.initRateModel(model); elif model == "logisticY0": initialPos = funcModels.initRateModel(model); elif model == "logisticY": initialPos = [-2.63785585e-02, 20, 0.02, 0.98]; elif model == "rotatedLogisticY": # initialPos = [ 0.04944521, 23.31556305, -25.49590252, 0.04268818, 0.95325393]; initialPos = [ 4.83412482e-02, 3.95216090e+01, -3.82447066e+01, 3.88681300e-02, 9.54596550e-01] elif model == "rotatedLogisticY2": initialPos = [ 4.83412482e-02, 3.95216090e+01, 1, -3.82447066e+01, 3.88681300e-02, 9.54596550e-01] elif model == "rotatedLogisticYXLogisticY": initialPos = [ 0.04944521, 23.31556305, -2.63785585e-02, 20, -25.49590252, 0.04268818, 0.95325393]; elif model == "logisticY02": initialPos = [-1.73396324e-01, 10, 2, 9.90011008e-01]; elif model == "gaussian": # initialPos = funcModels.initRateModel(model); initialPos = [ 0.62, 0.04, 1, 1, -0.01, 9.91039169e-01] elif model == "dualBrokenPowerLaw": initialPos = [ 0.96811698, 0.01257312, -0.00171099, -1e-2, 0.73671063, 0.00555828, 0.99154711] elif model == "rotatedLogisticX0": initialPos = [ 1.2, 9.7715652, 0.99773284, 106.91479715]; elif model == "rotatedLogisticX02": initialPos = [ 1.2, 9.7715652, 1.0, 0.99773284, 106.91479715]; elif model == "rotatedLogisticX0+gaussian": initialPos = funcModels.initRateModel(model); elif model == "rotatedLogisticX0xlogisticY0": initialPos = [ 1.50565457e+00, -3.09826269e-01, 4.92718937e+03, 1.36096954e+01, 5.52126518e-02, -1.23504297e+01, 9.97222157e-01]; else: initialPos = funcModels.initRateModel(model); print(initialPos) ``` [1.2, 9.7715652, 0.99773284, 106.91479715] ```python import scipy.optimize as op nll = lambda *args: -lnBinlike(*args) result = op.minimize(nll, initialPos, args=(tceData, model)) maxLikelihoodResult = result["x"]; modelLabels = funcModels.getModelLabels(model) for i in range(0,len(maxLikelihoodResult)): print("maximum Likelihood " + modelLabels[i] + ":={:.3f}".format(maxLikelihoodResult[i])) if lnBinprior(maxLikelihoodResult, tceData, model) == -np.inf: maxLikelihoodResult = initialPos; print("violates prior, replacing maxLikelihoodResult result with initialPos") x, y, n, c = tceData r = funcModels.rateModel(x,y,maxLikelihoodResult,model); print("maximum Likelihood rate min = {:.3f}".format(np.min(np.min(r))) + ", max = {:.3f}".format(np.max(np.max(r)))) ``` maximum Likelihood $x_0$:=524.592 maximum Likelihood $k_x$:=23.368 maximum Likelihood $A$:=892.920 maximum Likelihood $\phi$:=108.299 violates prior, replacing maxLikelihoodResult result with initialPos maximum Likelihood rate min = 0.676, max = 0.998 /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:6: RuntimeWarning: invalid value encountered in log /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/numpy/core/fromnumeric.py:83: RuntimeWarning: invalid value encountered in reduce return ufunc.reduce(obj, axis, dtype, out, **passkwargs) ```python import emcee ndim, nwalkers = len(maxLikelihoodResult), 100 pos = [maxLikelihoodResult + 1e-3*np.random.randn(ndim) for i in range(nwalkers)] sampler = emcee.EnsembleSampler(nwalkers, ndim, lnBinprob, args=(tceData, model)) # sampler = emcee.EnsembleSampler(nwalkers, ndim, lnBinprob, args=(cellXFlat, cellYFlat, nTce, cFp, model)) sampler.run_mcmc(pos, 10000); samples = sampler.chain[:, 5000:, :].reshape((-1, ndim)) dataResult = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]), zip(*np.percentile(samples, [16, 50, 84], axis=0))) dataResult = list(dataResult) np.save("binEffPosteriors_" + str(model) + ".npy", samples) modelLabels = funcModels.getModelLabels(model) for i in range(0,ndim): v = dataResult[i]; print("MCMC " + modelLabels[i] + ":={:.3f}".format(v[0]) + "+{:.3f}".format(v[1]) + "-{:.3f}".format(v[2])) # print("true " + modelLabels[i] + ":={:.3f}".format(trueTheta[i])) # print("compared to: rate={:.3f}".format(rate)) resultSize = np.shape(dataResult); fitTheta = np.zeros(resultSize[0]); for i in range(resultSize[0]): fitTheta[i] = dataResult[i][0] print("fitTheta = " + str(fitTheta)) plt.figure(figsize=(10,5)) for i in range(0,ndim): plt.subplot(ndim,1,i+1) plt.plot(np.transpose(sampler.chain[:, :, i]), color="k", alpha=0.1); plt.ylabel(modelLabels[i]); ``` MCMC $x_0$:=1.159+0.062-0.044 MCMC $k_x$:=22.587+8.811-6.291 MCMC $A$:=0.998+0.001-0.002 MCMC $\phi$:=98.551+3.834-2.778 fitTheta = [ 1.15903152 22.58687595 0.99793552 98.55066349] ![png](output_40_1.png) ```python import corner modelLabels = funcModels.getModelLabels(model) # trueTheta = funcModels.initRateModel(model) # fig = corner.corner(samples, labels=["$m$", "$b$", "$\ln\,f$"], # truths=[m_true, b_true, np.log(f_true)]) fig = corner.corner(samples, labels = modelLabels, label_kwargs = {"fontsize": 32}, truths = fitTheta) plt.savefig("fpEffPost.pdf",bbox_inches='tight') ``` ![png](output_41_0.png) We test the result by reconstructing the distribution of FPs and % of FPs using binomial-distributed random numbers, to see if they match the actual data. ```python fitGrid = np.zeros(np.shape(tceGrid)); for p in range(NPeriod): for m in range(NMes): fitGrid[(p,m)] = np.random.binomial(tceGrid[(p,m)], funcModels.rateModel(cellX[(p,m)]+dx/2, cellY[(p,m)]+dx/2, fitTheta, model), 1); drawHeatMap(fitGrid, (15,15), cellPeriod, cellMes); plt.title('reconstructed FPs from the fit'); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); fitFrac = np.zeros(np.shape(tceGrid)) fitFrac[tceGrid>minTcePerCell] = fitGrid[tceGrid>minTcePerCell]/tceGrid[tceGrid>minTcePerCell]; drawHeatMap(np.round(100*fitFrac), (15,15), cellPeriod, cellMes); plt.title('reconstructed FP rate from the fit'); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); ``` ![png](output_43_0.png) ![png](output_43_1.png) ```python from ipywidgets import FloatProgress from IPython.display import display nFits = 1000; fitGrid = np.zeros([np.shape(tceGrid)[0],np.shape(tceGrid)[1],nFits]); sidx = [0]*nFits progress = FloatProgress(min=0, max=nFits) display(progress) for f in range(nFits): sidx[f] = int(np.random.uniform(high=samples.shape[0]-1)); tTheta = samples[sidx[f],:] for p in range(NPeriod): for m in range(NMes): rm = funcModels.rateModel(cellX[(p,m)]+dx/2, cellY[(p,m)]+dy/2, tTheta, model) if rm > 1: rm = 1; fitGrid[(p,m,f)] = np.random.binomial(tceGrid[(p,m)], rm, 1); progress.value += 1 meanFit = np.mean(fitGrid, 2) stdFit = np.std(fitGrid, 2) ``` FloatProgress(value=0.0, max=1000.0) ```python drawHeatMap(meanFit, (15,15), cellPeriod, cellMes); plt.title("Mean reconstructed Observed FPs from the fit"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); fitFracMean = np.zeros(np.shape(tceGrid)) fitFracMean[tceGrid>minTcePerCell] = meanFit[tceGrid>minTcePerCell]/tceGrid[tceGrid>minTcePerCell]; drawHeatMap(np.round(100*fitFracMean), (15,15), cellPeriod, cellMes, nData = tceGrid, colorBarLabel="Mean FP %"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); plt.savefig("fpEffMean.pdf",bbox_inches='tight') plt.title("Mean reconstructed Observed FP rate from the fit"); stdFrac = np.zeros(np.shape(tceGrid)) stdFrac[tceGrid>minTcePerCell] = stdFit[tceGrid>minTcePerCell]/tceGrid[tceGrid>minTcePerCell]; drawHeatMap(np.round(100*stdFrac), (15,15), cellPeriod, cellMes, nData = tceGrid, colorBarLabel="Mean FP %"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); plt.savefig("fpEffStd.pdf",bbox_inches='tight') plt.title("Standard deviation of the reconstructed Observed FP rate from the fit"); ``` ![png](output_45_0.png) ![png](output_45_1.png) ![png](output_45_2.png) ```python fitDiff = fitFracMean - fpFrac fitDiffNorm =np.zeros(fitDiff.shape) fitDiffNorm[stdFit>0] = fitDiff[stdFit>0]/stdFit[stdFit>0]; drawHeatMap(np.round(100*fitDiff), (15,15), cellPeriod, cellMes, nData = tceGrid); plt.title("Residual from mean"); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); drawHeatMap(np.round(fitDiffNorm, 2), (15,15), cellPeriod, cellMes, nData = tceGrid, colorBarLabel="Mean Residual (in standard deviations)", forceInt = False); plt.ylabel('MES', fontsize = 16); plt.xlabel('Period', fontsize = 16); plt.savefig("fpEffMeanResid.pdf",bbox_inches='tight') plt.title("Residual from mean (in standard deviations)"); plt.figure(figsize=(15,5)); plt.hist(fitDiffNorm.flatten()[nTce > 0], 100); np.median(fitDiffNorm.flatten()[nTce > 0]) ``` -0.021124141684148695 ![png](output_46_1.png) ![png](output_46_2.png) ![png](output_46_3.png) ```python ``` ```python def binPdf(n, r, c): return spec.comb(n,c)*(r**c)*((1-r)**(n-c)); def plot_norm_bin(n, r, scale): xx = np.arange(0, n, 0.01) ix = np.arange(0, n) plt.plot(xx/n - r,scale*binPdf(n,r,xx)/max(binPdf(n,r,xx))); residuals = np.zeros(np.shape(tceGrid)); rateGrid = np.zeros(np.shape(tceGrid)); for p in range(NPeriod): for m in range(NMes): rateGrid[(p,m)] = funcModels.rateModel(cellX[(p,m)]+dx/2, cellY[(p,m)]+dy/2, fitTheta, model); if tceGrid[(p,m)] > 0: residuals[(p,m)] = fpGrid[(p,m)]/tceGrid[(p,m)] - rateGrid[(p,m)] rateFlat = rateGrid.flatten(); residualsFlat = residuals.flatten(); # group residuals by rate plt.figure(figsize=(15,5)); histVals = plt.hist(residualsFlat[(rateFlat>0.9)&(nTce>0)], 100); tcePctiles = np.percentile(nTce[(rateFlat>0.9)&(nTce>0)], [10, 50, 90], axis=0); plot_norm_bin(np.mean(nTce[(rateFlat>0.9)&(nTce>0)]), np.median(rateFlat), np.max(histVals[0])) plot_norm_bin(tcePctiles[0], np.median(rateFlat), np.max(histVals[0])) plot_norm_bin(tcePctiles[1], np.median(rateFlat), np.max(histVals[0])) plot_norm_bin(tcePctiles[2], np.median(rateFlat), np.max(histVals[0])) plt.grid(linestyle = ':'); ``` ![png](output_48_0.png) ```python np.median(rateFlat) ``` 0.9979351643206406 ```python from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure(figsize=plt.figaspect(0.3)); ax = fig.add_subplot(1, 3, 1, projection='3d') Z = funcModels.rateModel(cellX, cellY, fitTheta, model); fpFracPlot = fpFrac fpFrac[fpFrac == 0] = 1 surf = ax.plot_surface(cellPeriod, cellMes, Z, alpha = 0.5); scat = ax.scatter(cellPeriod, cellMes, fpFrac, c='r', marker = '.'); plt.xlabel("period"); plt.ylabel("MES"); ax.view_init(0,0) ax = fig.add_subplot(1, 3, 2, projection='3d') surf = ax.plot_surface(cellPeriod, cellMes, Z, alpha = 0.5); scat = ax.scatter(cellPeriod, cellMes, fpFrac, c='r', marker = '.'); plt.xlabel("period"); plt.ylabel("MES"); ax.view_init(0,-90) plt.title("Effectiveness"); ax = fig.add_subplot(1, 3, 3, projection='3d') surf = ax.plot_surface(cellPeriod, cellMes, Z, alpha = 0.5); scat = ax.scatter(cellPeriod, cellMes, fpFrac, c='r', marker = '.'); plt.xlabel("period"); plt.ylabel("MES"); fig, ax = plt.subplots(figsize=(5,5)); CS = ax.contour(cellPeriod, cellMes, Z); ax.clabel(CS, inline=1, fontsize=10); plt.xlabel("period"); plt.ylabel("MES"); ``` ![png](output_50_0.png) ![png](output_50_1.png) ```python funcModels.normalizeRange(372., 8., [periodMin, periodMax], [mesMin, mesMax]) ``` (0.5854545454545454, 0.043478260869565216) ```python fig, ax = plt.subplots(figsize=(15,10)); Z = funcModels.rateModel(cellX, cellY, fitTheta, model); CS = ax.contour(cellPeriod, cellMes, Z, colors='k'); ax.clabel(CS, inline=1, fontsize=18); scf = ax.scatter(cellPeriod[tceGrid>0], cellMes[tceGrid>0], cmap="cividis", c=fpFrac[tceGrid>0], s=5*tceGrid[tceGrid>0], alpha = 0.5); plt.xlabel("period", fontSize = 24); plt.ylabel("MES", fontSize = 24); cbh = plt.colorbar(scf); cbh.ax.set_ylabel("Measured Rate", fontSize = 24); plt.tick_params(labelsize = 16) plt.savefig("fpEffContours.pdf",bbox_inches='tight') plt.title("Vetting Effectiveness. Size of marker = # of TCEs in cell"); ``` ![png](output_52_0.png) ```python fig = plt.figure(figsize=plt.figaspect(0.3)); Z0 = funcModels.rateModel(cellX, cellY, fitTheta, model); Z = (1-Z0)/Z0; ax = fig.add_subplot(1, 3, 1, projection='3d') surf = ax.plot_surface(cellPeriod, cellMes, Z, alpha = 0.5); plt.xlabel("period"); plt.ylabel("MES"); ax.view_init(0,0) ax = fig.add_subplot(1, 3, 2, projection='3d') surf = ax.plot_surface(cellPeriod, cellMes, Z, alpha = 0.5); plt.xlabel("period"); plt.ylabel("MES"); ax.view_init(0,-90) plt.title("(1-E)/E"); ax = fig.add_subplot(1, 3, 3, projection='3d') surf = ax.plot_surface(cellPeriod, cellMes, Z, alpha = 0.5); plt.xlabel("period"); plt.ylabel("MES"); ``` ![png](output_53_0.png) Fit $F_{\mathrm{obsFP}}$. ```python aic = 2*len(fitTheta) - 2*lnBinlike(fitTheta, tceData, model) aic ``` 214.3854675031165 ```python maxLikelihoodAic = 2*len(maxLikelihoodResult) - 2*lnBinlike(maxLikelihoodResult, tceData, model) maxLikelihoodAic ``` 561.4227834857621 ```python l = np.zeros(np.shape(samples)[0]) aicDist = np.zeros(np.shape(samples)[0]) progress = FloatProgress(min=0, max=samples.shape[0]) display(progress) for i in range(np.shape(samples)[0]): l[i] = lnBinprob(samples[i,:], tceData, model) aicDist[i] = 2*len(samples[i,:]) - 2*lnBinlike(samples[i,:], tceData, model) progress.value += 1 ``` FloatProgress(value=0.0, max=500000.0) ```python plt.hist(aicDist, 100); ``` ![png](output_58_0.png) ```python minAic = min(aicDist) ``` ```python plt.hist(np.exp(l - np.median(l)), 100); ``` ![png](output_60_0.png) ```python np.median(l) ``` -103.84762823857324 ```python from skmonaco import mcquad lbnds = np.empty([np.shape(samples)[1]]) ubnds = np.empty([np.shape(samples)[1]]) for i in range(len(lbnds)): lbnds[i] = np.min(samples[:,i]) ubnds[i] = np.max(samples[:,i]) regularizationOffset = np.median(l) def linBinProbInt(theta): return np.exp(lnBinprob(theta, tceData, model) - regularizationOffset) BF, BFerror = mcquad(linBinProbInt, xl=lbnds,xu=ubnds, npoints=1e7,nprocs=8 ) print("BF = {:.3e} +/- {:.3e}").format(BF,BFerror) ``` BF = 1.924e-02 +/- 2.567e-04 ```python import os.path import pickle fname = "fpEffectivenessTable.pkl" if os.path.isfile(fname): modelComparisonTable = pd.read_pickle(fname) else: modelComparisonTable = pd.DataFrame({"Model": ["rotatedLogisticX0", "rotatedLogisticX02", "constant", "dualBrokenPowerLaw", "gaussian", "rotatedLogisticX0xlogisticY0", "rotatedLogisticX0+gaussian", "rotatedLogisticY", "rotatedLogisticYXLogisticY", "logisticY", "rotatedLogisticYXFixedLogisticY"], "medianMCMCAIC": [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], "minMCMCAIC": [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], "maxLikelihoodAIC": [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], "MedianLogPost": [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], "IntegralPost": [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], "IntegralPostErr": [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], "medianMCMCTheta": [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]], "maxLikelihoodTheta": [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]], "periodRange": [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]], "mesRange": [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]]}, columns=["Model","BayesFactor","BayesFactorError","AICRelativeProb", "medianMCMCAIC","minMCMCAIC","maxLikelihoodAIC","IntegralPost", "IntegralPostErr","MedianLogPost","medianMCMCTheta", "maxLikelihoodTheta","periodRange","mesRange"]) modelComparisonTable['IntegralPost'] = modelComparisonTable['IntegralPost'].map('{:,.3e}'.format) modelComparisonTable['IntegralPostErr'] = modelComparisonTable['IntegralPostErr'].map('{:,.3e}'.format) ``` ```python mctIndex = np.where(modelComparisonTable["Model"].isin([model]))[0][0] print(mctIndex) modelComparisonTable["medianMCMCAIC"][mctIndex] = aic; modelComparisonTable["minMCMCAIC"][mctIndex] = minAic; modelComparisonTable["maxLikelihoodAIC"][mctIndex] = maxLikelihoodAic; modelComparisonTable["MedianLogPost"][mctIndex] = regularizationOffset; modelComparisonTable["IntegralPost"][mctIndex] = BF; modelComparisonTable["IntegralPostErr"][mctIndex] = BFerror; modelComparisonTable["medianMCMCTheta"][mctIndex] = fitTheta; modelComparisonTable["maxLikelihoodTheta"][mctIndex] = maxLikelihoodResult; modelComparisonTable["periodRange"][mctIndex] = [periodMin, periodMax]; modelComparisonTable["mesRange"][mctIndex] = [mesMin, mesMax]; ``` 0 /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy This is separate from the ipykernel package so we can avoid doing imports until /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy after removing the cwd from sys.path. /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy """ /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:6: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:7: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy import sys /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:9: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy if __name__ == '__main__': /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:10: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy # Remove the CWD from sys.path while we load stuff. /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:11: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy # This is added back by InteractiveShellApp.init_path() /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/ipykernel_launcher.py:12: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy if sys.path[0] == '': ```python modelToCompareIndex = 0 modelComparisonTable["AICRelativeProb"] = 0. minAic = np.min(modelComparisonTable["medianMCMCAIC"][modelToCompareIndex]) for i in range(len(modelComparisonTable)): modelComparisonTable["AICRelativeProb"].iloc[i] = np.exp((minAic - modelComparisonTable["medianMCMCAIC"].iloc[i])/2.) ``` /Users/steve/anaconda3/envs/py2/lib/python2.7/site-packages/pandas/core/indexing.py:189: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self._setitem_with_indexer(indexer, value) ```python modelComparisonTable["BayesFactor"] = 0. c1 = modelComparisonTable["MedianLogPost"].iloc[modelToCompareIndex] i1 = np.double(modelComparisonTable["IntegralPost"].iloc[modelToCompareIndex]) for i in range(len(modelComparisonTable)): c2 = modelComparisonTable["MedianLogPost"].iloc[i] modelComparisonTable["BayesFactor"].iloc[i] = np.exp(c2 - c1)*np.double(modelComparisonTable["IntegralPost"].iloc[i])/i1 ``` ```python modelComparisonTable["BayesFactorError"] = 0. B = np.double(modelComparisonTable["IntegralPost"].iloc[modelToCompareIndex]) sB = np.double(modelComparisonTable["IntegralPostErr"].iloc[modelToCompareIndex]) c1 = modelComparisonTable["MedianLogPost"].iloc[modelToCompareIndex] for i in range(len(modelComparisonTable)): c2 = modelComparisonTable["MedianLogPost"].iloc[i] f = np.double(modelComparisonTable["BayesFactor"].iloc[i]) A = np.exp(c2 - c1)*np.double(modelComparisonTable["IntegralPost"].iloc[i]) sA = np.exp(c2 - c1)*np.double(modelComparisonTable["IntegralPostErr"].iloc[i]) modelComparisonTable["BayesFactorError"].iloc[i] = f*np.sqrt((sA/A)**2 + (sB/B)**2) ``` ```python modelComparisonTable ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Model</th> <th>BayesFactor</th> <th>BayesFactorError</th> <th>AICRelativeProb</th> <th>medianMCMCAIC</th> <th>minMCMCAIC</th> <th>maxLikelihoodAIC</th> <th>IntegralPost</th> <th>IntegralPostErr</th> <th>MedianLogPost</th> <th>medianMCMCTheta</th> <th>maxLikelihoodTheta</th> <th>periodRange</th> <th>mesRange</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>rotatedLogisticX0</td> <td>1.000000e+00</td> <td>1.887275e-02</td> <td>1.000000e+00</td> <td>214.385468</td> <td>214.063072</td> <td>561.422783</td> <td>0.0192384</td> <td>0.000256737</td> <td>-103.847628</td> <td>[1.1590315150009514, 22.586875946881573, 0.997...</td> <td>[1.2, 9.7715652, 0.99773284, 106.91479715]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>1</th> <td>rotatedLogisticX02</td> <td>7.158796e+03</td> <td>1.696061e+02</td> <td>2.580833e+00</td> <td>212.489243</td> <td>210.934068</td> <td>563.422783</td> <td>28.5536</td> <td>0.558966</td> <td>-102.274164</td> <td>[0.9064792402673865, 76.23615668492818, 232.90...</td> <td>[1.2, 9.7715652, 1.0, 0.99773284, 106.91479715]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>2</th> <td>constant</td> <td>3.411908e-14</td> <td>4.555072e-16</td> <td>6.354745e-13</td> <td>270.554276</td> <td>270.547627</td> <td>952.769116</td> <td>0.00496336</td> <td>1.89621e-06</td> <td>-133.501724</td> <td>[0.9863098402793025]</td> <td>[0.9]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>3</th> <td>dualBrokenPowerLaw</td> <td>1.596757e-13</td> <td>1.300053e-14</td> <td>1.772937e-08</td> <td>250.081554</td> <td>244.080387</td> <td>257.130362</td> <td>2.60543e-09</td> <td>2.09261e-10</td> <td>-117.498440</td> <td>[0.9577821055888789, 0.03169988663140294, -0.0...</td> <td>[0.96811698, 0.01257312, -0.00171099, -0.01, 0...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>4</th> <td>gaussian</td> <td>3.185662e-08</td> <td>2.238177e-09</td> <td>7.873621e-08</td> <td>247.099793</td> <td>243.483168</td> <td>289.760105</td> <td>0.00106318</td> <td>7.33368e-05</td> <td>-118.214005</td> <td>[0.8348500163634114, 0.34690035174257505, 2.40...</td> <td>[0.62, 0.04, 1, 1, -0.01, 0.991039169]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>5</th> <td>rotatedLogisticX0xlogisticY0</td> <td>6.221789e+04</td> <td>1.005328e+03</td> <td>4.839737e-02</td> <td>220.442087</td> <td>220.075061</td> <td>226.277773</td> <td>1181.05</td> <td>10.7597</td> <td>-103.834241</td> <td>[1.48299627332654, -0.16058180049364862, 5083....</td> <td>[1.50565457, -0.2807610841873724, 4927.18937, ...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>6</th> <td>rotatedLogisticX0+gaussian</td> <td>4.745257e-03</td> <td>9.964642e-04</td> <td>1.086556e-03</td> <td>228.034952</td> <td>216.740238</td> <td>39916.019257</td> <td>0.00012872</td> <td>2.69754e-05</td> <td>-104.191214</td> <td>[1.1670844258369066, 21.663865986386142, 0.998...</td> <td>[0.5, 8, 1.0, 107, 0.5, 0.4, 0.2, 0.2, -0.1]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>7</th> <td>rotatedLogisticY</td> <td>5.227172e-01</td> <td>2.352870e-02</td> <td>4.928830e-01</td> <td>215.800434</td> <td>212.356565</td> <td>214.993954</td> <td>0.00693595</td> <td>0.000298166</td> <td>-103.476154</td> <td>[-0.026718794826597985, 29.48200354472572, -10...</td> <td>[-0.03145787355104775, 28.04931565722331, -9.6...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>8</th> <td>rotatedLogisticYXLogisticY</td> <td>4.930810e+01</td> <td>3.158154e+00</td> <td>4.469880e-02</td> <td>220.601085</td> <td>216.532174</td> <td>248.276826</td> <td>0.7921</td> <td>0.0496201</td> <td>-103.667320</td> <td>[-0.027368879336427634, 29.635418525748943, -0...</td> <td>[0.04944521, 23.31556305, -0.0263785585, 20, -...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>9</th> <td>logisticY</td> <td>2.512121e-07</td> <td>3.803490e-09</td> <td>4.694144e-06</td> <td>238.923857</td> <td>238.451145</td> <td>305.538734</td> <td>0.00056506</td> <td>4.04111e-06</td> <td>-115.516866</td> <td>[-0.005878011222137505, 43.02592867432009, 0.0...</td> <td>[-0.0263785585, 20.0, 0.02, 0.98]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>10</th> <td>rotatedLogisticYXFixedLogisticY</td> <td>3.596075e-01</td> <td>8.401393e-02</td> <td>4.582628e-01</td> <td>215.946092</td> <td>212.577535</td> <td>663.259280</td> <td>0.00560281</td> <td>0.00130683</td> <td>-103.636732</td> <td>[-0.022752166772306688, 29.66903143779296, -11...</td> <td>[0.5, 2, 0.0, 0.1, 0.9]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> </tbody> </table> </div> ```python modelComparisonTable.to_pickle(fname) ``` ```python tt = pd.read_pickle(fname) tt ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Model</th> <th>BayesFactor</th> <th>BayesFactorError</th> <th>AICRelativeProb</th> <th>medianMCMCAIC</th> <th>minMCMCAIC</th> <th>maxLikelihoodAIC</th> <th>IntegralPost</th> <th>IntegralPostErr</th> <th>MedianLogPost</th> <th>medianMCMCTheta</th> <th>maxLikelihoodTheta</th> <th>periodRange</th> <th>mesRange</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>rotatedLogisticX0</td> <td>1.000000e+00</td> <td>1.887275e-02</td> <td>1.000000e+00</td> <td>214.385468</td> <td>214.063072</td> <td>561.422783</td> <td>0.0192384</td> <td>0.000256737</td> <td>-103.847628</td> <td>[1.1590315150009514, 22.586875946881573, 0.997...</td> <td>[1.2, 9.7715652, 0.99773284, 106.91479715]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>1</th> <td>rotatedLogisticX02</td> <td>7.158796e+03</td> <td>1.696061e+02</td> <td>2.580833e+00</td> <td>212.489243</td> <td>210.934068</td> <td>563.422783</td> <td>28.5536</td> <td>0.558966</td> <td>-102.274164</td> <td>[0.9064792402673865, 76.23615668492818, 232.90...</td> <td>[1.2, 9.7715652, 1.0, 0.99773284, 106.91479715]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>2</th> <td>constant</td> <td>3.411908e-14</td> <td>4.555072e-16</td> <td>6.354745e-13</td> <td>270.554276</td> <td>270.547627</td> <td>952.769116</td> <td>0.00496336</td> <td>1.89621e-06</td> <td>-133.501724</td> <td>[0.9863098402793025]</td> <td>[0.9]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>3</th> <td>dualBrokenPowerLaw</td> <td>1.596757e-13</td> <td>1.300053e-14</td> <td>1.772937e-08</td> <td>250.081554</td> <td>244.080387</td> <td>257.130362</td> <td>2.60543e-09</td> <td>2.09261e-10</td> <td>-117.498440</td> <td>[0.9577821055888789, 0.03169988663140294, -0.0...</td> <td>[0.96811698, 0.01257312, -0.00171099, -0.01, 0...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>4</th> <td>gaussian</td> <td>3.185662e-08</td> <td>2.238177e-09</td> <td>7.873621e-08</td> <td>247.099793</td> <td>243.483168</td> <td>289.760105</td> <td>0.00106318</td> <td>7.33368e-05</td> <td>-118.214005</td> <td>[0.8348500163634114, 0.34690035174257505, 2.40...</td> <td>[0.62, 0.04, 1, 1, -0.01, 0.991039169]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>5</th> <td>rotatedLogisticX0xlogisticY0</td> <td>6.221789e+04</td> <td>1.005328e+03</td> <td>4.839737e-02</td> <td>220.442087</td> <td>220.075061</td> <td>226.277773</td> <td>1181.05</td> <td>10.7597</td> <td>-103.834241</td> <td>[1.48299627332654, -0.16058180049364862, 5083....</td> <td>[1.50565457, -0.2807610841873724, 4927.18937, ...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>6</th> <td>rotatedLogisticX0+gaussian</td> <td>4.745257e-03</td> <td>9.964642e-04</td> <td>1.086556e-03</td> <td>228.034952</td> <td>216.740238</td> <td>39916.019257</td> <td>0.00012872</td> <td>2.69754e-05</td> <td>-104.191214</td> <td>[1.1670844258369066, 21.663865986386142, 0.998...</td> <td>[0.5, 8, 1.0, 107, 0.5, 0.4, 0.2, 0.2, -0.1]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>7</th> <td>rotatedLogisticY</td> <td>5.227172e-01</td> <td>2.352870e-02</td> <td>4.928830e-01</td> <td>215.800434</td> <td>212.356565</td> <td>214.993954</td> <td>0.00693595</td> <td>0.000298166</td> <td>-103.476154</td> <td>[-0.026718794826597985, 29.48200354472572, -10...</td> <td>[-0.03145787355104775, 28.04931565722331, -9.6...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>8</th> <td>rotatedLogisticYXLogisticY</td> <td>4.930810e+01</td> <td>3.158154e+00</td> <td>4.469880e-02</td> <td>220.601085</td> <td>216.532174</td> <td>248.276826</td> <td>0.7921</td> <td>0.0496201</td> <td>-103.667320</td> <td>[-0.027368879336427634, 29.635418525748943, -0...</td> <td>[0.04944521, 23.31556305, -0.0263785585, 20, -...</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>9</th> <td>logisticY</td> <td>2.512121e-07</td> <td>3.803490e-09</td> <td>4.694144e-06</td> <td>238.923857</td> <td>238.451145</td> <td>305.538734</td> <td>0.00056506</td> <td>4.04111e-06</td> <td>-115.516866</td> <td>[-0.005878011222137505, 43.02592867432009, 0.0...</td> <td>[-0.0263785585, 20.0, 0.02, 0.98]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> <tr> <th>10</th> <td>rotatedLogisticYXFixedLogisticY</td> <td>3.596075e-01</td> <td>8.401393e-02</td> <td>4.582628e-01</td> <td>215.946092</td> <td>212.577535</td> <td>663.259280</td> <td>0.00560281</td> <td>0.00130683</td> <td>-103.636732</td> <td>[-0.022752166772306688, 29.66903143779296, -11...</td> <td>[0.5, 2, 0.0, 0.1, 0.9]</td> <td>[50, 600]</td> <td>[7, 30]</td> </tr> </tbody> </table> </div> ```javascript %%javascript IPython.notebook.save_notebook() ``` <IPython.core.display.Javascript object> ```bash %%bash -s "$model" jupyter nbconvert --to html binomialFPEffectiveness.ipynb mv binomialFPEffectiveness.html htmlArchive/binomialFPEffectiveness_$1.html ``` [NbConvertApp] Converting notebook binomialFPEffectiveness.ipynb to html [NbConvertApp] Writing 1765114 bytes to binomialFPEffectiveness.html ```python ``` ```python plt.hist(spSyntheticPcs["Score"]) ``` (array([ 7., 10., 12., 16., 6., 10., 2., 0., 7., 3.]), array([0.051 , 0.1382, 0.2254, 0.3126, 0.3998, 0.487 , 0.5742, 0.6614, 0.7486, 0.8358, 0.923 ]), <a list of 10 Patch objects>) ![png](output_74_1.png) ```python np.max(spSyntheticPcs["Score"]) ``` 0.923 ```python ```
stevepurREPO_NAMEDR25-occurrence-publicPATH_START.@DR25-occurrence-public_extracted@DR25-occurrence-public-main@GKbaseline@binomialFPEffectiveness.ipynb@.PATH_END.py
{ "filename": "_xpad.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattermap/marker/colorbar/_xpad.py", "type": "Python" }
import _plotly_utils.basevalidators class XpadValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="xpad", parent_name="scattermap.marker.colorbar", **kwargs ): super(XpadValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), min=kwargs.pop("min", 0), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattermap@marker@colorbar@_xpad.py@.PATH_END.py
{ "filename": "SkyBrightness.py", "repo_name": "ZwickyTransientFacility/ztf_sim", "repo_path": "ztf_sim_extracted/ztf_sim-master/ztf_sim/SkyBrightness.py", "type": "Python" }
"""Sky brightness model.""" import sklearn from sklearn import model_selection, ensemble, preprocessing, pipeline from sklearn import neighbors, svm, linear_model from sklearn_pandas import DataFrameMapper import joblib import xgboost as xgb import pandas as pd import numpy as np from .constants import FILTER_NAME_TO_ID, BASE_DIR class SkyBrightness(object): def __init__(self): self.clf_r = joblib.load(BASE_DIR + '../data/sky_model/sky_model_r.pkl') self.clf_g = joblib.load(BASE_DIR + '../data/sky_model/sky_model_g.pkl') self.clf_i = joblib.load(BASE_DIR + '../data/sky_model/sky_model_i.pkl') def predict(self, df): """df is a dataframe with columns: mooonillf: 0-1 moonalt: degrees moon_dist: degrees azimuth: degrees altitude: degrees sunalt: degrees filterkey: 1, 2, 3""" filter_ids = df['filter_id'].unique() assert(np.sum(filter_ids > 3) == 0) sky = pd.Series(np.nan, index=df.index, name='sky_brightness') wg = (df['filter_id'] == FILTER_NAME_TO_ID['g']) if np.sum(wg): sky[wg] = self.clf_g.predict(df[wg]) wr = (df['filter_id'] == FILTER_NAME_TO_ID['r']) if np.sum(wr): sky[wr] = self.clf_r.predict(df[wr]) wi = (df['filter_id'] == FILTER_NAME_TO_ID['i']) if np.sum(wi): sky[wi] = self.clf_i.predict(df[wi]) return sky class FakeSkyBrightness(object): def __init__(self): pass def predict(self, df): y = np.ones(len(df)) * 20. return pd.Series(y, index=df.index, name='sky_brightness') def train_sky_model(filter_name='r', df=None): # PTF used 4 for i-band filterid_map = {'r': 2, 'g': 1, 'i': 4} if df is None: df = pd.read_csv(BASE_DIR + '../data/ptf-iptf_diq.csv.gz') # note that this is by pid, so there are multiple entries per image... df = df[df['filterkey'] == filterid_map[filter_name]].copy() # IPAC stores negative moonillf, but astroplan.moon_illumination does not df.loc[:, 'moonillf'] = np.abs(df['moonillf']) # returns dataframes! X_train, X_test, y_train, y_test = model_selection.train_test_split( df, df['sky_brightness'], test_size=0.2) # don't really need to standardize for RF, but preprocessing is nice # preprocessing through sklearn_pandas raises a deprecation warning # from sklearn, so skip it. mapper = DataFrameMapper([ (['moonillf'], preprocessing.StandardScaler()), (['moonalt'], preprocessing.StandardScaler()), (['moon_dist'], preprocessing.StandardScaler()), (['azimuth'], preprocessing.StandardScaler()), (['altitude'], preprocessing.StandardScaler()), (['sunalt'], preprocessing.StandardScaler())]) #('filterkey', None)]) clf = pipeline.Pipeline([ ('featurize', mapper), ('xgb', xgb.XGBRegressor())]) #('svr', svm.SVR(kernel='poly',degree=2))]) #('knr', neighbors.KNeighborsRegressor(n_neighbors=15, weights='distance', algorithm='auto'))]) #('lm', linear_model.BayesianRidge())]) #('rf', ensemble.RandomForestRegressor(n_jobs=-1))]) clf.fit(X_train, y_train.values.reshape(-1, 1)) print(clf.score(X_test, y_test.values.reshape(-1, 1))) joblib.dump(clf, BASE_DIR + '../data/sky_model/sky_model_{}.pkl'.format(filter_name)) return clf
ZwickyTransientFacilityREPO_NAMEztf_simPATH_START.@ztf_sim_extracted@ztf_sim-master@ztf_sim@SkyBrightness.py@.PATH_END.py
{ "filename": "core.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/matplotlib/py2/matplotlib/style/core.py", "type": "Python" }
from __future__ import absolute_import, division, print_function import six """ Core functions and attributes for the matplotlib style library: ``use`` Select style sheet to override the current matplotlib settings. ``context`` Context manager to use a style sheet temporarily. ``available`` List available style sheets. ``library`` A dictionary of style names and matplotlib settings. """ import os import re import contextlib import warnings import matplotlib as mpl from matplotlib import rc_params_from_file, rcParamsDefault __all__ = ['use', 'context', 'available', 'library', 'reload_library'] BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') # Users may want multiple library paths, so store a list of paths. USER_LIBRARY_PATHS = [os.path.join(mpl._get_configdir(), 'stylelib')] STYLE_EXTENSION = 'mplstyle' STYLE_FILE_PATTERN = re.compile(r'([\S]+).%s$' % STYLE_EXTENSION) # A list of rcParams that should not be applied from styles STYLE_BLACKLIST = { 'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.address', 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', 'toolbar', 'timezone', 'datapath', 'figure.max_open_warning', 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'} def _remove_blacklisted_style_params(d, warn=True): o = {} for key, val in d.items(): if key in STYLE_BLACKLIST: if warn: warnings.warn( "Style includes a parameter, '{0}', that is not related " "to style. Ignoring".format(key)) else: o[key] = val return o def is_style_file(filename): """Return True if the filename looks like a style file.""" return STYLE_FILE_PATTERN.match(filename) is not None def _apply_style(d, warn=True): mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn)) def use(style): """Use matplotlib style settings from a style specification. The style name of 'default' is reserved for reverting back to the default style settings. Parameters ---------- style : str, dict, or list A style specification. Valid options are: +------+-------------------------------------------------------------+ | str | The name of a style or a path/URL to a style file. For a | | | list of available style names, see `style.available`. | +------+-------------------------------------------------------------+ | dict | Dictionary with valid key/value pairs for | | | `matplotlib.rcParams`. | +------+-------------------------------------------------------------+ | list | A list of style specifiers (str or dict) applied from first | | | to last in the list. | +------+-------------------------------------------------------------+ """ style_alias = {'mpl20': 'default', 'mpl15': 'classic'} if isinstance(style, six.string_types) or hasattr(style, 'keys'): # If name is a single str or dict, make it a single element list. styles = [style] else: styles = style styles = (style_alias.get(s, s) if isinstance(s, six.string_types) else s for s in styles) for style in styles: if not isinstance(style, six.string_types): _apply_style(style) elif style == 'default': _apply_style(rcParamsDefault, warn=False) elif style in library: _apply_style(library[style]) else: try: rc = rc_params_from_file(style, use_default_template=False) _apply_style(rc) except IOError: raise IOError( "{!r} not found in the style library and input is not a " "valid URL or path; see `style.available` for list of " "available styles".format(style)) @contextlib.contextmanager def context(style, after_reset=False): """Context manager for using style settings temporarily. Parameters ---------- style : str, dict, or list A style specification. Valid options are: +------+-------------------------------------------------------------+ | str | The name of a style or a path/URL to a style file. For a | | | list of available style names, see `style.available`. | +------+-------------------------------------------------------------+ | dict | Dictionary with valid key/value pairs for | | | `matplotlib.rcParams`. | +------+-------------------------------------------------------------+ | list | A list of style specifiers (str or dict) applied from first | | | to last in the list. | +------+-------------------------------------------------------------+ after_reset : bool If True, apply style after resetting settings to their defaults; otherwise, apply style on top of the current settings. """ initial_settings = mpl.rcParams.copy() if after_reset: mpl.rcdefaults() try: use(style) except: # Restore original settings before raising errors during the update. mpl.rcParams.update(initial_settings) raise else: yield finally: mpl.rcParams.update(initial_settings) def load_base_library(): """Load style library defined in this package.""" library = dict() library.update(read_style_directory(BASE_LIBRARY_PATH)) return library def iter_user_libraries(): for stylelib_path in USER_LIBRARY_PATHS: stylelib_path = os.path.expanduser(stylelib_path) if os.path.exists(stylelib_path) and os.path.isdir(stylelib_path): yield stylelib_path def update_user_library(library): """Update style library with user-defined rc files""" for stylelib_path in iter_user_libraries(): styles = read_style_directory(stylelib_path) update_nested_dict(library, styles) return library def iter_style_files(style_dir): """Yield file path and name of styles in the given directory.""" for path in os.listdir(style_dir): filename = os.path.basename(path) if is_style_file(filename): match = STYLE_FILE_PATTERN.match(filename) path = os.path.abspath(os.path.join(style_dir, path)) yield path, match.groups()[0] def read_style_directory(style_dir): """Return dictionary of styles defined in `style_dir`.""" styles = dict() for path, name in iter_style_files(style_dir): with warnings.catch_warnings(record=True) as warns: styles[name] = rc_params_from_file(path, use_default_template=False) for w in warns: message = 'In %s: %s' % (path, w.message) warnings.warn(message) return styles def update_nested_dict(main_dict, new_dict): """Update nested dict (only level of nesting) with new values. Unlike dict.update, this assumes that the values of the parent dict are dicts (or dict-like), so you shouldn't replace the nested dict if it already exists. Instead you should update the sub-dict. """ # update named styles specified by user for name, rc_dict in six.iteritems(new_dict): if name in main_dict: main_dict[name].update(rc_dict) else: main_dict[name] = rc_dict return main_dict # Load style library # ================== _base_library = load_base_library() library = None available = [] def reload_library(): """Reload style library.""" global library available[:] = library = update_user_library(_base_library) reload_library()
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@matplotlib@py2@matplotlib@style@core.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "nanograv/enterprise_extensions", "repo_path": "enterprise_extensions_extracted/enterprise_extensions-master/README.md", "type": "Markdown" }
# enterprise_extensions A set of extensions, utilities, and scripts for the [enterprise](https://github.com/nanograv/enterprise) PTA analysis code. ## installation `enterprise_extensions` is not yet available on the Python Package Index (PyPI), but you can still install it directly from GitHub using `pip`. To install the __most recent__ version do: ``` pip install git+https://github.com/nanograv/enterprise_extensions@master ``` You can also install it by cloning the repo and running `pip install .` in the `enterprise_extensions` directory. ## citation Did you use `enterprise_extensions`? Remember to cite it as: >Taylor, S. R., Baker, P. T., Hazboun, J. S., Simon, J., & Vigeland, S. J. (2021). enterprise_extensions v2.4.3. https://github.com/nanograv/enterprise_extensions ```latex @misc{enterprise, author = {Stephen R. Taylor and Paul T. Baker and Jeffrey S. Hazboun and Joseph Simon and Sarah J. Vigeland}, title = {enterprise_extensions}, year = {2021}, url = {https://github.com/nanograv/enterprise_extensions}, note = {v2.4.3} } ``` <!-- howpublished = {Zenodo}, doi = {10.5281/zenodo.XXXXXXX}, -->
nanogravREPO_NAMEenterprise_extensionsPATH_START.@enterprise_extensions_extracted@enterprise_extensions-master@README.md@.PATH_END.py
{ "filename": "wfAlgorithmFactory.py", "repo_name": "lsst-ts/ts_wep", "repo_path": "ts_wep_extracted/ts_wep-main/python/lsst/ts/wep/estimation/wfAlgorithmFactory.py", "type": "Python" }
# This file is part of ts_wep. # # Developed for the LSST Telescope and Site Systems. # This product includes software developed by the LSST Project # (https://www.lsst.org). # See the COPYRIGHT file at the top-level directory of this distribution # for details of code ownership. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __all__ = ["WfAlgorithmFactory"] from typing import Union from lsst.ts.wep.estimation.danish import DanishAlgorithm from lsst.ts.wep.estimation.tie import TieAlgorithm from lsst.ts.wep.estimation.wfAlgorithm import WfAlgorithm from lsst.ts.wep.utils import WfAlgorithmName, configClass class WfAlgorithmFactory: """Factory for loading different wavefront estimation algorithms.""" @staticmethod def createWfAlgorithm( algoName: Union[WfAlgorithmName, str], algoConfig: Union[dict, WfAlgorithm, None] = None, ): """Return a configured WfAlgorithm. Parameters ---------- algoName : WfAlgorithmName or str A WfAlgorithmName enum or the corresponding string, indicating which WfAlgorithm to use. algoConfig : str or dict or WfAlgorithm, optional Algorithm configuration. If a string, it is assumed this points to a config file, which is used to configure the algorithm. If the path begins with "policy:", then it is assumed the path is relative to the policy directory. If a dictionary, it is assumed to hold keywords for configuration. If a WfAlgorithm object, that object is just used. If None, the algorithm defaults are used. (the default is None) """ # Convert to enum algoName = WfAlgorithmName(algoName) # Return the configured algorithm if algoName == WfAlgorithmName.TIE: return configClass(algoConfig, TieAlgorithm) elif algoName == WfAlgorithmName.Danish: return configClass(algoConfig, DanishAlgorithm) else: raise ValueError(f"{algoName} not supported.")
lsst-tsREPO_NAMEts_wepPATH_START.@ts_wep_extracted@ts_wep-main@python@lsst@ts@wep@estimation@wfAlgorithmFactory.py@.PATH_END.py
{ "filename": "_tickmode.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/histogram2dcontour/colorbar/_tickmode.py", "type": "Python" }
import _plotly_utils.basevalidators class TickmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="tickmode", parent_name="histogram2dcontour.colorbar", **kwargs ): super(TickmodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), implied_edits=kwargs.pop("implied_edits", {}), role=kwargs.pop("role", "info"), values=kwargs.pop("values", ["auto", "linear", "array"]), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@histogram2dcontour@colorbar@_tickmode.py@.PATH_END.py
{ "filename": "numpyro_ext.py", "repo_name": "markfortune/luas", "repo_path": "luas_extracted/luas-main/src/luas/numpyro_ext.py", "type": "Python" }
import numpyro.distributions as dist from numpyro.distributions.util import promote_shapes, validate_sample from jax import lax __all__ = [ "LuasNumPyro", ] class LuasNumPyro(dist.Distribution): """Custom ``NumPyro`` distribution which allows a ``luas.GPClass.GP`` object to be used with ``NumPyro``. Args: gp (object): The ``GP`` object used for log likelihood calculations. var_dict (PyTree): A PyTree of parameter values for calculating the log likelihood likelihood_fn (Callable, optional): Can specify a different log likelihood function than the default of ``GP.logP`` i.e. ``GP.logP_hessianable`` may be used which is more numerically stable if performing hessian/second order derivative calculations. """ def __init__( self, gp=None, var_dict=None, likelihood_fn=None, validate_args=None, ): self.gp = gp self.p = var_dict # If using NumPyro functionality which makes use of the hessian of the log likelihood # (i.e. numpyro.infer.autoguide.AutoLaplaceApproximation) then might be useful to set # likelihood_fn = gp.logP_hessianable as the default log likelihood is faster but not # as numerically stable for second order derivatives. if likelihood_fn is None: self.logP_fn = self.gp.logP else: self.logP_fn = likelihood_fn super().__init__( batch_shape = (), event_shape = (self.gp.N_l, self.gp.N_t), validate_args=validate_args, ) @dist.util.validate_sample def log_prob(self, Y): return self.logP_fn(self.p, Y) def support(self, Y): return dist.constraints.real(Y)
markfortuneREPO_NAMEluasPATH_START.@luas_extracted@luas-main@src@luas@numpyro_ext.py@.PATH_END.py
{ "filename": "_ygap.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/heatmap/_ygap.py", "type": "Python" }
import _plotly_utils.basevalidators class YgapValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="ygap", parent_name="heatmap", **kwargs): super(YgapValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), min=kwargs.pop("min", 0), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@heatmap@_ygap.py@.PATH_END.py
{ "filename": "CompositeLikelihood.py", "repo_name": "igomezv/simplemc_tests", "repo_path": "simplemc_tests_extracted/simplemc_tests-main/simplemc/likelihoods/CompositeLikelihood.py", "type": "Python" }
from simplemc.likelihoods.BaseLikelihood import BaseLikelihood import scipy as sp class CompositeLikelihood(BaseLikelihood): def __init__(self, llist=[]): """ This thing takes likelihoods and cooks one which is a composite of many. Parameters ---------- llist Returns ------- """ BaseLikelihood.__init__(self, "Composite") self.llist_ = llist def setTheory(self, theory): BaseLikelihood.setTheory(self, theory) for l in self.llist_: l.setTheory(theory) assert(self.theory_ is l.theory_) def addLikelihood(self, like): self.llist_.append(like) if hasattr(self, 'theory_'): like.setTheory(self.theory_) assert(self.theory_ is like.theory_) def addLikelihoods(self, likes): for like in likes: self.addLikelihood(like) def compositeNames(self): return [like.name() for like in self.llist_] def compositeLogLikes(self): return sp.array([like.loglike() for like in self.llist_]) def compositeLogLikes_wprior(self): return sp.array([like.loglike() for like in self.llist_] + [self.theory_.prior_loglike()]) def loglike(self): likes = [like.loglike() for like in self.llist_] return sp.array(likes).sum() # The base is good enough as # Everybody is holding the same reference # def updateParams(self,params): # ok=True # for l in self.llist_: # ok=ok and l.updateParams(params) # return ok
igomezvREPO_NAMEsimplemc_testsPATH_START.@simplemc_tests_extracted@simplemc_tests-main@simplemc@likelihoods@CompositeLikelihood.py@.PATH_END.py
{ "filename": "test_upfirdn.py", "repo_name": "waynebhayes/SpArcFiRe", "repo_path": "SpArcFiRe_extracted/SpArcFiRe-master/scripts/SpArcFiRe-pyvenv/lib/python2.7/site-packages/scipy/signal/tests/test_upfirdn.py", "type": "Python" }
# Code adapted from "upfirdn" python library with permission: # # Copyright (c) 2009, Motorola, Inc # # 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 Motorola 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 OWNER 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. import numpy as np from itertools import product from numpy.testing import assert_equal, assert_allclose from pytest import raises as assert_raises from scipy.signal import upfirdn, firwin, lfilter from scipy.signal._upfirdn import _output_len def upfirdn_naive(x, h, up=1, down=1): """Naive upfirdn processing in Python Note: arg order (x, h) differs to facilitate apply_along_axis use. """ h = np.asarray(h) out = np.zeros(len(x) * up, x.dtype) out[::up] = x out = np.convolve(h, out)[::down][:_output_len(len(h), len(x), up, down)] return out class UpFIRDnCase(object): """Test _UpFIRDn object""" def __init__(self, up, down, h, x_dtype): self.up = up self.down = down self.h = np.atleast_1d(h) self.x_dtype = x_dtype self.rng = np.random.RandomState(17) def __call__(self): # tiny signal self.scrub(np.ones(1, self.x_dtype)) # ones self.scrub(np.ones(10, self.x_dtype)) # ones # randn x = self.rng.randn(10).astype(self.x_dtype) if self.x_dtype in (np.complex64, np.complex128): x += 1j * self.rng.randn(10) self.scrub(x) # ramp self.scrub(np.arange(10).astype(self.x_dtype)) # 3D, random size = (2, 3, 5) x = self.rng.randn(*size).astype(self.x_dtype) if self.x_dtype in (np.complex64, np.complex128): x += 1j * self.rng.randn(*size) for axis in range(len(size)): self.scrub(x, axis=axis) x = x[:, ::2, 1::3].T for axis in range(len(size)): self.scrub(x, axis=axis) def scrub(self, x, axis=-1): yr = np.apply_along_axis(upfirdn_naive, axis, x, self.h, self.up, self.down) y = upfirdn(self.h, x, self.up, self.down, axis=axis) dtypes = (self.h.dtype, x.dtype) if all(d == np.complex64 for d in dtypes): assert_equal(y.dtype, np.complex64) elif np.complex64 in dtypes and np.float32 in dtypes: assert_equal(y.dtype, np.complex64) elif all(d == np.float32 for d in dtypes): assert_equal(y.dtype, np.float32) elif np.complex128 in dtypes or np.complex64 in dtypes: assert_equal(y.dtype, np.complex128) else: assert_equal(y.dtype, np.float64) assert_allclose(yr, y) class TestUpfirdn(object): def test_valid_input(self): assert_raises(ValueError, upfirdn, [1], [1], 1, 0) # up or down < 1 assert_raises(ValueError, upfirdn, [], [1], 1, 1) # h.ndim != 1 assert_raises(ValueError, upfirdn, [[1]], [1], 1, 1) def test_vs_lfilter(self): # Check that up=1.0 gives same answer as lfilter + slicing random_state = np.random.RandomState(17) try_types = (int, np.float32, np.complex64, float, complex) size = 10000 down_factors = [2, 11, 79] for dtype in try_types: x = random_state.randn(size).astype(dtype) if dtype in (np.complex64, np.complex128): x += 1j * random_state.randn(size) for down in down_factors: h = firwin(31, 1. / down, window='hamming') yl = lfilter(h, 1.0, x)[::down] y = upfirdn(h, x, up=1, down=down) assert_allclose(yl, y[:yl.size], atol=1e-7, rtol=1e-7) def test_vs_naive(self): tests = [] try_types = (int, np.float32, np.complex64, float, complex) # Simple combinations of factors for x_dtype, h in product(try_types, (1., 1j)): tests.append(UpFIRDnCase(1, 1, h, x_dtype)) tests.append(UpFIRDnCase(2, 2, h, x_dtype)) tests.append(UpFIRDnCase(3, 2, h, x_dtype)) tests.append(UpFIRDnCase(2, 3, h, x_dtype)) # mixture of big, small, and both directions (net up and net down) # use all combinations of data and filter dtypes factors = (100, 10) # up/down factors cases = product(factors, factors, try_types, try_types) for case in cases: tests += self._random_factors(*case) for test in tests: test() def _random_factors(self, p_max, q_max, h_dtype, x_dtype): n_rep = 3 longest_h = 25 random_state = np.random.RandomState(17) tests = [] for _ in range(n_rep): # Randomize the up/down factors somewhat p_add = q_max if p_max > q_max else 1 q_add = p_max if q_max > p_max else 1 p = random_state.randint(p_max) + p_add q = random_state.randint(q_max) + q_add # Generate random FIR coefficients len_h = random_state.randint(longest_h) + 1 h = np.atleast_1d(random_state.randint(len_h)) h = h.astype(h_dtype) if h_dtype == complex: h += 1j * random_state.randint(len_h) tests.append(UpFIRDnCase(p, q, h, x_dtype)) return tests
waynebhayesREPO_NAMESpArcFiRePATH_START.@SpArcFiRe_extracted@SpArcFiRe-master@scripts@SpArcFiRe-pyvenv@lib@python2.7@site-packages@scipy@signal@tests@test_upfirdn.py@.PATH_END.py
{ "filename": "Composite_model.ipynb", "repo_name": "andreatramacere/jetset", "repo_path": "jetset_extracted/jetset-master/doc/documentation_notebooks/notebooks/composite_model/Composite_model.ipynb", "type": "Jupyter Notebook" }
.. _composite_models: # Composite Models and depending pars ```python from jetset.jet_model import Jet from jetset.plot_sedfit import PlotSED from jetset.model_manager import FitModel ``` Composite models allow combining different models, such as Jet, and templates, including additive or multiplicative models and give the user the possibility to define the functional form of the model composition using simple and intuitive expressions such as: .. code-block:: ipython3 'jet1+jet2'*Franceschini_2008 which sums two jet models SEDs, and applies to both of them the ``Franceschini_2008`` EBL absorption. Building composite models is very easy. Composite models are handled by the :class:`.FitModel` class, as shown by the following examples. ## Combine a Jet model with the EBL model (Multiplicative case) We start by combining a Jet model with the EBL absorption model, i.e. a multiplicative model. First, we define our Jet model ```python from jetset.jet_model import Jet my_jet=Jet(electron_distribution='lppl',name='jet_flaring') ``` ===> setting C threads to 12 Second, we define the EBL model, and we use in this case the ``Franceschini_2008`` model ( read the section :ref:`ebl_model` for more info regarding the EBL models) ```python from jetset.template_2Dmodel import EBLAbsorptionTemplate ebl_franceschini=EBLAbsorptionTemplate.from_name('Franceschini_2008') ``` Now we add the components models to the the :class:`.FitModel` class, using the :class:`.FitModel.add_component()` method ```python composite_model=FitModel(nu_size=500,name='EBL corrected') composite_model.add_component(my_jet) composite_model.add_component(ebl_franceschini) ``` /Users/orion/miniforge3/envs/jetset/lib/python3.10/site-packages/jetset/model_manager.py:158: UserWarning: no cosmology defined, using FlatLambdaCDM(name="Planck13", H0=67.77 km / (Mpc s), Om0=0.30712, Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.048252) warnings.warn(m) the waring message is just telling that you are not passing any specific cosmology model to the `FitModel` class, so it is using a default one ```python composite_model.show_pars() ``` <i>Table length=14</i> <table id="table5747322560-454422" class="table-striped table-bordered table-condensed"> <thead><tr><th>model name</th><th>name</th><th>par type</th><th>units</th><th>val</th><th>phys. bound. min</th><th>phys. bound. max</th><th>log</th><th>frozen</th></tr></thead> <tr><td>jet_flaring</td><td>R</td><td>region_size</td><td>cm</td><td>5.000000e+15</td><td>1.000000e+03</td><td>1.000000e+30</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>R_H</td><td>region_position</td><td>cm</td><td>1.000000e+17</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>B</td><td>magnetic_field</td><td>gauss</td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>NH_cold_to_rel_e</td><td>cold_p_to_rel_e_ratio</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>beam_obj</td><td>beaming</td><td></td><td>1.000000e+01</td><td>1.000000e-04</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>z_cosm</td><td>redshift</td><td></td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gmin</td><td>low-energy-cut-off</td><td>lorentz-factor*</td><td>2.000000e+00</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gmax</td><td>high-energy-cut-off</td><td>lorentz-factor*</td><td>1.000000e+06</td><td>1.000000e+00</td><td>1.000000e+15</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>N</td><td>emitters_density</td><td>1 / cm3</td><td>1.000000e+02</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gamma0_log_parab</td><td>turn-over-energy</td><td>lorentz-factor*</td><td>1.000000e+04</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>s</td><td>LE_spectral_slope</td><td></td><td>2.000000e+00</td><td>-1.000000e+01</td><td>1.000000e+01</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>r</td><td>spectral_curvature</td><td></td><td>4.000000e-01</td><td>-1.500000e+01</td><td>1.500000e+01</td><td>False</td><td>False</td></tr> <tr><td>Franceschini_2008</td><td>scale_factor</td><td>scale_factor</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>Franceschini_2008</td><td>z_cosm</td><td>redshift</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> </table><style>table.dataTable {clear: both; width: auto !important; margin: 0 !important;} .dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate{ display: inline-block; margin-right: 1em; } .paginate_button { margin-right: 5px; } </style> <script> var astropy_sort_num = function(a, b) { var a_num = parseFloat(a); var b_num = parseFloat(b); if (isNaN(a_num) && isNaN(b_num)) return ((a < b) ? -1 : ((a > b) ? 1 : 0)); else if (!isNaN(a_num) && !isNaN(b_num)) return ((a_num < b_num) ? -1 : ((a_num > b_num) ? 1 : 0)); else return isNaN(a_num) ? -1 : 1; } require.config({paths: { datatables: 'https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min' }}); require(["datatables"], function(){ console.log("$('#table5747322560-454422').dataTable()"); jQuery.extend( jQuery.fn.dataTableExt.oSort, { "optionalnum-asc": astropy_sort_num, "optionalnum-desc": function (a,b) { return -astropy_sort_num(a, b); } }); $('#table5747322560-454422').dataTable({ order: [], pageLength: 100, lengthMenu: [[10, 25, 50, 100, 500, 1000, -1], [10, 25, 50, 100, 500, 1000, 'All']], pagingType: "full_numbers", columnDefs: [{targets: [4, 5, 6], type: "optionalnum"}] }); }); </script> Since, both the Jet model the EBL share the same parameter, i.e. the redshift, we link the two parameters ```python composite_model.link_par(par_name='z_cosm', from_model=my_jet.name, to_model='Franceschini_2008') ``` adding par: z_cosm to z_cosm ```python composite_model.show_pars() ``` <i>Table length=14</i> <table id="table5747319344-882310" class="table-striped table-bordered table-condensed"> <thead><tr><th>model name</th><th>name</th><th>par type</th><th>units</th><th>val</th><th>phys. bound. min</th><th>phys. bound. max</th><th>log</th><th>frozen</th></tr></thead> <tr><td>jet_flaring</td><td>R</td><td>region_size</td><td>cm</td><td>5.000000e+15</td><td>1.000000e+03</td><td>1.000000e+30</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>R_H</td><td>region_position</td><td>cm</td><td>1.000000e+17</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>B</td><td>magnetic_field</td><td>gauss</td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>NH_cold_to_rel_e</td><td>cold_p_to_rel_e_ratio</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>beam_obj</td><td>beaming</td><td></td><td>1.000000e+01</td><td>1.000000e-04</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>z_cosm(L,Franceschini_2008)</td><td>redshift</td><td></td><td>--</td><td>--</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>gmin</td><td>low-energy-cut-off</td><td>lorentz-factor*</td><td>2.000000e+00</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gmax</td><td>high-energy-cut-off</td><td>lorentz-factor*</td><td>1.000000e+06</td><td>1.000000e+00</td><td>1.000000e+15</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>N</td><td>emitters_density</td><td>1 / cm3</td><td>1.000000e+02</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gamma0_log_parab</td><td>turn-over-energy</td><td>lorentz-factor*</td><td>1.000000e+04</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>s</td><td>LE_spectral_slope</td><td></td><td>2.000000e+00</td><td>-1.000000e+01</td><td>1.000000e+01</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>r</td><td>spectral_curvature</td><td></td><td>4.000000e-01</td><td>-1.500000e+01</td><td>1.500000e+01</td><td>False</td><td>False</td></tr> <tr><td>Franceschini_2008</td><td>scale_factor</td><td>scale_factor</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>Franceschini_2008</td><td>z_cosm(M)</td><td>redshift</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> </table><style>table.dataTable {clear: both; width: auto !important; margin: 0 !important;} .dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate{ display: inline-block; margin-right: 1em; } .paginate_button { margin-right: 5px; } </style> <script> var astropy_sort_num = function(a, b) { var a_num = parseFloat(a); var b_num = parseFloat(b); if (isNaN(a_num) && isNaN(b_num)) return ((a < b) ? -1 : ((a > b) ? 1 : 0)); else if (!isNaN(a_num) && !isNaN(b_num)) return ((a_num < b_num) ? -1 : ((a_num > b_num) ? 1 : 0)); else return isNaN(a_num) ? -1 : 1; } require.config({paths: { datatables: 'https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min' }}); require(["datatables"], function(){ console.log("$('#table5747319344-882310').dataTable()"); jQuery.extend( jQuery.fn.dataTableExt.oSort, { "optionalnum-asc": astropy_sort_num, "optionalnum-desc": function (a,b) { return -astropy_sort_num(a, b); } }); $('#table5747319344-882310').dataTable({ order: [], pageLength: 100, lengthMenu: [[10, 25, 50, 100, 500, 1000, -1], [10, 25, 50, 100, 500, 1000, 'All']], pagingType: "full_numbers", columnDefs: [{targets: [4, 5, 6], type: "optionalnum"}] }); }); </script> As you can see, now the paramter `z_cosm` in `jet_flaring` is the `master` parameter (flagged by the M in parenthesis), and the one belonging to the `Franceschini_2008` component is the linked one (flagged by the L in parenthesis). ## Setting parameters .. note:: composite model (:class:`.FitModel` class) requires to set parameters by specifying the model component, this is different from versions<1.2.0 These methods are alternative and equivalent ways to set a parameter in a composite model: a) accessing the model component member of the b) using `set_par` and passing as first argument the model component name c) using `set_par` and passing as first argument the model component object ```python #a composite_model.Franceschini_2008.parameters.z_cosm.val=0.1 #b composite_model.set_par('Franceschini_2008','z_cosm',0.1) #c composite_model.set_par(ebl_franceschini,'z_cosm',0.1) ``` And now, we can define the functional form of the model composition, just by writing the mathematical expression as a string, using the model names reported in the model description table, and that's it! ```python composite_model.show_model_components() ``` -------------------------------------------------------------------------------- Composite model description -------------------------------------------------------------------------------- name: EBL corrected type: composite_model components models: -model name: jet_flaring model type: jet -model name: Franceschini_2008 model type: table2D -------------------------------------------------------------------------------- ```python composite_model.composite_expr='jet_flaring*Franceschini_2008' ``` ```python composite_model.jet_flaring.IC_nu_size=150 composite_model.eval() p=composite_model.plot_model() ``` ![png](output_24_0.png) ```python composite_model.save_model('composite.pkl') cm=FitModel.load_model('composite.pkl') ``` ===> setting C threads to 12 ## Sum of two jets (steady and flaring) and application of the EBL absorption to both (Multiplicative and additive) Assume that now we want to sum to jet models (a steady and flaring component) and apply to both of them the EBL absorption. ```python composite_model=FitModel(nu_size=500,name='EBL corrected flaring+steady') composite_model.add_component(my_jet) composite_model.add_component(ebl_franceschini) ``` /Users/orion/miniforge3/envs/jetset/lib/python3.10/site-packages/jetset/model_manager.py:158: UserWarning: no cosmology defined, using FlatLambdaCDM(name="Planck13", H0=67.77 km / (Mpc s), Om0=0.30712, Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.048252) warnings.warn(m) ```python steady_jet=Jet(electron_distribution='plc',name='steady_jet') composite_model.add_component(steady_jet) composite_model.show_model_components() ``` ===> setting C threads to 12 -------------------------------------------------------------------------------- Composite model description -------------------------------------------------------------------------------- name: EBL corrected flaring+steady type: composite_model components models: -model name: jet_flaring model type: jet -model name: Franceschini_2008 model type: table2D -model name: steady_jet model type: jet -------------------------------------------------------------------------------- now we link the same parameter `z_cosm` from the `steady_jet` to the same `master` parameter used for the `EBL` model, i.e. to the `jet_flaring` model ```python composite_model.link_par(par_name='z_cosm',from_model=['steady_jet'],to_model='Franceschini_2008') ``` adding par: z_cosm to z_cosm ```python composite_model.show_pars() ``` <i>Table length=25</i> <table id="table5745750704-201022" class="table-striped table-bordered table-condensed"> <thead><tr><th>model name</th><th>name</th><th>par type</th><th>units</th><th>val</th><th>phys. bound. min</th><th>phys. bound. max</th><th>log</th><th>frozen</th></tr></thead> <tr><td>jet_flaring</td><td>R</td><td>region_size</td><td>cm</td><td>5.000000e+15</td><td>1.000000e+03</td><td>1.000000e+30</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>R_H</td><td>region_position</td><td>cm</td><td>1.000000e+17</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>B</td><td>magnetic_field</td><td>gauss</td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>NH_cold_to_rel_e</td><td>cold_p_to_rel_e_ratio</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>beam_obj</td><td>beaming</td><td></td><td>1.000000e+01</td><td>1.000000e-04</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>z_cosm(L,Franceschini_2008)</td><td>redshift</td><td></td><td>--</td><td>--</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>gmin</td><td>low-energy-cut-off</td><td>lorentz-factor*</td><td>2.000000e+00</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gmax</td><td>high-energy-cut-off</td><td>lorentz-factor*</td><td>1.000000e+06</td><td>1.000000e+00</td><td>1.000000e+15</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>N</td><td>emitters_density</td><td>1 / cm3</td><td>1.000000e+02</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gamma0_log_parab</td><td>turn-over-energy</td><td>lorentz-factor*</td><td>1.000000e+04</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>s</td><td>LE_spectral_slope</td><td></td><td>2.000000e+00</td><td>-1.000000e+01</td><td>1.000000e+01</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>r</td><td>spectral_curvature</td><td></td><td>4.000000e-01</td><td>-1.500000e+01</td><td>1.500000e+01</td><td>False</td><td>False</td></tr> <tr><td>Franceschini_2008</td><td>scale_factor</td><td>scale_factor</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>Franceschini_2008</td><td>z_cosm(M)</td><td>redshift</td><td></td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>R</td><td>region_size</td><td>cm</td><td>5.000000e+15</td><td>1.000000e+03</td><td>1.000000e+30</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>R_H</td><td>region_position</td><td>cm</td><td>1.000000e+17</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>B</td><td>magnetic_field</td><td>gauss</td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>NH_cold_to_rel_e</td><td>cold_p_to_rel_e_ratio</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>beam_obj</td><td>beaming</td><td></td><td>1.000000e+01</td><td>1.000000e-04</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>z_cosm(L,Franceschini_2008)</td><td>redshift</td><td></td><td>--</td><td>--</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>gmin</td><td>low-energy-cut-off</td><td>lorentz-factor*</td><td>2.000000e+00</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>gmax</td><td>high-energy-cut-off</td><td>lorentz-factor*</td><td>1.000000e+06</td><td>1.000000e+00</td><td>1.000000e+15</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>N</td><td>emitters_density</td><td>1 / cm3</td><td>1.000000e+02</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>gamma_cut</td><td>turn-over-energy</td><td>lorentz-factor*</td><td>1.000000e+04</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>p</td><td>LE_spectral_slope</td><td></td><td>2.000000e+00</td><td>-1.000000e+01</td><td>1.000000e+01</td><td>False</td><td>False</td></tr> </table><style>table.dataTable {clear: both; width: auto !important; margin: 0 !important;} .dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate{ display: inline-block; margin-right: 1em; } .paginate_button { margin-right: 5px; } </style> <script> var astropy_sort_num = function(a, b) { var a_num = parseFloat(a); var b_num = parseFloat(b); if (isNaN(a_num) && isNaN(b_num)) return ((a < b) ? -1 : ((a > b) ? 1 : 0)); else if (!isNaN(a_num) && !isNaN(b_num)) return ((a_num < b_num) ? -1 : ((a_num > b_num) ? 1 : 0)); else return isNaN(a_num) ? -1 : 1; } require.config({paths: { datatables: 'https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min' }}); require(["datatables"], function(){ console.log("$('#table5745750704-201022').dataTable()"); jQuery.extend( jQuery.fn.dataTableExt.oSort, { "optionalnum-asc": astropy_sort_num, "optionalnum-desc": function (a,b) { return -astropy_sort_num(a, b); } }); $('#table5745750704-201022').dataTable({ order: [], pageLength: 100, lengthMenu: [[10, 25, 50, 100, 500, 1000, -1], [10, 25, 50, 100, 500, 1000, 'All']], pagingType: "full_numbers", columnDefs: [{targets: [4, 5, 6], type: "optionalnum"}] }); }); </script> ```python composite_model.steady_jet.IC_nu_size=150 ``` ```python composite_model.composite_expr='(jet_flaring + steady_jet) * Franceschini_2008' ``` ```python composite_model.eval() p=composite_model.plot_model() p.setlim(y_max=1E-12) ``` ![png](output_35_0.png) ```python composite_model.save_model('composite.pkl') ``` ```python cm=FitModel.load_model('composite.pkl') ``` ===> setting C threads to 12 ===> setting C threads to 12 ```python cm.show_pars() ``` <i>Table length=25</i> <table id="table5747736736-581571" class="table-striped table-bordered table-condensed"> <thead><tr><th>model name</th><th>name</th><th>par type</th><th>units</th><th>val</th><th>phys. bound. min</th><th>phys. bound. max</th><th>log</th><th>frozen</th></tr></thead> <tr><td>jet_flaring</td><td>gmin</td><td>low-energy-cut-off</td><td>lorentz-factor*</td><td>2.000000e+00</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gmax</td><td>high-energy-cut-off</td><td>lorentz-factor*</td><td>1.000000e+06</td><td>1.000000e+00</td><td>1.000000e+15</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>N</td><td>emitters_density</td><td>1 / cm3</td><td>1.000000e+02</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>gamma0_log_parab</td><td>turn-over-energy</td><td>lorentz-factor*</td><td>1.000000e+04</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>s</td><td>LE_spectral_slope</td><td></td><td>2.000000e+00</td><td>-1.000000e+01</td><td>1.000000e+01</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>r</td><td>spectral_curvature</td><td></td><td>4.000000e-01</td><td>-1.500000e+01</td><td>1.500000e+01</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>R</td><td>region_size</td><td>cm</td><td>5.000000e+15</td><td>1.000000e+03</td><td>1.000000e+30</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>R_H</td><td>region_position</td><td>cm</td><td>1.000000e+17</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>B</td><td>magnetic_field</td><td>gauss</td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>NH_cold_to_rel_e</td><td>cold_p_to_rel_e_ratio</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>jet_flaring</td><td>beam_obj</td><td>beaming</td><td></td><td>1.000000e+01</td><td>1.000000e-04</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>jet_flaring</td><td>z_cosm(L,Franceschini_2008)</td><td>redshift</td><td></td><td>--</td><td>--</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>Franceschini_2008</td><td>scale_factor</td><td>scale_factor</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>Franceschini_2008</td><td>z_cosm(M)</td><td>redshift</td><td></td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>gmin</td><td>low-energy-cut-off</td><td>lorentz-factor*</td><td>2.000000e+00</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>gmax</td><td>high-energy-cut-off</td><td>lorentz-factor*</td><td>1.000000e+06</td><td>1.000000e+00</td><td>1.000000e+15</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>N</td><td>emitters_density</td><td>1 / cm3</td><td>1.000000e+02</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>gamma_cut</td><td>turn-over-energy</td><td>lorentz-factor*</td><td>1.000000e+04</td><td>1.000000e+00</td><td>1.000000e+09</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>p</td><td>LE_spectral_slope</td><td></td><td>2.000000e+00</td><td>-1.000000e+01</td><td>1.000000e+01</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>R</td><td>region_size</td><td>cm</td><td>5.000000e+15</td><td>1.000000e+03</td><td>1.000000e+30</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>R_H</td><td>region_position</td><td>cm</td><td>1.000000e+17</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>B</td><td>magnetic_field</td><td>gauss</td><td>1.000000e-01</td><td>0.000000e+00</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>NH_cold_to_rel_e</td><td>cold_p_to_rel_e_ratio</td><td></td><td>1.000000e+00</td><td>0.000000e+00</td><td>--</td><td>False</td><td>True</td></tr> <tr><td>steady_jet</td><td>beam_obj</td><td>beaming</td><td></td><td>1.000000e+01</td><td>1.000000e-04</td><td>--</td><td>False</td><td>False</td></tr> <tr><td>steady_jet</td><td>z_cosm(L,Franceschini_2008)</td><td>redshift</td><td></td><td>--</td><td>--</td><td>--</td><td>False</td><td>True</td></tr> </table><style>table.dataTable {clear: both; width: auto !important; margin: 0 !important;} .dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate{ display: inline-block; margin-right: 1em; } .paginate_button { margin-right: 5px; } </style> <script> var astropy_sort_num = function(a, b) { var a_num = parseFloat(a); var b_num = parseFloat(b); if (isNaN(a_num) && isNaN(b_num)) return ((a < b) ? -1 : ((a > b) ? 1 : 0)); else if (!isNaN(a_num) && !isNaN(b_num)) return ((a_num < b_num) ? -1 : ((a_num > b_num) ? 1 : 0)); else return isNaN(a_num) ? -1 : 1; } require.config({paths: { datatables: 'https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min' }}); require(["datatables"], function(){ console.log("$('#table5747736736-581571').dataTable()"); jQuery.extend( jQuery.fn.dataTableExt.oSort, { "optionalnum-asc": astropy_sort_num, "optionalnum-desc": function (a,b) { return -astropy_sort_num(a, b); } }); $('#table5747736736-581571').dataTable({ order: [], pageLength: 100, lengthMenu: [[10, 25, 50, 100, 500, 1000, -1], [10, 25, 50, 100, 500, 1000, 'All']], pagingType: "full_numbers", columnDefs: [{targets: [4, 5, 6], type: "optionalnum"}] }); }); </script>
andreatramacereREPO_NAMEjetsetPATH_START.@jetset_extracted@jetset-master@doc@documentation_notebooks@notebooks@composite_model@Composite_model.ipynb@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "SPARTA-dev/SPARTA", "repo_path": "SPARTA_extracted/SPARTA-master/sparta/UNICOR/__init__.py", "type": "Python" }
from .Spectrum import Spectrum from .Template import Template from .CCF1d import CCF1d
SPARTA-devREPO_NAMESPARTAPATH_START.@SPARTA_extracted@SPARTA-master@sparta@UNICOR@__init__.py@.PATH_END.py
{ "filename": "eos.py", "repo_name": "geodynamics/burnman", "repo_path": "burnman_extracted/burnman-main/burnman/tools/eos.py", "type": "Python" }
# This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for # the Earth and Planetary Sciences # Copyright (C) 2012 - 2021 by the BurnMan team, released under the GNU # GPL v2 or later. import numpy as np import warnings from scipy.linalg import logm def check_eos_consistency( m, P=1.0e9, T=300.0, tol=1.0e-4, verbose=False, including_shear_properties=True, equilibration_function=None, ): """ Checks that numerical derivatives of the Gibbs energy of a mineral under given conditions are equal to those provided analytically by the equation of state. :param m: The mineral for which the equation of state is to be checked for consistency. :type m: :class:`burnman.Mineral` :param P: The pressure at which to check consistency. :type P: float :param T: The temperature at which to check consistency. :type T: float :param tol: The fractional tolerance for each of the checks. :type tol: float :param verbose: Decide whether to print information about each check. :type verbose: bool :param including_shear_properties: Decide whether to check shear information, which is pointless for liquids and equations of state without shear modulus parameterizations. :type including_shear_properties: bool :param equilibration_function: Function to internally equilibrate object. Called after every set_state. Takes the mineral object as its only argument. :type equilibration_function: function :returns: Boolean stating whether all checks have passed. :rtype: bool """ if equilibration_function is None: def equilibration_function(mineral): pass dT = 1.0 dP = 1000.0 m.set_state(P, T) equilibration_function(m) G0 = m.gibbs S0 = m.S V0 = m.V expr = ["G = F + PV", "G = H - TS", "G = E - TS + PV"] eq = [ [m.gibbs, (m.helmholtz + P * m.V)], [m.gibbs, (m.H - T * m.S)], [m.gibbs, (m.molar_internal_energy - T * m.S + P * m.V)], ] m.set_state(P, T + dT) equilibration_function(m) G1 = m.gibbs S1 = m.S V1 = m.V m.set_state(P + dP, T) equilibration_function(m) G2 = m.gibbs V2 = m.V # T derivatives m.set_state(P, T + 0.5 * dT) equilibration_function(m) expr.extend(["S = -dG/dT", "alpha = 1/V dV/dT", "C_p = T dS/dT"]) eq.extend( [ [m.S, -(G1 - G0) / dT], [m.alpha, (V1 - V0) / dT / m.V], [m.molar_heat_capacity_p, (T + 0.5 * dT) * (S1 - S0) / dT], ] ) # P derivatives m.set_state(P + 0.5 * dP, T) equilibration_function(m) expr.extend(["V = dG/dP", "K_T = -V dP/dV"]) eq.extend( [ [m.V, (G2 - G0) / dP], [m.isothermal_bulk_modulus_reuss, -0.5 * (V2 + V0) * dP / (V2 - V0)], ] ) expr.extend( ["C_v = Cp - alpha^2*K_T*V*T", "K_S = K_T*Cp/Cv", "gr = alpha*K_T*V/Cv"] ) eq.extend( [ [ m.molar_heat_capacity_v, m.molar_heat_capacity_p - m.alpha * m.alpha * m.isothermal_bulk_modulus_reuss * m.V * T, ], [ m.isentropic_bulk_modulus_reuss, m.isothermal_bulk_modulus_reuss * m.molar_heat_capacity_p / m.molar_heat_capacity_v, ], [ m.gr, m.alpha * m.isothermal_bulk_modulus_reuss * m.V / m.molar_heat_capacity_v, ], ] ) expr.append("Vphi = np.sqrt(K_S/rho)") eq.append([m.bulk_sound_velocity, np.sqrt(m.isentropic_bulk_modulus_reuss / m.rho)]) if including_shear_properties: expr.extend(["Vp = np.sqrt((K_S + 4G/3)/rho)", "Vs = np.sqrt(G_S/rho)"]) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") eq.extend( [ [ m.p_wave_velocity, np.sqrt( (m.isentropic_bulk_modulus_reuss + 4.0 * m.G / 3.0) / m.rho ), ], [m.shear_wave_velocity, np.sqrt(m.G / m.rho)], ] ) if len(w) == 1: print(w[0].message) print( "\nYou can suppress this message by setting the " "parameter\nincluding_shear_properties to False " "when calling check_eos_consistency.\n" ) note = "" else: note = " (not including shear properties)" consistencies = [ np.abs(e[0] - e[1]) < np.abs(tol * e[1]) + np.finfo("float").eps for e in eq ] eos_is_consistent = np.all(consistencies) if verbose: print("Checking EoS consistency for {0:s}{1}".format(m.to_string(), note)) print("Expressions within tolerance of {0:2f}".format(tol)) for i, c in enumerate(consistencies): print("{0:10s} : {1:5s}".format(expr[i], str(c))) if not c: print(eq[i]) if eos_is_consistent: print( "All EoS consistency constraints satisfied for {0:s}".format( m.to_string() ) ) else: print( "Not satisfied all EoS consistency constraints for {0:s}".format( m.to_string() ) ) return eos_is_consistent def check_anisotropic_eos_consistency( m, P=1.0e9, T=300.0, tol=1.0e-4, verbose=False, equilibration_function=None ): """ Checks that numerical derivatives of the Gibbs energy of an anisotropic mineral under given conditions are equal to those provided analytically by the equation of state. :param m: The anisotropic mineral for which the equation of state is to be checked for consistency. :type m: :class:`burnman.AnisotropicMineral` :param P: The pressure at which to check consistency. :type P: float :param T: The temperature at which to check consistency. :type T: float :param tol: The fractional tolerance for each of the checks. :type tol: float :param verbose: Decide whether to print information about each check. :type verbose: bool :param equilibration_function: Function to internally equilibrate object. Called after every set_state. Takes the mineral object as its only argument. :type equilibration_function: function :returns: Boolean stating whether all checks have passed. :rtype: bool """ if equilibration_function is None: def equilibration_function(mineral): pass dT = 1.0 dP = 1000.0 m.set_state(P, T) equilibration_function(m) G0 = m.gibbs S0 = m.S V0 = m.V expr = ["G = F + PV", "G = H - TS", "G = E - TS + PV"] eq = [ [m.gibbs, (m.helmholtz + P * m.V)], [m.gibbs, (m.H - T * m.S)], [m.gibbs, (m.molar_internal_energy - T * m.S + P * m.V)], ] m.set_state(P, T + dT) equilibration_function(m) G1 = m.gibbs S1 = m.S V1 = m.V m.set_state(P + dP, T) equilibration_function(m) G2 = m.gibbs V2 = m.V # T derivatives m.set_state(P, T + 0.5 * dT) equilibration_function(m) expr.extend(["S = -dG/dT", "alpha = 1/V dV/dT", "C_p = T dS/dT"]) eq.extend( [ [m.S, -(G1 - G0) / dT], [m.alpha, (V1 - V0) / dT / m.V], [m.molar_heat_capacity_p, (T + 0.5 * dT) * (S1 - S0) / dT], ] ) # P derivatives m.set_state(P + 0.5 * dP, T) equilibration_function(m) expr.extend(["V = dG/dP", "K_T = -V dP/dV"]) eq.extend( [ [m.V, (G2 - G0) / dP], [m.isothermal_bulk_modulus_reuss, -0.5 * (V2 + V0) * dP / (V2 - V0)], ] ) expr.extend(["C_v = Cp - alpha^2*K_T*V*T", "K_S = K_T*Cp/Cv"]) eq.extend( [ [ m.molar_heat_capacity_v, m.molar_heat_capacity_p - m.alpha * m.alpha * m.isothermal_bulk_modulus_reuss * m.V * T, ], [ m.isentropic_bulk_modulus_reuss, m.isothermal_bulk_modulus_reuss * m.molar_heat_capacity_p / m.molar_heat_capacity_v, ], ] ) # Third derivative m.set_state(P + 0.5 * dP, T) equilibration_function(m) b0 = m.isothermal_compressibility_tensor F0 = m.deformation_gradient_tensor m.set_state(P + 0.5 * dP, T + dT) equilibration_function(m) b1 = m.isothermal_compressibility_tensor F1 = m.deformation_gradient_tensor m.set_state(P, T + 0.5 * dT) equilibration_function(m) a0 = m.thermal_expansivity_tensor F2 = m.deformation_gradient_tensor m.set_state(P + dP, T + 0.5 * dT) equilibration_function(m) a1 = m.thermal_expansivity_tensor F3 = m.deformation_gradient_tensor m.set_state(P + 0.5 * dP, T + 0.5 * dT) equilibration_function(m) beta0 = -(logm(F3) - logm(F2)) / dP alpha0 = (logm(F1) - logm(F0)) / dT Q = m.deformed_coordinate_frame beta1 = m.isothermal_compressibility_tensor alpha1 = m.thermal_expansivity_tensor beta1 = np.einsum("mi, nj, ij->mn", Q, Q, beta1) alpha1 = np.einsum("mi, nj, ij->mn", Q, Q, alpha1) if m.orthotropic: expr.extend( [f"SI = -d(lnm(F))/dP ({i}{j})" for i in range(3) for j in range(i, 3)] ) expr.extend( [f"alpha = d(lnm(F))/dT ({i}{j})" for i in range(3) for j in range(i, 3)] ) else: expr.extend( [ f"SI = -0.5(dF/dP*F^-1 + (dF/dP*F^-1)^T) ({i}{j})" for i in range(3) for j in range(i, 3) ] ) expr.extend( [ f"alpha = 0.5(dF/dT*F^-1 + (dF/dT*F^-1)^T) ({i}{j})" for i in range(3) for j in range(i, 3) ] ) invF = np.linalg.inv(m.deformation_gradient_tensor) dFdP = (F3 - F2) / dP LP = np.einsum("ij,kj->ik", dFdP, invF) beta0 = -0.5 * (LP + LP.T) dFdT = (F1 - F0) / dT LT = np.einsum("ij,kj->ik", dFdT, invF) alpha0 = 0.5 * (LT + LT.T) eq.extend([[beta0[i, j], beta1[i, j]] for i in range(3) for j in range(i, 3)]) eq.extend([[alpha0[i, j], alpha1[i, j]] for i in range(3) for j in range(i, 3)]) expr.extend( [f"d(alpha)/dP = -d(beta_T)/dT ({i}{j})" for i in range(3) for j in range(i, 3)] ) eq.extend( [ [(a1[i, j] - a0[i, j]) / dP, -(b1[i, j] - b0[i, j]) / dT] for i in range(3) for j in range(i, 3) ] ) # Consistent Phi expr.extend(["dPsidf_Voigt[:3,:3] == 1"]) eq.extend( [ [ np.sum(m.isothermal_compliance_tensor[:3, :3]), m.isothermal_compressibility_reuss, ] ] ) # Consistent inverses expr.extend([f"S_T = inv(C_T) ({i}{j})" for i in range(6) for j in range(i, 6)]) S_T = m.isothermal_compliance_tensor S_T2 = np.linalg.inv(m.isothermal_stiffness_tensor) eq.extend([[S_T[i, j], S_T2[i, j]] for i in range(6) for j in range(i, 6)]) expr.extend([f"S_N = inv(C_N) ({i}{j})" for i in range(6) for j in range(i, 6)]) S_N = m.isentropic_compliance_tensor S_N2 = np.linalg.inv(m.isentropic_stiffness_tensor) eq.extend([[S_N[i, j], S_N2[i, j]] for i in range(6) for j in range(i, 6)]) # Consistent isotropic and anisotropic properties expr.extend( [ "V = det(M)", "alpha_v = tr(alpha)", "beta_RT = sum(I S_T I)", "beta_RS = sum(I S_S I)", ] ) eq.extend( [ [m.V, np.linalg.det(m.cell_vectors)], [m.alpha, np.trace(m.thermal_expansivity_tensor)], [ m.isothermal_compressibility_reuss, np.sum(m.isothermal_compliance_tensor[:3, :3]), ], [ m.isentropic_compressibility_reuss, np.sum(m.isentropic_compliance_tensor[:3, :3]), ], ] ) expr.append("Vphi = np.sqrt(K_S/rho)") eq.append([m.bulk_sound_velocity, np.sqrt(m.isentropic_bulk_modulus_reuss / m.rho)]) consistencies = [ np.abs(e[0] - e[1]) < np.abs(tol * e[1]) + np.finfo("float").eps for e in eq ] eos_is_consistent = np.all(consistencies) if verbose: print("Checking EoS consistency for {0:s}".format(m.to_string())) print("Expressions within tolerance of {0:2f}".format(tol)) for i, c in enumerate(consistencies): print("{0:10s} : {1:5s}".format(expr[i], str(c))) if not c: print(eq[i]) if eos_is_consistent: print( "All EoS consistency constraints satisfied for {0:s}".format( m.to_string() ) ) else: print( "Not satisfied all EoS consistency constraints for {0:s}".format( m.to_string() ) ) return eos_is_consistent
geodynamicsREPO_NAMEburnmanPATH_START.@burnman_extracted@burnman-main@burnman@tools@eos.py@.PATH_END.py
{ "filename": "_histogram2dcontour.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/layout/template/data/_histogram2dcontour.py", "type": "Python" }
import _plotly_utils.basevalidators class Histogram2DcontourValidator(_plotly_utils.basevalidators.CompoundArrayValidator): def __init__( self, plotly_name="histogram2dcontour", parent_name="layout.template.data", **kwargs ): super(Histogram2DcontourValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Histogram2dContour"), data_docs=kwargs.pop( "data_docs", """ """, ), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@layout@template@data@_histogram2dcontour.py@.PATH_END.py
{ "filename": "_size.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/scatter/unselected/marker/_size.py", "type": "Python" }
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="scatter.unselected.marker", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), min=kwargs.pop("min", 0), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@scatter@unselected@marker@_size.py@.PATH_END.py
{ "filename": "_lineposition.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattergeo/hoverlabel/font/_lineposition.py", "type": "Python" }
import _plotly_utils.basevalidators class LinepositionValidator(_plotly_utils.basevalidators.FlaglistValidator): def __init__( self, plotly_name="lineposition", parent_name="scattergeo.hoverlabel.font", **kwargs, ): super(LinepositionValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), extras=kwargs.pop("extras", ["none"]), flags=kwargs.pop("flags", ["under", "over", "through"]), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattergeo@hoverlabel@font@_lineposition.py@.PATH_END.py
{ "filename": "redcal_inspect_2458086.ipynb", "repo_name": "HERA-Team/H1C_IDR3_Notebooks", "repo_path": "H1C_IDR3_Notebooks-main/redcal_inspect/redcal_inspect_2458086.ipynb", "type": "Jupyter Notebook" }
# Stage 2 Redundant Calibration Nightly Notebook **Josh Dillon**, Last Revised 7/30/20 ```python import numpy as np import matplotlib.pyplot as plt import matplotlib from hera_cal import io, redcal, apply_cal from hera_qm.metrics_io import load_metric_file import glob import os from copy import deepcopy import inspect import h5py %matplotlib inline %config InlineBackend.figure_format = 'retina' ``` ```python # If you want to run this notebook locally, copy the output of the next cell into the first few lines of this cell. # JD = '2459122' # data_path = '/lustre/aoc/projects/hera/H4C/2459122' # os.environ["JULIANDATE"] = JD # os.environ["DATA_PATH"] = data_path ``` ```python # Use environment variables to figure out path to data JD = os.environ['JULIANDATE'] data_path = os.environ['DATA_PATH'] print(f'JD = "{JD}"') print(f'data_path = "{data_path}"') ``` JD = "2458086" data_path = "/lustre/aoc/projects/hera/H1C_IDR3/IDR3_2/2458086" ```python print('Looking for data in', data_path, 'on JD', JD) data_list = sorted(glob.glob(os.path.join(data_path, f'zen.{JD}.?????.sum.uvh5'))) if len(data_list) == 0: data_list = sorted(glob.glob(os.path.join(data_path, f'zen.{JD}.?????.uvh5'))) print('Found {} files.'.format(len(data_list))) ``` Looking for data in /lustre/aoc/projects/hera/H1C_IDR3/IDR3_2/2458086 on JD 2458086 Found 73 files. # Load Single File ```python # Pick middle of the night data file to examine example_file = data_list[len(data_list)//2] file_JD = '.'.join([s for s in example_file.split('.') if s.isdigit()]) ``` ```python # controls how many redundant baseline groups to plot. # 2 means the most common ee- and nn-polarized baseline. n_reds_to_plot = 2 ``` ```python # Load omnical gains and determine ex_ants hc = io.HERACal(example_file.replace('.uvh5', f'.omni.calfits')) gains, gain_flags, _, _ = hc.read() ex_ants = [ant for ant in gain_flags if np.all(gain_flags[ant])] # Load the most common redundant baselines and calibrate hd = io.HERAData(example_file) reds = redcal.get_reds(hd.antpos, pols=['ee', 'nn']) red_bl_map = {bl: red[0] for red in reds for bl in red} reds = redcal.filter_reds(reds, ex_ants=ex_ants) reds = sorted(reds, key=len, reverse=True) data, flags, nsamples = hd.read( bls=[bl for red in reds[0:n_reds_to_plot] for bl in red]) apply_cal.calibrate_in_place(data, gains, data_flags=flags, cal_flags=gain_flags) # Load omnical visibility solutions hdo = io.HERAData(example_file.replace('.uvh5', f'.omni_vis.uvh5')) omni_data, omni_flags, omni_nsamples = hdo.read( bls=[red_bl_map[red[0]] for red in reds[0:n_reds_to_plot]]) ``` # Inspect Single File ```python plt.figure(figsize=(8,8)) plt.scatter(np.array(list(hd.antpos.values()))[:,0], np.array(list(hd.antpos.values()))[:,1], c='w', s=0) for ant,pos in hd.antpos.items(): bad = ant in [ant[0] for ant in ex_ants] plt.gca().add_artist(plt.Circle(tuple(pos[0:2]), radius=7, fill=(~bad), color=['grey','r'][bad])) plt.text(pos[0],pos[1],str(ant), va='center', ha='center', color='w') plt.xlabel("Antenna East-West Position (meters)") plt.ylabel("Antenna North-South Position (meters)") plt.title('Antenna Positions on {} (Red = Flagged)'.format(file_JD)); plt.axis('equal') plt.tight_layout() plt.show() ``` ![png](output_10_0.png) ### Figure 1: Array and Flagged Antennas #### OBSERVER CHECKLIST: * Check that the array configuration looks reasonable. * Check that all flags expected to be flagged are actually flagged but also that not everything is getting flagged. ```python # Plot redundant groups for red in reds[0:n_reds_to_plot]: blvec = hd.antpos[red[0][1]] - hd.antpos[red[0][0]] for func, plot, ylabel in zip([np.abs, np.angle], [plt.semilogy, plt.plot], ['Amplitude (Arbitrary Units)', 'Phase (Radians)']): plt.figure(figsize=(16,4)) for bl in red: plot(hd.freqs/1e6, func(np.median(data[bl], axis=0))) plot(hd.freqs/1e6, func(np.median(omni_data[red_bl_map[red[0]]], axis=0)), 'k-', label='Omnical Visibility Solution') plt.xlabel('Frequency (MHz)') plt.ylabel(ylabel) plt.legend(loc='lower right') plt.title('{}-Polarized, {:f} m East, {:f} m North Visibility on {}'.format(red[0][2], blvec[0], blvec[1], file_JD)) ``` ![png](output_12_0.png) ![png](output_12_1.png) ![png](output_12_2.png) ![png](output_12_3.png) ### Figure 2: Example redundant baseline groups and omnical visibility solution for a single file. #### OBSERVER CHECKLIST: * Check that that there actually is something plotted and the data isn't all flagged somehow. * Check whether most of the baselines cluster together and that the black line follows the cluster. * Check whether there are any significant outliers (though it won't be clear as yet which antennas those are attributable to, see below). # Load Whole Day ```python # load all redcal metadata into dictionaries meta_list = [df.replace('.uvh5', f'.redcal_meta.hdf5') for df in data_list] ee_iters_dict = {} nn_iters_dict = {} dlys_dict = {} flips_dict = {} times_dict = {} lsts_dict = {} histories_dict = {} ants = set([]) for mf in meta_list: (fc_meta, omni_meta, freqs, times_dict[mf], lsts_dict[mf], antpos, histories_dict[mf]) = io.read_redcal_meta(mf) ee_iters_dict[mf] = omni_meta['iter']["['ee']"] nn_iters_dict[mf] = omni_meta['iter']["['nn']"] flips_dict[mf] = fc_meta['polarity_flips'] dlys_dict[mf] = fc_meta['dlys'] ants |= set(fc_meta['dlys'].keys()) ants = sorted(ants) times = np.hstack(list(times_dict.values())) lsts = np.hstack(list(lsts_dict.values())) ``` ```python # Load chisq and flagging info from omnical gains cal_list = [df.replace('.uvh5', f'.omni.calfits') for df in data_list] ant_flags_dict = {} chisq_ee_dict = {} chisq_nn_dict = {} cspa_med_dict = {} for cal in cal_list: hc = io.HERACal(cal) _, flags, cspa, chisq = hc.read() ant_flags_dict[cal] = {ant: np.all(flags[ant]) for ant in flags} chisq_ee_dict[cal] = chisq['Jee'] chisq_nn_dict[cal] = chisq['Jnn'] cspa_med_dict[cal] = {ant: np.nanmedian(cspa[ant], axis=1) for ant in cspa} all_flagged_dict = {ant: np.all([af[ant] for af in ant_flags_dict.values()]) for ant in ants} cspa = {ant: np.hstack([np.squeeze(cspa_med_dict[cal][ant]) / \ ~ant_flags_dict[cal][ant] for cal in cal_list]) for ant in ants} ``` invalid value encountered in true_divide divide by zero encountered in true_divide ```python # save middle-numbered ants with a minimal number of flags ants_to_save = {} for pol in ['Jee', 'Jnn']: min_flags = np.min([np.sum(~np.isfinite(cspa[ant])) for ant in cspa if ant[1] == pol]) ant_candidates = sorted([ant for ant in cspa if ant[1] == pol and np.sum(~np.isfinite(cspa[ant])) == min_flags]) Nac = len(ant_candidates) ants_to_save[pol] = ant_candidates[(Nac // 2 - 1):(Nac // 2 + 1)] # Reload omnical gains gain_dict = {} flag_dict = {} for cal in cal_list: hc = io.HERACal(cal) gains, flags, _, _ = hc.read() gain_dict[cal] = {ant: gains[ant] for pol in ants_to_save for ant in ants_to_save[pol]} flag_dict[cal] = {ant: flags[ant] for pol in ants_to_save for ant in ants_to_save[pol]} gains = {ant: np.vstack([gain_dict[cal][ant] for cal in gain_dict]) for pol in ants_to_save for ant in ants_to_save[pol]} flags = {ant: np.vstack([flag_dict[cal][ant] for cal in flag_dict]) for pol in ants_to_save for ant in ants_to_save[pol]} flag_mask = np.all([f for f in flags.values()], axis=0) ``` # Inspect Whole Day ```python # Plot delays dlys = {ant: np.hstack([dlys_dict[mf][ant] for mf in dlys_dict]) for ant in ants} dly_meds = {ant: np.nanmedian(dlys[ant]) for ant in dlys} plt.figure(figsize=(16,10)) for ant in dlys: plt.plot(times, (dlys[ant])*1e9) if np.isfinite(dly_meds[ant]): plt.text(np.min(times) - 20*np.median(np.diff(times)), 1e9*dly_meds[ant], '{}{}'.format(ant[0], ant[1][-1]), va='center', ha='right', fontsize=8) plt.gca().set_xticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_xticks()]] * 12 / np.pi, 2)) plt.xlabel('LST (Hours)') plt.ylabel('Delay (ns)') plt.title('Firstcal Delays'); ``` All-NaN slice encountered FixedFormatter should only be used together with FixedLocator Text(0.5, 1.0, 'Firstcal Delays') ![png](output_19_2.png) ### Figure 3: Firstcal Delays Shows solved firstcal delays. These will have an arbitrary tip/tilt and offset. #### OBSERVER CHECKLIST: * Look for outliers. All antennas should be within a few hundred ns. ```python # Plot offset delays plt.figure(figsize=(16, len(ants)/7.4)) unflagged_dlys = {ant: dlys[ant] for ant in dlys if not all_flagged_dict[ant]} for n, ant in enumerate(unflagged_dlys): plt.plot(times, (dlys[ant]-dly_meds[ant])*1e9 + n, label=ant) plt.text(np.min(times) - 20*np.median(np.diff(times)), n, '{}{}'.format(ant[0], ant[1][-1]), va='center', ha='right', fontsize=8) plt.gca().set_xticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_xticks()]] * 12 / np.pi, 2)) plt.xlabel('LST (Hours)') plt.ylabel('Delay with Arbitrary Offset (ns)') plt.title('Firstcal Delays With Arbitrary Offset'); plt.ylim([-10, len(unflagged_dlys) + 10]) ``` FixedFormatter should only be used together with FixedLocator (-10.0, 92.0) ![png](output_21_2.png) ### Figure 4: Offset Firstcal Delays Same as Figure 4, but with arbitrary offsets for each antenna. #### OBSERVER CHECKLIST: * Look for antennas that exhibit wild swings (> 10 ns) in their delay over time. ```python # Figure out oc_maxiter if np.all(['oc_maxiter' in history for history in histories_dict.values()]): history = list(histories_dict.values())[0] oc_maxiter = int(history.split('--oc_maxiter')[1].split('--')[0]) else: oc_maxiter = inspect.signature(redcal.redcal_run).parameters['oc_maxiter'].default ``` ```python # Recast from dictionaries to one big array ee_iters = np.vstack(np.array(list(ee_iters_dict.values()))) nn_iters = np.vstack(np.array(list(nn_iters_dict.values()))) plt.figure(figsize=(20,12)) my_cmap = deepcopy(matplotlib.cm.get_cmap('viridis')) my_cmap.set_under('w') my_cmap.set_over('r') for sp, iters, t in zip([121, 122], [ee_iters, nn_iters], ['ee-polarized', 'nn-polarized']): plt.subplot(sp) plt.imshow(iters, aspect='auto', cmap=my_cmap, vmin=1, vmax=oc_maxiter-1, interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.title('Number of Omnical Iterations: ' + t) plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() ``` Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray You are modifying the state of a globally registered colormap. In future versions, you will not be able to modify a registered colormap in-place. To remove this warning, you can make a copy of the colormap first. cmap = copy.copy(mpl.cm.get_cmap("viridis")) You are modifying the state of a globally registered colormap. In future versions, you will not be able to modify a registered colormap in-place. To remove this warning, you can make a copy of the colormap first. cmap = copy.copy(mpl.cm.get_cmap("viridis")) FixedFormatter should only be used together with FixedLocator ![png](output_24_1.png) ### Figure 5: Number of omnical iterations per polarization Red indicates that omnical reached the maximum number of integrations. White indicates that omnical didn't run, likely because the data were flagged. #### OBSERVER CHECKLIST: * Check that few-to-no data were flagged (white) before omnical and check that this matches * Check that few-to-no data hit the maximum number of iterations for omnical (red) ```python # Make dictionary mapping antenna to the whole night of antenna flips flips = {ant: np.hstack([flips_dict[mf][ant] for mf in flips_dict]) for ant in ants} plt.figure(figsize=(16,8)) my_cmap = matplotlib.cm.get_cmap('cool') for sp, jpol, t in zip([121, 122], ['Jee', 'Jnn'], ['ee-polarized ', 'nn-polarized']): plt.subplot(sp) plt.scatter(np.array(list(hd.antpos.values()))[:,0], np.array(list(hd.antpos.values()))[:,1], c='w', s=0) for ant,pos in hd.antpos.items(): flip_frac = np.nanmean(flips[(ant, jpol)]) if np.isfinite(flip_frac): color=my_cmap(flip_frac) else: color='w' plt.gca().add_artist(plt.Circle(tuple(pos[0:2]), radius=7, fill=(~bad), color=color, ec='k')) plt.text(pos[0], pos[1], '{}:\n{}%'.format(ant, np.round(100*flip_frac,0)), va='center', ha='center', color='k') plt.xlabel("Antenna East-West Position (meters)") plt.ylabel("Antenna North-South Position (meters)") # count the number of times a self-consistent polarity flip solution was found all_flips_this_pol = [flips[ant] for ant in flips if ant[1] == jpol] success = np.round(100*np.mean(np.any(np.isfinite(all_flips_this_pol), axis=0)), 2) plt.title(t + ' Polarity Flips -- Solution Found {}% of the Time'.format(success)) plt.axis('equal') plt.tight_layout() ``` Mean of empty slice ![png](output_26_1.png) ### Figure 6: Detection of polarity-flipped antennas Blue indicates nominal operation, pink indicates polarity flips. #### OBSERVER CHECKLIST: * Check that all antennas are either nearly 100% flipped, nearly 0% flipped, or flagged. * Check that a solution for polarity flips was found a reasonable percentage of the time (ideally more than a few %) ```python # Grid and plot overall chi^2 for each polarization ee_chisq = np.vstack(np.array(list(chisq_ee_dict.values()))) nn_chisq = np.vstack(np.array(list(chisq_nn_dict.values()))) plt.figure(figsize=(20,12)) for sp, cs, t in zip([121, 122], [ee_chisq, nn_chisq], ['ee-polarized', 'nn-polarized']): plt.subplot(sp) plt.imshow(cs / ~flag_mask, aspect='auto', vmin=0, cmap='inferno', vmax=3, interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.title('Overall $\chi^2$ / DoF: ' + t) plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() ``` Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray divide by zero encountered in true_divide invalid value encountered in true_divide FixedFormatter should only be used together with FixedLocator ![png](output_28_1.png) ### Figure 7 Overall $\chi^2$ / DoF #### OBSERVER CHECKLIST: * Looks for regions of large non-redundancy not directly attributable to RFI. ```python # plot all chi^2 per antenna, highlight antennas with >1.5 mean chisq per ant (median over frequency) plt.figure(figsize=(20,10)) for sp, pol, t in zip([121, 122], ['Jee', 'Jnn'], ['ee-polarized', 'nn-polarized']): plt.subplot(sp) for ant in sorted([ant for ant in ants if ant[1] == pol], key=lambda ant: np.nanmean(cspa[ant]), reverse=True): if not np.all([ant_flags_dict[cal][ant] for cal in cal_list]): if np.nanmean(cspa[ant]) > 1.5: plt.plot(times, cspa[ant], '.', label=ant) else: plt.plot(times, cspa[ant], '-', color='grey', lw=.25) plt.ylabel('Normalized Median $\chi^2$ per Antenna (unitless)') plt.gca().set_xticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_xticks()]] * 12 / np.pi, 2)) plt.xlabel('LST (Hours)') plt.title(t + ' Antennas') plt.legend() ``` FixedFormatter should only be used together with FixedLocator FixedFormatter should only be used together with FixedLocator ![png](output_30_1.png) ### Figure 8: Normalized $\chi^2$ per antenna Antennas with chisq per ant (mean over time, median over freq) > 1.5 are colored. All other antennas are shown in grey. #### OBSERVER CHECKLIST: * Look for outliers in the chi^2 per antenna distribution ```python # Plot example gain amplitudes plt.figure(figsize=(20,12)) for sp, pol in zip([121, 122], ['Jee', 'Jnn']): plt.subplot(sp) ant = ants_to_save[pol][1] plt.title(str(ant) + ' Gain Magnitude') plt.imshow(np.abs(gains[ant]) / ~flag_mask, aspect='auto', cmap='inferno', interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.clim([0,2]) plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') ``` divide by zero encountered in true_divide FixedFormatter should only be used together with FixedLocator ![png](output_32_1.png) ### Figure 9: Example Amplitudes #### OBSERVER CHECKLIST: * Looks for large discontinuities or fuzziness not attributable to RFI ```python # Plot example gain relative phases plt.figure(figsize=(20,12)) for sp, pol in zip([121, 122], ['Jee', 'Jnn']): plt.subplot(sp) ant0, ant1 = ants_to_save[pol] plt.title('Angle of gains[{}] / gains[{}]'.format(ant0, ant1)) plt.imshow(np.angle(gains[ant0] / gains[ant1]) / ~flag_mask, aspect='auto', cmap='twilight', interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') ``` invalid value encountered in true_divide FixedFormatter should only be used together with FixedLocator ![png](output_34_1.png) ### Figure 10: Example Gain Phases Relative gain phases of two example antennas. #### OBSERVER CHECKLIST: * Check that these gains are relatively stable in time and that there aren't huge phase discontinuities. # Metadata ```python print(redcal.version.history_string()) ``` ------------ This file was produced by the function <module>() in <ipython-input-1-c6de44361328> using: git_branch: master git_description: v3.0-733-gd2dd8ccf git_hash: d2dd8ccf3fe43d5e5eb6a4c28ceaf4a6e3d1fcb7 git_origin: git@github.com:HERA-Team/hera_cal.git version: 3.0 ------------
HERA-TeamREPO_NAMEH1C_IDR3_NotebooksPATH_START.@H1C_IDR3_Notebooks-main@redcal_inspect@redcal_inspect_2458086.ipynb@.PATH_END.py
{ "filename": "talk_plots.ipynb", "repo_name": "ojhall94/halletal2019", "repo_path": "halletal2019_extracted/halletal2019-master/code/Scripts/talk_plots.ipynb", "type": "Jupyter Notebook" }
```python import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import matplotlib from mpl_toolkits.axes_grid1.inset_locator import inset_axes, mark_inset from mpl_toolkits.axes_grid1.colorbar import colorbar matplotlib.rcParams['text.usetex'] = False sns.set_palette('colorblind',10) sns.set_context('notebook') matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) matplotlib.rc('axes',labelsize=20) __imdir = '/home/oliver/PhD/Skill_Transfers/Warwick_Science_Day/' ``` ## Results ```python def read_paramdict(majorlabel, minorlabel='', sort='astero'): '''Reads in results for either: -A full run series (majorlabel) where the minorlabel is included as a column in the output. -A single run (majorlabel and minorlabel). Returns a pandas dataframe. ''' loc = __outdir__+majorlabel+'/' if minorlabel != '': globlist = glob.glob(loc+sort+'_'+str(float(minorlabel))+'_*pars*.csv') else: globlist = glob.glob(loc+sort+'*_*pars*.csv') minorlabels = [os.path.basename(globloc).split('_')[1] for globloc in globlist] if sort == 'gaia': ccdlabels = [os.path.basename(globloc).split('_')[-2] for globloc in globlist] df = pd.DataFrame() for n, globloc in enumerate(globlist): sdf = pd.read_csv(globloc, index_col = 0) if minorlabels[n] != 'pars.csv': sdf[majorlabel] = minorlabels[n] if sort == 'gaia': sdf['ccdlabel'] = ccdlabels[n] df = df.append(sdf) return df.sort_values(by=majorlabel) import os import glob __outdir__ = os.path.expanduser('~')+'/PhD/Gaia_Project/Output/Paper_Output_2.0/' ``` ## Errorbar method ```python yu_knoc = read_paramdict('K_tempscale_noCorrection') yu_krc = read_paramdict('K_tempscale_Clump') yu_knoc['tempscale'] = yu_knoc['K_tempscale_noCorrection'].str.strip() yu_knoc['tempscale'] = yu_knoc.tempscale.astype(float) yu_krc['tempscale'] = yu_krc['K_tempscale_Clump'].str.strip() yu_krc['tempscale'] = yu_krc.tempscale.astype(float) apo_knoc = read_paramdict('APOKASC_K_tempscale_noCorrection') apo_krc = read_paramdict('APOKASC_K_tempscale_Clump') apo_knoc['tempscale'] = apo_knoc['APOKASC_K_tempscale_noCorrection'].str.strip() apo_knoc['tempscale'] = apo_knoc.tempscale.astype(float) apo_krc['tempscale'] = apo_krc['APOKASC_K_tempscale_Clump'].str.strip() apo_krc['tempscale'] = apo_krc.tempscale.astype(float) ``` # Asteroseismic Run ```python import matplotlib.gridspec as gridspec cmap = sns.color_palette('colorblind') fig = plt.figure(figsize=(16, 8)) gs0 = gridspec.GridSpec(1, 2, figure=fig,wspace=0.) ax1 = plt.subplot(gs0[:, :1]) ax2 = plt.subplot(gs0[:, 1:],sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) ax1.grid() ax1.set_axisbelow(True) ax2.grid() ax2.set_axisbelow(True) (_, caps1,_) = ax2.errorbar(yu_knoc.tempscale, yu_knoc.mu, yerr = yu_knoc.mu_std, fmt='o', capsize=10, label='No Correction') (_, caps2,_) = ax2.errorbar(yu_krc.tempscale, yu_krc.mu, yerr = yu_krc.mu_std, fmt='o', capsize=10,label='Clump Correction') (_, caps3,_) = ax1.errorbar(apo_knoc.tempscale, apo_knoc.mu, yerr = apo_knoc.mu_std, fmt='o', capsize=10, label='No Correction') (_, caps4,_) = ax1.errorbar(apo_krc.tempscale, apo_krc.mu, yerr = apo_krc.mu_std, fmt='o', capsize=10,label='Clump Correction') for cap1, cap2 in zip(caps1, caps2): cap1.set_markeredgewidth(1) cap2.set_markeredgewidth(1) ax1.set_ylabel(r'Position of RC in $K$ band (mag)', fontsize=25) fig.text(0.72, 0.9, r'Yu et al. 2018', ha='center', fontsize=25) fig.text(0.32, 0.9, r"APOKASC-2", ha='center', fontsize=25) fig.text(0.32, 0.02, r'Temperature Shift (K)', ha='center', fontsize=25) fig.text(0.72, 0.02, r'Temperature Shift (K)', ha='center', fontsize=25) ax1.legend(loc='upper right', fontsize='20') ax2.legend(loc='upper right', fontsize='20') plt.savefig(__imdir+'seismo_error.pdf') plt.show() ``` /home/oliver/.local/lib/python2.7/site-packages/matplotlib/font_manager.py:1331: UserWarning: findfont: Font family [u'serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ![png](output_6_1.png) ## Violinplot method ```python def read_music(ml, kind, band, cnc, crc): chains = np.array([]) tempscales = np.array([]) ncrc = np.array([]) for ts in np.arange(-50.,60.,10.): temp = str(ts) #Add NC chains & labels chain = np.genfromtxt(glob.glob(__outdir__+ml+'_'+cnc+'/'+kind+'_'+temp+'_chains.txt')[0])[0] chains = np.append(chains, chain) tempscales = np.append(tempscales, np.ones(len(chain))*ts) ncrc = np.append(ncrc, ['No Correction']*len(chain)) #Add RC chains & labels chain = np.genfromtxt(glob.glob(__outdir__+ml+'_'+crc+'/'+kind+'_'+temp+'_chains.txt')[0])[0] chains = np.append(chains, chain) tempscales = np.append(tempscales, np.ones(len(chain))*ts) ncrc = np.append(ncrc, ['Clump Corrected']*len(chain)) music = pd.DataFrame() music['chains'] = chains music['tempscales'] = tempscales music['ncrc'] = ncrc return music ``` ```python mls = ['K_tempscale', 'APOKASC_K_tempscale'] kind = 'astero' bands = ['K', 'GAIA'] cnc = 'noCorrection' crc = 'Clump' yukmusic = read_music(mls[0], kind, bands[0], cnc, crc) apokmusic = read_music(mls[1], kind, bands[0], cnc, crc) ``` ```python fig = plt.figure(figsize=(16, 8)) gs0 = gridspec.GridSpec(1, 2, figure=fig,wspace=0.) ax1 = plt.subplot(gs0[:, :1]) ax2 = plt.subplot(gs0[:, 1:],sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) ax1.grid() ax1.set_axisbelow(True) ax2.grid() ax2.set_axisbelow(True) sns.violinplot(apokmusic.tempscales.astype(int).values, apokmusic.chains.values, hue=apokmusic.ncrc.values, palette='Set2',split=True, inner='quartile', ax = ax1) sns.violinplot(yukmusic.tempscales.astype(int).values, yukmusic.chains.values, hue=yukmusic.ncrc.values, palette='Set2',split=True, inner='quartile', ax = ax2) ax1.set_ylabel(r'Position of RC in $K$ band (mag)', fontsize=25) fig.text(0.72, 0.9, r'Yu et al. 2018', ha='center', fontsize=25) fig.text(0.32, 0.9, r"APOKASC-2", ha='center', fontsize=25) fig.text(0.32, 0.02, r'Temperature Shift (K)', ha='center', fontsize=25) fig.text(0.72, 0.02, r'Temperature Shift (K)', ha='center', fontsize=25) ax1.legend(loc='upper right', fontsize='20') ax2.legend(loc='upper right', fontsize='20') plt.savefig(__imdir+'seismo_violin.pdf') plt.savefig(__imdir+'seismo_violin.png') plt.show() ``` ![png](output_10_0.png) # Gaia run using seismic priors ## Errorbar Method ```python yu_krc = read_paramdict('Gaia_K_tempscale_Clump',sort='gaia') yu_krc['tempscale'] = yu_krc['Gaia_K_tempscale_Clump'].str.strip() yu_krc['tempscale'] = yu_krc.tempscale.astype(float) apo_krc = read_paramdict('Gaia_APOKASC_K_tempscale_Clump',sort='gaia') apo_krc['tempscale'] = apo_krc['Gaia_APOKASC_K_tempscale_Clump'].str.strip() apo_krc['tempscale'] = apo_krc.tempscale.astype(float) ``` ```python fig = plt.figure(figsize=(16, 8)) gs0 = gridspec.GridSpec(1, 2, figure=fig,wspace=0.) ax1 = plt.subplot(gs0[:, :1]) ax2 = plt.subplot(gs0[:, 1:],sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) ax1.grid() ax1.set_axisbelow(True) ax2.grid() ax2.set_axisbelow(True) (_, caps2,_) = ax2.errorbar(yu_krc.mu, yu_krc.oo_zp, yerr = yu_krc.oo_zp_std, xerr = yu_krc.mu_std, fmt='o', capsize=10,label='Clump Correction') (_, caps4,_) = ax1.errorbar(apo_krc.mu, apo_krc.oo_zp, yerr = apo_krc.oo_zp_std, xerr = apo_krc.mu_std, fmt='o', capsize=10,label='Clump Correction') for cap1, cap2 in zip(caps1, caps2): cap1.set_markeredgewidth(1) cap2.set_markeredgewidth(1) ax1.set_ylabel(r'Parallax Zero-Point Offset ($\mu \rm as$)', fontsize=25) fig.text(0.72, 0.9, r'Yu et al. 2018', ha='center', fontsize=25) fig.text(0.32, 0.9, r"APOKASC-2", ha='center', fontsize=25) fig.text(0.32, 0.02, r'Position of RC in $K$ band (mag)', ha='center', fontsize=25) fig.text(0.72, 0.02, r'Position of RC in $K$ band (mag)', ha='center', fontsize=25) plt.savefig(__imdir+'gaia_error.pdf') plt.show() ``` ![png](output_14_0.png) ## Violinplot Method ```python def read_music(mls): chains = np.array([]) tempscales = np.array([]) rcmag = np.array([]) source = np.array([]) sources = ['Yu+2018','APOKASC-2'] cols = ['Left','Right'] col = np.array([]) for idx, ml in enumerate(mls): for ts in np.arange(-50.,100.,50.): temp = str(ts) #Add RC chains & labels try: chain = np.genfromtxt(__outdir__+ml+'/'+'gaia_'+temp+'_chains.txt')[-1] chains = np.append(chains, chain) tempscales = np.append(tempscales, np.ones(len(chain))*ts) mu = np.round(pd.read_csv(__outdir__+ml+'/'+'gaia_'+temp+'_pars.csv')['mu'].values[0],2) rcmag = np.append(rcmag, np.ones(len(chain))*mu) source = np.append(source, [sources[idx]]*len(chain)) col = np.append(col, [cols[idx]]*len(chain)) except IOError: popt = get_slopes(mls, ccd) mu_wanted = np.round(pd.read_csv(__outdir__+ml.replace('Gaia_','')+'/'+'astero_'+temp+'_pars.csv')['mu'].values[0],2) oozp_wanted = popt[0]*mu_wanted + popt[1] oozp_base = pd.read_csv(__outdir__+mls[0]+'/'+'gaia_-50.0_pars.csv')['oo_zp'].values[0] diff = oozp_wanted - oozp_base chain = np.genfromtxt(__outdir__+mls[0]+'/'+'gaia_-50.0_chains.txt')[-1] chains = np.append(chains, chain+diff) rcmag = np.append(rcmag, np.ones(len(chain))*mu_wanted) source = np.append(source, ['Extrapolated']*len(chain)) tempscales = np.append(tempscales, np.ones(len(chain))*ts) col = np.append(col, [cols[idx]]*len(chain)) music = pd.DataFrame() music['chains'] = chains music['tempscales'] = tempscales music['rcmag'] = rcmag music['source'] = source music['col'] = col return music ``` ```python mlk = ['Gaia_K_tempscale_Clump', 'Gaia_APOKASC_K_tempscale_Clump'] kmusic = read_music(mlk) kyu = kmusic[kmusic.source == 'Yu+2018'] kapo = kmusic[kmusic.source == 'APOKASC-2'] ``` ```python fig = plt.figure(figsize=(16, 8)) gs0 = gridspec.GridSpec(1, 2, figure=fig,wspace=0.) ax1 = plt.subplot(gs0[:, :1]) ax2 = plt.subplot(gs0[:, 1:],sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) ax1.grid() ax1.set_axisbelow(True) ax2.grid() ax2.set_axisbelow(True) sns.violinplot(kyu.rcmag.values, kyu.chains.values, palette='Set2', hue = kyu.source.values, dodge=False, inner='quartile',ax=ax1) sns.violinplot(kapo.rcmag.values, kapo.chains.values, palette='Paired', hue = kapo.source.values, dodge=False, inner='quartile',ax=ax2) ax1.set_ylabel(r'Parallax Zero-Point Offset ($\mu \rm as$)', fontsize=25) fig.text(0.32, 0.9, r'Yu et al. 2018', ha='center', fontsize=25) fig.text(0.72, 0.9, r"APOKASC-2", ha='center', fontsize=25) fig.text(0.32, 0.02, r'Position of RC in $K$ band (mag)', ha='center', fontsize=25) fig.text(0.72, 0.02, r'Position of RC in $K$ band (mag)', ha='center', fontsize=25) ax1.get_legend().remove() ax2.get_legend().remove() plt.savefig(__imdir+'gaia_violin.pdf') plt.show() ``` ![png](output_18_0.png) # Gaia run using Literature Priors ```python oozps = pd.DataFrame(index=['Lindegren','Zinn','Riess','Sahlholdt','Stassun','Hawkins','Uninformed'], columns=['mu','spread']) oozps.loc['Lindegren']['mu'] = -29. oozps.loc['Lindegren']['spread'] = 1. oozps.loc['Zinn']['mu'] = -52.8 oozps.loc['Zinn']['spread'] = 3.4 oozps.loc['Riess']['mu'] = -46. oozps.loc['Riess']['spread'] = 13. oozps.loc['Sahlholdt']['mu'] = -35. oozps.loc['Sahlholdt']['spread'] = 16. oozps.loc['Stassun']['mu'] = -82. oozps.loc['Stassun']['spread'] = 33. oozps.loc['Hawkins']['mu'] = 0. oozps.loc['Hawkins']['spread'] = 1. # oozps.loc['Uninformed']['mu'] = 0. # oozps.loc['Uninformed']['spread'] = 1000. # oozps.loc['Khan']['mu'] = -47.02 # oozps.loc['Khan']['spread'] = 0.80 ``` ```python loc = os.path.expanduser('~')+'/PhD/Gaia_Project/Output/'+'Parallax_Runs/Highruns/' indices = oozps.index.values df = pd.DataFrame() for idx in indices: sdf = pd.read_csv(loc+'K_'+idx+'_pars.csv',index_col=0) sdf['Source'] = idx df = df.append(sdf) ``` ```python fig, ax = plt.subplots(figsize=(16, 8)) ax.grid() ax.set_axisbelow(True) modindices = ['Lindegren','Zinn','Riess','Sahlholdt & Silva Aguirre','Stassun & Torres','None','Uninformed'] ax.set_ylabel(r'Position of RC in $K$ band (mag)', fontsize=25) ax.set_xlabel(r'Literature Parallax Zero-Point ($\mu \rm as$)',fontsize=25) for n, idx in enumerate(oozps.index.values): if idx == 'Uninformed': sel = df['Source'] == idx print(df[sel]['mu']) print(df[sel]['mu_std']) (_, caps, _) = ax.errorbar(df[sel].oo_zp,df[sel]['mu'], yerr=df[sel]['mu_std'], xerr=df[sel].oo_zp_std, linewidth=4., capsize=10, zorder=2,c='r',label=None) ax.scatter(df[sel].oo_zp, df[sel].mu, marker='*',s=800, c='r', label=modindices[n],zorder=10, edgecolor='k') else: sel = df['Source'] == idx (_, caps, _) = ax.errorbar(oozps.loc[idx]['mu'],df[sel]['mu'], yerr=df[sel]['mu_std'], xerr=oozps.loc[idx]['spread'], linewidth=3., capsize=10, label=modindices[n], zorder=1) for cap in caps: cap.set_markeredgewidth(1) ax.legend(loc='lower center', fontsize=20,ncol=4, bbox_to_anchor=(.5, .05)) fig.tight_layout() plt.savefig(__imdir+'paralalx_error.pdf') plt.show() ``` 0 -1.638231 Name: mu, dtype: float64 0 0.011805 Name: mu_std, dtype: float64 ![png](output_22_1.png) # Inference of seismology from Gaia ```python yu_knoc = read_paramdict('K_tempscale_noCorrection') yu_krc = read_paramdict('K_tempscale_Clump') yu_knoc['tempscale'] = yu_knoc['K_tempscale_noCorrection'].str.strip() yu_knoc['tempscale'] = yu_knoc.tempscale.astype(float) yu_krc['tempscale'] = yu_krc['K_tempscale_Clump'].str.strip() yu_krc['tempscale'] = yu_krc.tempscale.astype(float) yu_knoc = yu_knoc.sort_values('tempscale') yu_krc = yu_krc.sort_values('tempscale') apo_knoc = read_paramdict('APOKASC_K_tempscale_noCorrection') apo_krc = read_paramdict('APOKASC_K_tempscale_Clump') apo_knoc['tempscale'] = apo_knoc['APOKASC_K_tempscale_noCorrection'].str.strip() apo_knoc['tempscale'] = apo_knoc.tempscale.astype(float) apo_krc['tempscale'] = apo_krc['APOKASC_K_tempscale_Clump'].str.strip() apo_krc['tempscale'] = apo_krc.tempscale.astype(float) apo_knoc = apo_knoc.sort_values('tempscale') apo_krc = apo_krc.sort_values('tempscale') __datdir__ = os.path.expanduser('~')+'/PhD/Gaia_Project/data/KepxDR2/' df = pd.read_csv(__datdir__+'rcxyu18.csv') apo = pd.read_csv(__datdir__+'rcxyuxapokasc2.csv') yumedt = np.array([np.mean(df.Teff+dt) for dt in np.arange(-50,60,10)]) apomedt = np.array([np.mean(apo.Teff+dt) for dt in np.arange(-50, 60,10)]) ``` ```python #Lets fit some lines fig = plt.figure() x0 = np.linspace(4600, 5000, 1000) p0 = np.zeros(4) p1 = np.zeros(4) for idx, frame in enumerate([yu_knoc, yu_krc, apo_knoc, apo_krc]): if idx < 2: medt = yumedt else: medt = apomedt A = np.vander(medt, 2) y = frame.mu.values yerr = frame.mu_std.values p = np.linalg.solve(np.dot(A.T, A/yerr[:, None]**2), np.dot(A.T, y/yerr**2)) p0[idx] = p[0] p1[idx] = p[1] ``` <Figure size 432x288 with 0 Axes> ```python fig, ax1 = plt.subplots(figsize=(16, 8)) ax1.grid() ax1.set_axisbelow(True) (_, caps1,_) = ax1.errorbar(yumedt, yu_knoc.mu, yerr = yu_knoc.mu_std, fmt='o', elinewidth=3, capsize=10, label='No Correction') (_, caps2,_) = ax1.errorbar(yumedt, yu_krc.mu, yerr = yu_krc.mu_std, fmt='*', elinewidth=3, capsize=10,label='Clump Correction') (_, caps3,_) = ax1.errorbar(apomedt, apo_knoc.mu, yerr = apo_knoc.mu_std, fmt='o', elinewidth=3, capsize=10, label='No Correction') (_, caps4,_) = ax1.errorbar(apomedt, apo_krc.mu, yerr = apo_krc.mu_std, fmt='*', elinewidth=3, capsize=10,label='Clump Correction') mumax = -1.638 + 0.012 mumin = -1.638 - 0.012 idx = 0 for pzero, pone in zip(p0, p1): line = x0*pzero + pone tmin = (mumax - pone)/pzero tmax = (mumin - pone)/pzero ax1.plot(x0, x0*pzero + pone,linestyle='-.', lw=2,c='k',alpha=.5) xfill = np.linspace(x0.min(), tmin,100) linefill = xfill*pzero + pone ax1.fill_between(xfill, np.ones(len(xfill))*mumin, np.ones(len(xfill))*mumax, interpolate=True, alpha=.1, color='r') xfill = np.linspace(tmin, tmax, 100) linefill = xfill*pzero + pone ax1.fill_between(xfill, np.ones(len(xfill))*-1.80, linefill, alpha=.1, interpolate=True, color='r') if idx < 2: print('Mean shift correspond to a temperature of: {} K'.format(np.mean(xfill)-np.mean(df.Teff))) else: print('Mean shift correspond to a temperature of: {} K'.format(np.mean(xfill)-np.mean(apo.Teff))) idx += 1 print('Difference in means from Yu to Apo: {} K'.format(np.mean(df.Teff - np.mean(apo.Teff)))) print('Difference in means from Yu to Apo subsamples: {} K'.format(np.mean(apo.Yu_Teff - np.mean(apo.Teff)))) ax1.set_ylabel(r'Position of RC in $K$ band (mag)', fontsize=25) fig.text(0.75, 0.9, r'Yu et al. 2018', ha='center', fontsize=25) fig.text(0.43, 0.9, r"APOKASC-2", ha='center', fontsize=25) ax1.set_xlabel(r'Mean Temperature of run sample ($K$)',fontsize=25) ax1.legend(loc='upper right', fontsize='20') ax1.set_xlim(x0.min(), x0.max()) ax1.set_ylim(-1.78, -1.60) plt.savefig(__imdir+'calibration.pdf') plt.show() ``` Mean shift correspond to a temperature of: -183.903803093 K Mean shift correspond to a temperature of: -186.639457147 K Mean shift correspond to a temperature of: -90.464282768 K Mean shift correspond to a temperature of: -94.6819759369 K Difference in means from Yu to Apo: 159.197782691 K Difference in means from Yu to Apo subsamples: 55.1209529627 K ![png](output_26_1.png) # KASC/TASC Graveyard ## Asteroseismic model ```python df = pd.read_csv('../../data/KepxDR2/rcxyu18.csv') df.head(1) ``` ```python fig, ax = plt.subplots(figsize=(12,10)) c=ax.scatter(df.ra, df.dec, s=df.parallax*80, c=df.Kmag,cmap='viridis_r') plt.xlabel('RA') plt.ylabel('Dec') fig.colorbar(c, label='K-band apparent magnitude') fig.tight_layout() plt.title('Total # Stars: '+str(len(df)),fontsize=25) plt.savefig('data_field.png') plt.show() ``` ```python fig, ax = plt.subplots(figsize=(6,6)) sns.distplot(df['ast_Mbol'], ax = ax) plt.xlabel('Seismic Absolute K-band Magnitude') plt.yticks([]) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) plt.tight_layout() plt.savefig('seismic_kmag.png') plt.show() ``` ```python def normal(x, mu, sigma): return (1/np.sqrt(2*np.pi*sigma**2)) * np.exp(-(x - mu)**2/(2*sigma**2)) rmu = -1.7 rsigma = .1 rsigo = 4. * rsigma rQ = .85 x = np.linspace(-3, -0.5, len(df)) fg = normal(x, rmu, rsigma) bg = normal(x, rmu, rsigo) ll = rQ * fg + (1-rQ) * bg fig, ax = plt.subplots(figsize=(6,6)) ax.plot(x, fg, linestyle='--', label='RC') ax.plot(x, bg, linestyle='--', label='Outliers') ax.plot(x, ll, label = 'Model') ax.legend(loc='best', fontsize=20) plt.yticks([]) plt.xlabel('Seismic Absolute K-band Magnitude') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) plt.tight_layout() plt.savefig('mixmod.png') plt.show() ``` ```python from tqdm import tqdm def normal(x, mu, sigma): return (1/np.sqrt(2*np.pi*sigma**2)) * np.exp(-(x - mu)**2/(2*sigma**2)) x = np.linspace(-3.0, -0.5, 100) fig, ax = plt.subplots(figsize=(6,6)) for idx in tqdm(range(len(df[:20]))): ax.plot(x, normal(x, df['ast_MKs'][idx], df['ast_M_err'][idx]),alpha=.75) plt.yticks([]) plt.xlabel('Seismic Absolute K-band Magnitude') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) plt.tight_layout() plt.savefig('infM.png') plt.show() ``` ```python df.ast_M_err[0] ``` HR Diagram ```python df = pd.read_csv('../../data/TRILEGAL_sim/k1.6b_K15b30_0910_new.all.out.txt',sep = '\s+') df = df[:] print(list(df)) ``` ```python fig, ax = plt.subplots(figsize=(10,10)) ax.scatter(3.7,1.52,facecolor=None) ax.scatter(df['logg'], df['logL'],c=df.stage,s=1) # df_rc = df[(df.stage == 4) | (df.stage == 5) | (df.stage == 6)] # ax.scatter(df_rc['logg'], df_rc['logL'],s=2) # axins = inset_axes(ax, width='33%', height='33%',loc=3, borderpad=6.) # Telo, Tehi = 3.64, 3.72 # Llo, Lhi = 1.52, 2.1 # df_in = df[(df.logTe > Telo) & (df.logTe < Tehi) & (df.logL > Llo) & (df.logL < Lhi)] # sel = (df_in.stage.values == 4) | (df_in.stage.values == 5) | (df_in.stage.values == 6) # axins.scatter(df_in.logTe[~sel], df_in.logL[~sel], s=5, c='k',alpha=.01) # c = axins.scatter(df_in.logTe[sel], df_in.logL[sel], s=5, c=df_in.Mact[sel], cmap='viridis') # cax = inset_axes(axins, # width="5%", # width = 10% of parent_bbox width # height="100%", # height : 50% # loc=3, # bbox_to_anchor=(1.05, 0., 1, 1), # bbox_transform=axins.transAxes, # borderpad=0, # ) # fig.colorbar(c, cax=cax, label=r'$M (M_\odot)$') # axins.invert_xaxis() # patch, pp1, pp2 = mark_inset(ax, axins, loc1=4, loc2=1, lw=1, ec='k', fc='none') # pp1.loc1 = 2 # pp1.loc2 = 1 # pp2.loc1 = 1 # pp2.loc2 = 2 # ax.set_xlabel(r'$log(T_{\rmeff} (K)$)') # ax.set_ylabel(r'$log(L)(L_\odot)$') # ax.set_title(r'TRILEGAL HR Diagram | Subset: Core He Burning coloured by Mass',fontsize=20) # ax.invert_xaxis() # plt.savefig('HRdiagram.png') plt.show() ```
ojhall94REPO_NAMEhalletal2019PATH_START.@halletal2019_extracted@halletal2019-master@code@Scripts@talk_plots.ipynb@.PATH_END.py
{ "filename": "name.py", "repo_name": "jkluter/MLG", "repo_path": "MLG_extracted/MLG-master/name.py", "type": "Python" }
import numpy as np __all__ = ['name'] def name(event_id, no_name = True, silent = False): '''------------------------------------------------------------ Description: --------------------------------------------------------------- Input: --------------------------------------------------------------- Output: ------------------------------------------------------------''' event_id = np.int64(event_id) where = np.where(namelist['ID'] == event_id)[0] if len(where)== 0: if not silent:print('Not in list:', event_id) if no_name: return 'DR2: '+ str(event_id) else: return '' if len(where)==1: if namelist[where[0]]['Name'] == '' : if no_name: return 'DR2: '+ str(event_id) else: return '' else: return namelist[where[0]]['Name'] if len(where)>1: if not silent:print('douplikat:', event_id) return namelist[where[0]]['Name'] def name_good(event_id, silent = False): '''------------------------------------------------------------ Description: --------------------------------------------------------------- Input: --------------------------------------------------------------- Output: ------------------------------------------------------------''' event_id = np.int64(event_id) where = np.where(namelist['ID'] == event_id)[0] if len(where)== 0: return True elif len(where)==1: return bool(namelist[where[0]]['Good']) print(1) elif len(where)>1: if not silent:print('douplikat:', event_id) return namelist[where[0]]['Good'] return True namelist = np.array([ (5853498713160606720, 'Proxima Cen', True), (1872046574983497216, '61 Cyg B', True), (5332606522595645952, 'LAWD 37', True), (1872046574983507456, '61 Cyg A', True), (5254061535097566848, 'L 143-23', True), (4516199240734836608, 'Ross 733', True), (4472832130942575872, "Barnard's star" , True), (5951824121022278144, 'GJ 674', True), (5339892367683264384, "Innes' star", True), (470826482635701376, 'Stein 2051 B', True), (6710522912622915712, 'UCAC3 86-396928', True), (1543076475514008064, 'G 123-61B', True), (5696640563228494464, 'WT 1550', True), (1964791583368232832, 'tau Cyg A', True), (4687445500635789184, 'OGLE SMC115.5 319', True), (1978296747258230912, 'LSPM J2129+4720', True), (2315857227976341504, 'HD 2404', True), (429297924157113856, 'G 217-32', True), (1157210463244589568, 'G 15-11', True), (2390377345808152832, 'HD 222506', True), (1935209944575937024, 'UCAC4 677-123934', True), (4793869292650732160, 'UPM J0537-4924', True), (6677000246203170944, 'HD 197484', True), (4687511776265158400, 'L 51-47', True), (5492622847798742272, 'L 240-16', True), (1543076475509704192, 'G 123-61A', True), (4544176352376541312, 'LP 506-50 A', True), (6522256697697129600, 'LEHPM 6274', True), (4529285391522200320, '109 Her', True), (6128259487711387008, 'L 328-36', True), (6585158207436506368, 'HD 207450', True), (5309386791195469824, 'HD 85228', True), (1961141200470502400, 'LSPM J2154+4344', True), (3347284175186268160, 'UCAC4 527-018168', True), (5396870945686245504, 'HD 97073', True), (5902780301768699392, 'HD 136466A', True), (3398414352092062720, 'G 100-35B', True), (4924486979061864832, 'CD-53 40', True), (4657982643495556608, 'OGLE LMC162.5 41235', True), (577478114092768384, 'G 114-33', True), (6368299918479525632, 'UCAC3 27-74415', True), (6036143915373978880, 'HD 144179A', True), (5225957639881367552, 'L 66-82', True), (5921433963191695872, 'LAWD 68', True), (4623882630333283328, 'L 31-84', True), (5559827605531610240, 'CD-43 3055', True), (2534338503471881728, 'G 70-55A', True), (2846620421603149312, 'G 129-51', True), (5302618648583292800, 'PM J08503-5848', True), (4451575895403432064, 'G 16-29', True), (5930568598406530048, 'HD 149192', True), (3763681215875388288, 'G 163-21', True), (4116840541184279296, 'L 702-43', True), (2759428629829608064, 'G 29-73', True), (5736464668224470400, 'L 820-19', True), (2912585037597833856, 'LP 838-28 A', True), (5235714289453482240, 'L 103-12', True), (1382796061323905024, 'TYC 3064-1282-1', True), (546488928621555328, 'G 245-47A', True), (6213824650812054528, 'LP 859-51', True), (5134154157033028352, 'LP 828-36', True), (2790883634570755968, 'LP 350-66', True), (5600272625752039296, 'L 601-78', True), (6874112547575038336, 'LP 814-25', True), (6549824370485770112, 'UCAC4 260-200149', True), (5608893346278863616, 'LP 896-12 A', True), (4056233810947522304, 'HD 316899', True), (654826970401335296, 'HD 66553', True), (6054954738289909632, 'HD 108500A', True), (4149572555606973568, 'LP 748-33', True), (2826159850241446784, 'HD 222474A', True), (2358524597030794112, 'V* YZ Cet', True), (1875076004382831616, 'BD+21 4747A', True), (6415630939116638464, 'EC 19249-7343', True), (1444367711752056960, 'LP 379-98', True), (1625058605098521600, 'HD 146868', True), (239070631455336064, 'BD+39 710A', True), (568432427635050240, 'G 245-68', True), (4937000898855759104, 'GJ 86', False), (5032229910174557056, 'HD 5425A', True), (2870877194301321088, 'TYC 2752-1121-1', True), (6916644779774493696, 'LP 636-60', True), (5359745012164917632, 'L 250-10', True), (2646280705713202816, 'BD+00 5017', True), (5243594081269535872, 'L 100-115', True), (5429919108417092096, 'LP 462-88', True), (5979367986779538432, 'CD-32 12693', True), (4041006743145526656, 'LP 486-32', True), (835871554301614848, 'LSPM J1047+5016', True), (5895473600324039680, 'L 260-120', True), (3585636855608873984, 'HD 102392A', True), (4228023259961831296, 'HD 197623', True), (101283987497967360, 'HD 13482A', True), (5393446658454453632, 'DENIS J1048.0-3956', True), (3842095911266162432, 'HD 78663', True), (4198685678421509376, 'HD 177758', True), (643819484616249984, 'mu. Leo', True), (4786715182805934592, 'HD 30361A', True), (4269932382606282112, 'eta Ser', True), (5941940988948890112, 'HD 330763A', True), (6031475835680030720, 'L 555-14', True), (1568219729458240128, 'HD 110833', True), (1015799283499485440, 'HD 77006', True), (3202470247468181632, 'BD-06 855', True), (488099359330834432, 'HD 22399', True), (1251328585567327744, 'HD 120065', True), (962141157557751552, 'G 101-35', True), (416158489625704320, 'G 172-11', True), (1962597885872344704, 'BD+43 4138', True), (4361365433110271232, 'HD 156826', True), (1817982759302341376, 'HD 347427', True), (2937651222655480832, 'HD 44573', True), (5657306462454704640, 'HD 85725', True), (4780100658292046592, 'L 230-188', True), (5941478335062267392, 'L 338-152', True), (6254033894120917760, 'L 768-119', True), (6209995700348976896, 'LP 915-41', True), (1136512191212093440, 'G 251-35', True), (5650153825784353280, 'HD 78643', True), (5413531987125139712, 'PM J10195-4622', True), (2028065934962125184, 'Ross 165A', True), (6787883382523590400, 'HD 201989', True), (3934198156329809152, 'HD 110315', True), (4657193606465368704, 'HD 39194', True), (598180646733241216, 'G 46-2', True), (5801950515627094400, 'HD 155918', True), (829777377964973952, 'HD 92855', True), (5856411869205581568, 'HD 109200', True), (466294295706341760, 'HD 18757', True), (533621859441169920, 'Ross 318', True), (4535144998232287232, 'HD 171314', True), (5534742080239458048, 'HD 66020', True), (5849427049801267200, 'HD 124584', True), (4293318823182081408, 'HD 180617', True), (1193030490492925824, 'gam Ser', True), (689004018040211072, '75 Cnc', True) ], dtype=[('ID','i8'),('Name','U25'), ('Good',bool)])
jkluterREPO_NAMEMLGPATH_START.@MLG_extracted@MLG-master@name.py@.PATH_END.py
{ "filename": "_tickformatstopdefaults.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/layout/scene/yaxis/_tickformatstopdefaults.py", "type": "Python" }
import _plotly_utils.basevalidators class TickformatstopdefaultsValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="tickformatstopdefaults", parent_name="layout.scene.yaxis", **kwargs, ): super(TickformatstopdefaultsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Tickformatstop"), data_docs=kwargs.pop( "data_docs", """ """, ), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@layout@scene@yaxis@_tickformatstopdefaults.py@.PATH_END.py
{ "filename": "main.py", "repo_name": "cdslaborg/paramonte", "repo_path": "paramonte_extracted/paramonte-main/example/fortran/pm_distExpGamma/getExpGammaLogPDF/main.py", "type": "Python" }
#!/usr/bin/env python import matplotlib.pyplot as plt import pandas as pd import numpy as np import glob import sys fontsize = 17 marker ={ "CK" : "-" , "IK" : "." , "RK" : "-" } xlab = { "CK" : "X ( real/imaginary components )" , "IK" : "X ( integer-valued )" , "RK" : "X ( real-valued )" } legends = [ "$\kappa = 0.5, \log(\sigma) = -.5$" , "$\kappa = 1.0, \log(\sigma) = -.5$" , "$\kappa = 2.0, \log(\sigma) = -.5$" , "$\kappa = 0.5, \log(\sigma) = 2.0$" , "$\kappa = 1.0, \log(\sigma) = 2.0$" , "$\kappa = 2.0, \log(\sigma) = 2.0$" ] for kind in ["IK", "CK", "RK"]: pattern = "*." + kind + ".txt" fileList = glob.glob(pattern) if len(fileList) == 1: df = pd.read_csv(fileList[0], delimiter = " ") fig = plt.figure(figsize = 1.25 * np.array([6.4, 4.8]), dpi = 200) ax = plt.subplot() if kind == "CK": plt.plot( df.values[:, 0] , df.values[:,1:len(legends)+1] , marker[kind] #, color = "r" ) plt.plot( df.values[:, 1] , df.values[:,1:len(legends)+1] , marker[kind] #, color = "blue" ) else: plt.plot( df.values[:, 0] , df.values[:,1:len(legends)+1] , marker[kind] #, color = "r" ) ax.legend ( legends , fontsize = fontsize ) plt.xticks(fontsize = fontsize - 2) plt.yticks(fontsize = fontsize - 2) ax.set_xlabel(xlab[kind], fontsize = 17) ax.set_ylabel("Probability Density Function (PDF)", fontsize = 17) ax.set_xlim([-11.0, 5]) plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-") ax.tick_params(axis = "y", which = "minor") ax.tick_params(axis = "x", which = "minor") plt.savefig(fileList[0].replace(".txt",".png")) elif len(fileList) > 1: sys.exit("Ambiguous file list exists.")
cdslaborgREPO_NAMEparamontePATH_START.@paramonte_extracted@paramonte-main@example@fortran@pm_distExpGamma@getExpGammaLogPDF@main.py@.PATH_END.py
{ "filename": "physics.py", "repo_name": "johannesulf/dsigma", "repo_path": "dsigma_extracted/dsigma-main/dsigma/physics.py", "type": "Python" }
"""Physics functions for the dsigma pipeline.""" import numpy as np from astropy import constants as c from astropy import units as u from scipy.special import jv, jn_zeros from astropy.cosmology import FlatLambdaCDM __all__ = ['mpc_per_degree', 'projection_angle', 'critical_surface_density', 'effective_critical_surface_density', 'lens_magnification_shear_bias'] _sigma_crit_factor = (c.c**2 / (4 * np.pi * c.G)).to(u.Msun / u.pc).value def mpc_per_degree(z, cosmology=FlatLambdaCDM(H0=100, Om0=0.3), comoving=False): """Estimate the angular scale in Mpc/degree at certain redshift. Parameters ---------- cosmology : astropy.cosmology, optional Cosmology to assume for calculations. z : float or numpy.ndarray Redshift of the object. comoving : boolen Use comoving distance instead of physical distance when True. Default: False Returns ------- float or numpy.ndarray Physical scale in unit of Mpc/degree. """ if comoving: return (cosmology.comoving_transverse_distance(z).to(u.Mpc).value * np.deg2rad(1)) return (cosmology.angular_diameter_distance(z).to(u.Mpc).value * np.deg2rad(1)) def projection_angle(ra_l, dec_l, ra_s, dec_s): r"""Calculate projection angle between lens and sources. Parameters ---------- ra_l, dec_l : float or numpy.ndarray Coordinates of the lens galaxies in degrees. ra_s, dec_s : float or numpy.ndarray Coordinates of the source galaxies in degrees. Returns ------- cos_2phi, sin_2phi : float or numpy.ndarray The :math:`\cos` and :math:`\sin` of :math:`2 \phi`, where :math:`\phi` is the angle measured from right ascension direction to a line connecting the lens and source galaxies. """ # Convert everything into radians. ra_l, dec_l = np.deg2rad(ra_l), np.deg2rad(dec_l) ra_s, dec_s = np.deg2rad(ra_s), np.deg2rad(dec_s) # Calculate the tan(phi). mask = np.cos(dec_s) * np.sin(ra_s - ra_l) != 0 if hasattr(mask, "__len__"): tan_phi = ( (np.cos(dec_l) * np.sin(dec_s) - np.sin(dec_l) * np.cos(dec_s) * np.cos(ra_s - ra_l))[mask] / (np.cos(dec_s) * np.sin(ra_s - ra_l))[mask]) cos_2phi = np.repeat(-1.0, len(mask)) sin_2phi = np.repeat(0.0, len(mask)) cos_2phi[mask] = (2.0 / (1.0 + tan_phi * tan_phi)) - 1.0 sin_2phi[mask] = 2.0 * tan_phi / (1.0 + tan_phi * tan_phi) elif mask: tan_phi = ( (np.cos(dec_l) * np.sin(dec_s) - np.sin(dec_l) * np.cos(dec_s) * np.cos(ra_s - ra_l)) / (np.cos(dec_s) * np.sin(ra_s - ra_l))) cos_2phi = (2.0 / (1.0 + tan_phi * tan_phi)) - 1.0 sin_2phi = (2.0 * tan_phi / (1.0 + tan_phi * tan_phi)) else: cos_2phi = -1 sin_2phi = 0 return cos_2phi, sin_2phi def critical_surface_density(z_l, z_s, cosmology=None, comoving=True, d_l=None, d_s=None): """Compute the critical surface density. Parameters ---------- z_l : float or numpy.ndarray Redshift of lens. z_s : float or numpy.ndarray Redshift of source. cosmology : astropy.cosmology, optional Cosmology to assume for calculations. Only used if comoving distances are not passed. comoving : boolean, optional Flag for using comoving instead of physical units. d_l : float or numpy.ndarray Comoving transverse distance to the lens. If not given, it is calculated from the redshift provided. d_s : float or numpy.ndarray Comoving transverse distance to the source. If not given, it is calculated from the redshift provided. Returns ------- sigma_crit : float or numpy.ndarray Critical surface density for each lens-source pair. """ if d_l is None: d_l = cosmology.comoving_transverse_distance(z_l).to(u.Mpc).value if d_s is None: d_s = cosmology.comoving_transverse_distance(z_s).to(u.Mpc).value dist_term = (1e-6 * (d_s / (1 + z_s)) / (d_l / (1 + z_l)) / (np.where(d_s > d_l, d_s - d_l, 1) / (1 + z_s))) if np.isscalar(dist_term): if d_s <= d_l: dist_term = np.inf else: dist_term[d_s <= d_l] = np.inf if comoving: dist_term /= (1.0 + z_l)**2 return _sigma_crit_factor * dist_term def effective_critical_surface_density(z_l, z_s, n_s, cosmology, comoving=True): """Compute the effective critical surface density. Parameters ---------- z_l : float or numpy.ndarray Redshift of lens. z_s : numpy.ndarray Redshifts of sources. n_s : numpy.ndarray Fraction of source galaxies in each redshift bin. Does not need to be normalized. cosmology : astropy.cosmology Cosmology to assume for calculations. comoving : boolean, optional Flag for using comoving instead of physical unit. Returns ------- sigma_crit_eff : float or numpy.ndarray Effective critical surface density for the lens redshift given the source redshift distribution. """ d_l = cosmology.comoving_transverse_distance(z_l).to(u.Mpc).value d_s = cosmology.comoving_transverse_distance(z_s).to(u.Mpc).value if not np.isscalar(z_l): z_l = np.repeat(z_l, len(z_s)).reshape((len(z_l), len(z_s))) d_l = np.repeat(d_l, len(z_s)).reshape(z_l.shape) z_s = np.tile(z_s, len(z_l)).reshape(z_l.shape) d_s = np.tile(d_s, len(z_l)).reshape(z_l.shape) n_s = np.tile(n_s, len(z_l)).reshape(z_l.shape) sigma_crit = critical_surface_density(z_l, z_s, cosmology=cosmology, comoving=comoving, d_l=d_l, d_s=d_s) if not np.isscalar(z_l): sigma_crit_eff = np.repeat(np.inf, len(z_l)) mask = np.average(sigma_crit**-1, axis=-1, weights=n_s) == 0 sigma_crit_eff[~mask] = np.average(sigma_crit**-1, axis=-1, weights=n_s)[~mask]**-1 return sigma_crit_eff else: if np.average(sigma_crit**-1, weights=n_s) > 0: return np.average(sigma_crit**-1, weights=n_s)**-1 else: return np.inf def lens_magnification_shear_bias(theta, alpha_l, z_l, z_s, camb_results, n_z=10, n_ell=200, bessel_function_zeros=100, k_max=1e3): r"""Compute the lens magnification bias to the mean tangential shear. This function is based on equations (13) and (14) in Unruh et al. (2020). Parameters ---------- theta : float or astropy.units.quantity.Quantity Angular separation :math:`\theta` from the lens sample. If not quantity is given, the separation is assumed to be in radians. alpha_l : float Local slope of the flux distribution of lenses near the flux limit. z_l : float Redshift of lens. z_s : float Redshift of source. camb_results : camb.results.CAMBdata CAMB results object that contains information on cosmology and the matter power spectrum. n_z : int, optional Number of redshift bins used in the integral. Larger numbers will be more accurate. n_ell : int, optional Number of :math:`\ell` bins used in the integral. Larger numbers will be more accurate. bessel_function_zeros : int, optional The calculation involves an integral over the second order Bessel function :math:`J_2 (\ell \theta)` from :math:`\ell = 0` to :math:`\ell = \infty`. In practice, this function replaces the upper bound with the bessel_function_zeros-th zero point of the Bessel function. Larger number should lead to more accurate results. However, in practice, this also requires larger `n_ell`. Particularly, `n_ell` should never fall below `bessel_function_zeros`. k_max : float, optional The maximum wavenumber beyond which the power spectrum is assumed to be 0. Returns ------- et_lm : float Bias in the mean tangential shear due to lens magnification effects. """ camb_interp = camb_results.get_matter_power_interpolator( hubble_units=False, k_hunit=False) if not isinstance(theta, u.quantity.Quantity): theta = theta * u.rad theta = theta.to(u.rad).value ell_min = 0 ell_max = np.amax(jn_zeros(2, bessel_function_zeros)) / theta z_min = 0 z_max = min(z_l, z_s) z, w_z = np.polynomial.legendre.leggauss(n_z) z = (z_max - z_min) / 2.0 * z + (z_max + z_min) / 2.0 w_z = w_z * (z_max - z_min) / 2.0 ell, w_ell = np.polynomial.legendre.leggauss(n_ell) ell = (ell_max - ell_min) / 2.0 * ell + (ell_max + ell_min) / 2.0 w_ell = w_ell * (ell_max - ell_min) / 2.0 int_z = np.array([ (1 + z_i)**2 / (2 * np.pi) * camb_results.hubble_parameter(0) / camb_results.hubble_parameter(z_i) * camb_results.angular_diameter_distance2(z_i, z_l) * camb_results.angular_diameter_distance2(z_i, z_s) / camb_results.angular_diameter_distance(z_l) / camb_results.angular_diameter_distance(z_s) for z_i in z]) d_ang = np.array([ camb_results.angular_diameter_distance(z_i) for z_i in z]) z = np.tile(z, n_ell) int_z = np.tile(int_z, n_ell) d_ang = np.tile(d_ang, n_ell) w_z = np.tile(w_z, n_ell) int_ell = ell * jv(2, ell * theta) ell = np.repeat(ell, n_z) int_ell = np.repeat(int_ell, n_z) w_ell = np.repeat(w_ell, n_z) k = (ell + 0.5) / ((1 + z) * d_ang) int_z_ell = np.array([camb_interp.P(z[i], k[i]) for i in range(len(k))]) int_z_ell = np.where(k > k_max, 0, int_z_ell) gamma = np.sum(int_z * int_ell * int_z_ell * w_z * w_ell) gamma = ((gamma * u.Mpc**3) * 9 * camb_results.Params.H0**3 * u.km**3 / u.s**3 / u.Mpc**3 * (camb_results.Params.omch2 + camb_results.Params.ombh2)**2 / (camb_results.Params.H0 / 100)**4 / 4 / c.c**3) return 2 * (alpha_l - 1) * gamma.to(u.dimensionless_unscaled).value
johannesulfREPO_NAMEdsigmaPATH_START.@dsigma_extracted@dsigma-main@dsigma@physics.py@.PATH_END.py
{ "filename": "nse.py", "repo_name": "nuc-astro/winnet", "repo_path": "winnet_extracted/winnet-master/test/nse.py", "type": "Python" }
#!/usr/bin/env python t.checklist = { \ 'finab.dat' : { 'method':'default', 'tolerance':2.0e-4 }, \ } t.program = t.basedir + "/bin/winnet" t.testdir = t.basedir + "/test/" + t.testname t.logfile = t.testdir + ".log" t.arcfile = t.testdir + ".tar.gz"
nuc-astroREPO_NAMEwinnetPATH_START.@winnet_extracted@winnet-master@test@nse.py@.PATH_END.py
{ "filename": "_tracerefminus.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/scatter/error_y/_tracerefminus.py", "type": "Python" }
import _plotly_utils.basevalidators class TracerefminusValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="tracerefminus", parent_name="scatter.error_y", **kwargs ): super(TracerefminusValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), min=kwargs.pop("min", 0), role=kwargs.pop("role", "info"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@scatter@error_y@_tracerefminus.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "joezuntz/cosmosis", "repo_path": "cosmosis_extracted/cosmosis-main/cosmosis/samplers/pmc/__init__.py", "type": "Python" }
joezuntzREPO_NAMEcosmosisPATH_START.@cosmosis_extracted@cosmosis-main@cosmosis@samplers@pmc@__init__.py@.PATH_END.py
{ "filename": "_opacity.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scattermap/selected/marker/_opacity.py", "type": "Python" }
import _plotly_utils.basevalidators class OpacityValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="opacity", parent_name="scattermap.selected.marker", **kwargs ): super(OpacityValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), max=kwargs.pop("max", 1), min=kwargs.pop("min", 0), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scattermap@selected@marker@_opacity.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "JulianBMunoz/RelicFast", "repo_path": "RelicFast_extracted/RelicFast-master/CAMB_Current/pycamb/camb/__init__.py", "type": "Python" }
# coding: utf8 """ Python CAMB interface (http://camb.info) """ __author__ = "Antony Lewis" __contact__ = "antony at cosmologist dot info" __status__ = "beta" __version__ = "0.1.6.1" from .baseconfig import dll_import from .camb import CAMBdata, MatterTransferData, get_results, get_transfer_functions, get_background, \ get_age, get_zre_from_tau, set_z_outputs, set_feedback_level, set_params, get_matter_power_interpolator, \ set_custom_scalar_sources, clear_custom_scalar_sources from . import model from . import initialpower from . import reionization from .nonlinear import set_halofit_version from .model import CAMBparams, TransferParams from .reionization import ReionizationParams from .initialpower import InitialPowerParams from .bispectrum import threej from ctypes import c_int, c_double, c_bool ThreadNum = dll_import(c_int, "modelparams", "threadnum") # ThreadNum.value = 0 # Variables from module GaugeInterface DoTensorNeutrinos = dll_import(c_bool, "gaugeinterface", "dotensorneutrinos") # DoTensorNeutrinos.value = True Magnetic = dll_import(c_double, "gaugeinterface", "magnetic") # Magnetic.value = 0. vec_sig0 = dll_import(c_double, "gaugeinterface", "vec_sig0") # vec_sig0.value = 1.
JulianBMunozREPO_NAMERelicFastPATH_START.@RelicFast_extracted@RelicFast-master@CAMB_Current@pycamb@camb@__init__.py@.PATH_END.py
{ "filename": "overview.md", "repo_name": "dmentipl/plonk", "repo_path": "plonk_extracted/plonk-main/docs/source/getting-started/overview.md", "type": "Markdown" }
# Overview ```{eval-rst} .. currentmodule:: plonk ``` This document gives an overview of using Plonk for analysis and visualization of smoothed particle hydrodynamics data. For a further guide see {doc}`../../user-guide/usage`. ```{toctree} :maxdepth: 1 overview/data overview/visualization overview/analysis ``` ```{important} To follow along, download the sample data `plonk_example_data.tar` from [figshare](https://figshare.com/articles/dataset/Plonk_example_dataset/12885587). Then extract with `tar xvf plonk_example_data.tar` and change into the `plonk_example_data` directory. This data set is from a Phantom simulation of a dust and gas protoplanetary disc with an embedded protoplanet. ``` ## Data file formats Plonk supports the following SPH file formats: - Phantom output in [HDF](https://en.wikipedia.org/wiki/Hierarchical_Data_Format) form (as opposed to the sphNG-based Fortran binary format). ```{note} HDF5 output was added to Phantom as an option with git commit [9b22ded](https://github.com/danieljprice/phantom/commit/9b22ded9e7b4d512966f2b2e4b84d693b1afc9e6) on the 14th of March 2019. See the [Phantom documentation](https://phantomsph.readthedocs.io/) for instructions on how to compile with HDF5 output and to convert from the sphNG-based output. ```
dmentiplREPO_NAMEplonkPATH_START.@plonk_extracted@plonk-main@docs@source@getting-started@overview.md@.PATH_END.py
{ "filename": "migrate-to-maplibre.md", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/doc/python/migrate-to-maplibre.md", "type": "Markdown" }
--- jupyter: jupytext: notebook_metadata_filter: all text_representation: extension: .md format_name: markdown format_version: '1.3' jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 language_info: codemirror_mode: name: ipython version: 3 file_extension: .py mimetype: text/x-python name: python nbconvert_exporter: python pygments_lexer: ipython3 version: 3.10.11 plotly: description: Migrating from Mapbox traces to MapLibre traces. display_as: maps language: python layout: base name: MapLibre Migration order: 1 page_type: u-guide permalink: python/mapbox-to-maplibre/ redirect_from: python/maplibre-migration/ thumbnail: thumbnail/mapbox-layers.png --- ## Migrating from Mapbox traces to MapLibre traces With the release of Plotly.py v5.24.0, we are introducing a new set of trace types for maps with tile underlays, including from Plotly Express: - `px.scatter_map` - `px.line_map` - `px.choropleth_map` - `px.density_map` as well as Plotly Graph Objects: - `go.Choroplethmap` - `go.Scattermap` - `go.Densitymap` These traces replace the existing Mapbox traces, `px.scatter_mapbox`, `px.line_mapbox`, etc., but use [MapLibre](https://maplibre.org) as the map renderer rather than Mapbox. When switching to the new traces, keep an eye out for improved rendering performance, WebGL2 support, and over time, improved features in the Plotly map traces inherited from the MapLibre renderer, including projection support, globe views, terrain support, and support for modern mapping standards. You can learn more about the motivations for this change in our [announcement post](https://plotly.com/blog/plotly-is-switching-to-maplibre/). As a result of removing Mapbox as the rendering engine, we're also removing the Mapbox branding from these trace names. This means that migrating from Mapbox traces to MapLibre traces will require some code changes in your projects. 1. Change trace names from `*mapbox` to `*map`. For any existing trace name ending in `*mapbox`, ensure you've removed the "`box`" suffix. 2. If in use, update `layout.mapbox` argument in your layout configuration to `layout.map`. The nested properties are identical in the new map traces, so no other changes should be required. 3. If in use, update `mapbox_style` to `map_style`. 4. Verify your `map_style` settings. With `mapbox` traces, we bundle `basic`, `streets`, `outdoors`, `light`, `dark`, `satellite`, and `satellite-streets` styles, using Mapbox styling. These style names are still available, but they now reference slightly different styles provided by other tools. Note that Mapbox API keys are no longer required for Plotly-provided styles, but using external styles in your Plotly maps remains supported with the existing API. ### Style changes Built-in styles in map traces are free styles from [Carto](https://carto.com) and [ESRI](https://www.esri.com/en-us/home). Several names are re-used from the previous Mapbox styles. <p align="center"> <img src="https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/baselines/map_predefined-styles1.png" alt="Style comparison part 1" width="45%" /> <img src="https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/baselines/map_predefined-styles2.png" alt="Style comparison part 2" width="45%" /> </p> Compare to the previous Mapbox styles: <p align="center"> <img src="https://raw.githubusercontent.com/plotly/graphing-library-docs/master/all_static/images/mapbox_1.png" alt="Style comparison part 1" width="45%" /> <img src="https://raw.githubusercontent.com/plotly/graphing-library-docs/master/all_static/images/mapbox_2.png" alt="Style comparison part 2" width="45%" /> </p>
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@doc@python@migrate-to-maplibre.md@.PATH_END.py
{ "filename": "_templateitemname.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/layout/xaxis/tickformatstop/_templateitemname.py", "type": "Python" }
import _plotly_utils.basevalidators class TemplateitemnameValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="templateitemname", parent_name="layout.xaxis.tickformatstop", **kwargs, ): super(TemplateitemnameValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@layout@xaxis@tickformatstop@_templateitemname.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "RadioAstronomySoftwareGroup/pyuvdata", "repo_path": "pyuvdata_extracted/pyuvdata-main/tests/uvbeam/__init__.py", "type": "Python" }
# Copyright (c) 2019 Radio Astronomy Software Group # Licensed under the 2-clause BSD License
RadioAstronomySoftwareGroupREPO_NAMEpyuvdataPATH_START.@pyuvdata_extracted@pyuvdata-main@tests@uvbeam@__init__.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "google/jax", "repo_path": "jax_extracted/jax-main/jaxlib/README.md", "type": "Markdown" }
# jaxlib: support library for JAX jaxlib is the support library for JAX. While JAX itself is a pure Python package, jaxlib contains the binary (C/C++) parts of the library, including Python bindings, the XLA compiler, the PJRT runtime, and a handful of handwritten kernels. For more information, including installation and build instructions, refer to main JAX README: https://github.com/jax-ml/jax/.
googleREPO_NAMEjaxPATH_START.@jax_extracted@jax-main@jaxlib@README.md@.PATH_END.py
{ "filename": "conftest.py", "repo_name": "tardis-sn/tardis", "repo_path": "tardis_extracted/tardis-main/tardis/montecarlo/tests/conftest.py", "type": "Python" }
import os import pytest from tardis.io import config_reader from ctypes import ( CDLL, byref, c_int64, c_double, c_ulong, ) from tardis.montecarlo.struct import ( RPacket, StorageModel, RKState, TARDIS_PACKET_STATUS_IN_PROCESS, CONTINUUM_OFF, BoundFreeTreatment, ) from tardis.montecarlo.base import MontecarloRunner @pytest.fixture(scope="function") def packet(): """Fixture to return `RPacket` object with default params initialized.""" return RPacket( nu=0.4, mu=0.3, energy=0.9, r=7.5e14, tau_event=2.9e13, nu_line=0.2, current_shell_id=0, next_line_id=1, last_line=0, close_line=0, current_continuum_id=1, virtual_packet_flag=1, virtual_packet=0, next_shell_id=1, status=TARDIS_PACKET_STATUS_IN_PROCESS, id=0, chi_cont=6.652486e-16, chi_bf_tmp_partial=(c_double * 2)(), compute_chi_bf=True, vpacket_weight=1.0, ) @pytest.fixture(scope="function") def model(): """ Fixture to return `StorageModel` object with default params initialized. """ return StorageModel( last_line_interaction_in_id=(c_int64 * 2)(*([0] * 2)), last_line_interaction_shell_id=(c_int64 * 2)(*([0] * 2)), last_interaction_type=(c_int64 * 2)(*([2])), last_interaction_out_type=(c_int64 * 1)(*([0])), no_of_shells=2, r_inner=(c_double * 2)(*[6.912e14, 8.64e14]), r_outer=(c_double * 2)(*[8.64e14, 1.0368e15]), time_explosion=5.2e7, inverse_time_explosion=1 / 5.2e7, electron_densities=(c_double * 2)(*[1.0e9] * 2), inverse_electron_densities=(c_double * 2)(*[1.0e-9] * 2), line_list_nu=(c_double * 5)( *[ 1.26318289e16, 1.26318289e16, 1.23357675e16, 1.23357675e16, 1.16961598e16, ] ), continuum_list_nu=(c_double * 2)(*([1.0e13] * 2)), line_lists_tau_sobolevs=(c_double * 1000)(*([1.0e-5] * 1000)), line_lists_j_blues=(c_double * 2)(*([1.0e-10] * 2)), line_lists_j_blues_nd=0, # Init to an explicit array line_lists_Edotlu=(c_double * 3)(*[0.0, 0.0, 1.0]), no_of_lines=5, no_of_edges=2, line_interaction_id=0, line2macro_level_upper=(c_int64 * 2)(*([0] * 2)), js=(c_double * 2)(*([0.0] * 2)), nubars=(c_double * 2)(*([0.0] * 2)), spectrum_start_nu=1.0e14, spectrum_delta_nu=293796608840.0, spectrum_end_nu=6.0e15, spectrum_virt_start_nu=1e14, spectrum_virt_end_nu=6e15, spectrum_virt_nu=(c_double * 20000)(*([0.0] * 20000)), sigma_thomson=6.652486e-25, inverse_sigma_thomson=1 / 6.652486e-25, inner_boundary_albedo=0.0, reflective_inner_boundary=0, chi_ff_factor=(c_double * 2)(*([1.0] * 2)), t_electrons=(c_double * 2)(*([1.0e4] * 2)), l_pop=(c_double * 20000)(*([2.0] * 20000)), l_pop_r=(c_double * 20000)(*([3.0] * 20000)), cont_status=CONTINUUM_OFF, bf_treatment=BoundFreeTreatment.LIN_INTERPOLATION.value, ff_heating_estimator=(c_double * 2)(*([0.0] * 2)), cont_edge2macro_level=(c_int64 * 6)(*([1] * 6)), survival_probability=0.0, tau_russian=10.0, tau_bias=(c_double * 3)(*([5.0, 0.5, 0.0])), enable_biasing=0, ) @pytest.fixture(scope="function") def mt_state(): """Fixture to return `RKState` object with default params initialized.""" return RKState( key=(c_ulong * 624)(*([0] * 624)), pos=0, has_gauss=0, gauss=0.0 ) @pytest.fixture(scope="function") def mt_state_seeded(clib, mt_state): seed = 23111963 clib.rk_seed(seed, byref(mt_state)) return mt_state @pytest.fixture(scope="function") def runner(): config_fname = "tardis/io/tests/data/tardis_configv1_verysimply.yml" config = config_reader.Configuration.from_yaml(config_fname) runner = MontecarloRunner.from_config(config) return runner
tardis-snREPO_NAMEtardisPATH_START.@tardis_extracted@tardis-main@tardis@montecarlo@tests@conftest.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "Nikhel1/Gal-DINO", "repo_path": "Gal-DINO_extracted/Gal-DINO-main/models/dino/ops/functions/__init__.py", "type": "Python" }
# ------------------------------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------------------------------ # Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0 # ------------------------------------------------------------------------------------------------ from .ms_deform_attn_func import MSDeformAttnFunction
Nikhel1REPO_NAMEGal-DINOPATH_START.@Gal-DINO_extracted@Gal-DINO-main@models@dino@ops@functions@__init__.py@.PATH_END.py
{ "filename": "_range.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/layout/polar/radialaxis/_range.py", "type": "Python" }
import _plotly_utils.basevalidators class RangeValidator(_plotly_utils.basevalidators.InfoArrayValidator): def __init__( self, plotly_name="range", parent_name="layout.polar.radialaxis", **kwargs ): super(RangeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, anim=kwargs.pop("anim", True), edit_type=kwargs.pop("edit_type", "plot"), implied_edits=kwargs.pop("implied_edits", {"autorange": False}), items=kwargs.pop( "items", [ { "valType": "any", "editType": "plot", "impliedEdits": {"^autorange": False}, }, { "valType": "any", "editType": "plot", "impliedEdits": {"^autorange": False}, }, ], ), role=kwargs.pop("role", "info"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@layout@polar@radialaxis@_range.py@.PATH_END.py
{ "filename": "simple_radial_profile.py", "repo_name": "yt-project/yt", "repo_path": "yt_extracted/yt-main/doc/source/cookbook/simple_radial_profile.py", "type": "Python" }
import yt # Load the dataset. ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") # Create a sphere of radius 100 kpc in the center of the box. my_sphere = ds.sphere("c", (100.0, "kpc")) # Create a profile of the average density vs. radius. plot = yt.ProfilePlot( my_sphere, ("index", "radius"), ("gas", "density"), weight_field=("gas", "mass"), ) # Change the units of the radius into kpc (and not the default in cgs) plot.set_unit(("index", "radius"), "kpc") # Save the image. # Optionally, give a string as an argument # to name files with a keyword. plot.save()
yt-projectREPO_NAMEytPATH_START.@yt_extracted@yt-main@doc@source@cookbook@simple_radial_profile.py@.PATH_END.py
{ "filename": "velociraptor_test.py", "repo_name": "pynbody/pynbody", "repo_path": "pynbody_extracted/pynbody-master/tests/velociraptor_test.py", "type": "Python" }
import numpy as np import pytest import pynbody import pynbody.test_utils @pytest.fixture(scope='module', autouse=True) def get_data(): pynbody.test_utils.ensure_test_data_available("swift") @pytest.mark.parametrize("load_all", [True, False]) def test_swift_velociraptor(load_all): f = pynbody.load("testdata/SWIFT/snap_0150.hdf5") assert pynbody.halo.velociraptor.VelociraptorCatalogue._can_load(f) h = pynbody.halo.velociraptor.VelociraptorCatalogue(f) if load_all: h.load_all() assert len(h) == 209 assert len(h[1]) == 443 assert len(h[1].dm) == 246 assert len(h[1].gas) == 197 h_unbound = pynbody.halo.velociraptor.VelociraptorCatalogue(f, include_unbound=True) if load_all: h_unbound.load_all() assert len(h_unbound[1]) == 444 testvals = [395183, 411313, 394929, 386993, 419631, 402993, 411571, 395313, 386865, 419505, 411439, 419503, 395059, 395187, 419507, 402995, 411437, 395057, 395315, 411565, 419635, 403121, 403377, 419633, 403253, 411443, 411441, 395185, 403123, 403251, 403371, 403507, 395181, 403509, 419761, 411183, 403117, 411185, 419629, 411697, 411445, 395053, 411573, 419763, 411317, 403373, 395055, 403255, 386995, 411435, 411311, 411569, 411309, 403247, 411563, 403125, 419759, 403245, 395061, 411567, 419500, 394922, 386608, 395050, 394932, 403124, 411444, 403254, 395182, 411186, 402988, 411566, 419630, 411312, 386862, 403376, 411442, 419632, 419502, 403244, 411316, 394928, 386990, 402992, 395056, 394924, 403246, 386994, 403122, 402990, 395060, 395186, 395054, 386864, 394800, 403374, 386866, 395184, 403250, 395058, 403248, 386992, 403252, 411564, 386738, 411436, 411562, 419504, 395310, 403116, 403372, 403370, 411438, 411568, 411314, 403120, 411310, 419628, 411182, 411570, 394930, 395314, 411440, 411308, 386736, 402994, 419634, 411306, 386860, 411434, 395188, 403118, 395180, 394798, 419506, 411184, 403378, 402986] assert (np.sort(h[20]['iord']) == np.sort(testvals)).all() @pytest.mark.filterwarnings("ignore:Accessing multiple halos") @pytest.mark.parametrize("use_all", [True, False]) def test_swift_velociraptor_parents_and_children(use_all): f = pynbody.load("testdata/SWIFT/snap_0150.hdf5") h = pynbody.halo.velociraptor.VelociraptorCatalogue(f) if use_all: properties = h.get_properties_all_halos() getter = lambda k, i: properties[k][h.number_mapper.number_to_index(i)] else: getter = lambda k, i: h[i].properties[k] assert getter('parent', 2) == -1 assert (getter('children', 2) == [208]).all() assert getter('parent', 208) == 2 assert (getter('children', 3) == [209]).all() assert getter('parent', 209) == 3 # the above were from the genuine velociraptor output. But since these were the only subhalos, the test was # a bit too trivial. The following are some faked subhalos to test a more complex scenario assert (getter('children', 1) == [203, 204, 206]).all() assert (getter('children', 4) == [205, 207]).all() assert getter('parent', 203) == 1 @pytest.mark.filterwarnings("ignore:Accessing multiple halos") @pytest.mark.parametrize("load_all", [True, False]) def test_swift_velociraptor_properties(load_all): f = pynbody.load("testdata/SWIFT/snap_0150.hdf5") h = pynbody.halo.velociraptor.VelociraptorCatalogue(f) if load_all: h.load_all() assert np.allclose(float(h[1].properties['Lx']), -90787.3983020414e13) assert np.allclose(float(h[10].properties['Lx']), -73881.83861892551e13) assert np.allclose(h[1].properties['Lx'].ratio("1e13 kpc Msol km s**-1"), -90787.3983020414) @pytest.mark.parametrize("with_units", [True, False]) def test_swift_velociraptor_all_properties(with_units): f = pynbody.load("testdata/SWIFT/snap_0150.hdf5") h = pynbody.halo.velociraptor.VelociraptorCatalogue(f) all_properties = h.get_properties_all_halos(with_units=with_units) assert np.allclose(all_properties['Lx'][0], -90787.3983020414) assert np.allclose(all_properties['Lx'][9], -73881.83861892551) if with_units: assert all_properties['Lx'].units == '1e13 kpc Msol km s**-1' else: assert not hasattr(all_properties['Lx'], 'units') def test_swift_velociraptor_select_catalogue_with_filename(): f = pynbody.load("testdata/SWIFT/snap_0150.hdf5") h = f.halos(filename="testdata/SWIFT/catalogue_0150/output") assert isinstance(h, pynbody.halo.velociraptor.VelociraptorCatalogue) h.load_all() assert len(h) == 209
pynbodyREPO_NAMEpynbodyPATH_START.@pynbody_extracted@pynbody-master@tests@velociraptor_test.py@.PATH_END.py
{ "filename": "test_c_sockets_implementation.py", "repo_name": "amusecode/amuse", "repo_path": "amuse_extracted/amuse-main/src/amuse/test/suite/compile_tests/test_c_sockets_implementation.py", "type": "Python" }
from amuse.support.interface import InCodeComponentImplementation from amuse.test.amusetest import TestWithMPI from amuse.support import exceptions from amuse.support import options import os import time from amuse.units import nbody_system from amuse.units import units from amuse import datamodel from amuse.rfi.tools import create_c from amuse.rfi import channel from amuse.rfi.core import * from . import test_c_implementation class TestCSocketsImplementationInterface(test_c_implementation.TestCImplementationInterface): @classmethod def setup_class(cls): cls.check_not_in_mpiexec() super(TestCSocketsImplementationInterface, cls).setup_class() # set sockets channel as default channel options.GlobalOptions.instance().override_value_for_option("channel_type", "sockets") @classmethod def teardown_class(cls): del options.GlobalOptions.instance().overriden_options["channel_type"] def test22(self): self.skip("this test uses mpi internals, skip here") def test29(self): self.skip("this test uses mpi internals, skip here") @classmethod def check_not_in_mpiexec(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ if 'HYDI_CONTROL_FD' in os.environ: return # for now assume HYDI_CONTROL_FD is newer, and sockets will work! if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: cls.skip('cannot run the socket tests under mpi process manager')
amusecodeREPO_NAMEamusePATH_START.@amuse_extracted@amuse-main@src@amuse@test@suite@compile_tests@test_c_sockets_implementation.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/waterfall/decreasing/marker/__init__.py", "type": "Python" }
import sys if sys.version_info < (3, 7): from ._line import LineValidator from ._color import ColorValidator else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name__, [], ["._line.LineValidator", "._color.ColorValidator"] )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@waterfall@decreasing@marker@__init__.py@.PATH_END.py
{ "filename": "SDSS.py", "repo_name": "mjuric/lsd", "repo_path": "lsd_extracted/lsd-master/src/lsd/builtins/SDSS.py", "type": "Python" }
import os from .misc import FileTable class RunToMJD(object): def __init__(self, runlist=None): if runlist is None: runlist = os.getenv('SDSS_RUNLIST', None) if runlist is None: from .. import config runlist = os.path.join(config.data_dir, 'sdss', 'opRunlist.par') self.run2mjd = FileTable(runlist).map('run', 'mjd_ref', 'field_ref') def __call__(self, run, field=0, rowc=0): data = self.run2mjd(run) offs_obj = rowc * 0.396 / (360.985647 * 3600.) offs_fld = 36*(field - data['field_ref']) / (24.*3600.) halfexp = (53.907456 / 2.) / (24.*3600.) mjd = data['mjd_ref'] + offs_fld + offs_obj - halfexp return mjd from ..utils import LazyCreate mjd_obs = LazyCreate(RunToMJD)
mjuricREPO_NAMElsdPATH_START.@lsd_extracted@lsd-master@src@lsd@builtins@SDSS.py@.PATH_END.py
{ "filename": "_outlinewidth.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/streamtube/colorbar/_outlinewidth.py", "type": "Python" }
import _plotly_utils.basevalidators class OutlinewidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="outlinewidth", parent_name="streamtube.colorbar", **kwargs ): super(OutlinewidthValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@streamtube@colorbar@_outlinewidth.py@.PATH_END.py
{ "filename": "setup-mpf.py", "repo_name": "dstndstn/tractor", "repo_path": "tractor_extracted/tractor-main/tractor/setup-mpf.py", "type": "Python" }
from distutils.core import setup, Extension import numpy import os numpy_inc = [numpy.get_include()] cflags = os.environ.get('CFLAGS') kwargs = {} if os.environ.get('CC') == 'icc': if cflags is None: cflags = '-g -xhost -axMIC-AVX512' else: print('mp_fourier: using user-specified CFLAGS') cflags = cflags.split() kwargs.update(extra_compile_args=cflags, extra_link_args=['-g', '-lsvml']) else: if cflags is None: cflags = '-std=c99' else: cflags = cflags = cflags.split() kwargs.update(extra_compile_args=cflags) kwargs.update(extra_link_args=['-g']) mpf_module = Extension('_mp_fourier', sources = ['mp_fourier.i' ], include_dirs = numpy_inc, **kwargs) setup(name = 'Gaussian mixtures -- Fourier transform', version = '1.0', description = '', author = 'Lang & Hogg', author_email = 'dstndstn@gmail.com', url = 'http://astrometry.net', ext_modules = [mpf_module])
dstndstnREPO_NAMEtractorPATH_START.@tractor_extracted@tractor-main@tractor@setup-mpf.py@.PATH_END.py
{ "filename": "WaveToy.py", "repo_name": "zachetienne/nrpytutorial", "repo_path": "nrpytutorial_extracted/nrpytutorial-master/CarpetX/WaveToy.py", "type": "Python" }
import os import sys import re import grid from cactusthorn import CactusThorn, loop from sympy import sympify, sin, cos, pi import NRPy_param_funcs as par from subprocess import call import numpy as np from fstr import f from outputC import lhrh par.set_parval_from_str("outputC::PRECISION", "CCTK_REALVEC") pre_kernel = """ #include <iostream> #include <cmath> const int nx = 10, ny = 10; int mask; using std::cos; using std::sin; typedef double CCTK_REALVEC; struct PointDesc { static constexpr int DI[3]={0,0,0}; double x,y,dx=.01,dy=.02; int I=0; }; namespace Arith { template<typename T> double iota() { return T(0); } } struct GF { double data; double& operator()(int n) { return data; } double& operator()(int n,int p) { return data; } double& operator()(int n,int l,int p) { return data; } }; double cctk_delta_space[3] = {.5, .4}; inline double CCTK_DELTA_SPACE(int n) { return cctk_delta_space[n]; } int main() { int VVC_index = 0; int CCC_index = 0; int VVC_tmp_index = 0; int VVC_layout = 0; GF uuGF, vvGF, anaGF, rhs_uuGF, rhs_vvGF, tmp1v, tmp0v, regrid_error; PointDesc p; double cctk_time = 0; double wave_speed = .4; for(int i=0;i<nx;i++) { for(int j=0;j<ny;j++) { const double invdx0 = 1 / CCTK_DELTA_SPACE(0); const double invdx1 = 1 / CCTK_DELTA_SPACE(1); uuGF(0) = .25 + .01*i - .015*j; vvGF(0) = .33 - .015*i + .015*j; // Begin test.cc """ post_kernel=""" // End test.cc std::cout << anaGF(0) << std::endl; } } return 0; }""" def before_main(): # Init environment os.environ["CACTUS_HOME"]="Cactus" os.environ["CACTUS_DRIVER"]="CarpetX" # Trick CactusThorn into believing this is a real install try: os.makedirs("Cactus/arrangements/CarpetX/CarpetX") #,exist_ok=True) except OSError as oe: pass def after_main_fn(fn): save = False kernel = "" with open(fn, "r") as fd: for line in fd.readlines(): if "Begin NRPy+ Kernel" in line: save = True elif "End NRPy+ Kernel" in line: save = False elif save: kernel += line if kernel == "": return None fc = os.path.join("Cactus","test.cc") with open(fc, "w") as fd: fd.write(f(""" {pre_kernel} {kernel} {post_kernel} """)) test = os.path.join("Cactus","test") testc = test + ".cc" testo = test + "-out.txt" r = call(["g++","-std=c++17","-D_USE_MATH_DEFINES","-o",test,testc]) if r != 0: raise Exception(f("Compile failure of {testc} while processing "+fn)) with open(testo,"w") as fd: call([test],stdout=fd) data = np.genfromtxt(testo,encoding="ascii") g = re.match(r'.*\bwave_(.*)\.cc', fn) if g is not None: print("Setting:",g.group(1)) globals()[g.group(1)] = [float(ff) for ff in data] return data def after_main(): dn = os.path.join("Cactus","arrangements","TestOne","WaveToyNRPy","src") da = [] for fn in os.listdir(dn): data = after_main_fn(os.path.join(dn, fn)) if data is not None: print("File:",fn) da += [data] return da def main(): global par # Current options are Carpet and CarpetX grid.ET_driver = os.environ.get("CACTUS_DRIVER","Carpet") thorn = CactusThorn("TestOne","WaveToyNRPy") #FD_order = thorn.declare_param('FD_order',default=2,vmin=2,vmax=8,doc="The finite difference order") wave_speed = thorn.declare_param('wave_speed',default=1,vmin=.1,vmax=100,doc="The speed of the wave") x0 = thorn.declare_param('x0',default=0,vmin=-100,vmax=100,doc="The x pos of the wave") y0 = thorn.declare_param('y0',default=0,vmin=-100,vmax=100,doc="The y pos of the wave") z0 = thorn.declare_param('z0',default=0,vmin=-100,vmax=100,doc="The z pos of the wave") zero = thorn.declare_param('zero',default=0,vmin=0,vmax=0,doc="zero") centering='VVC' # AUXEVOL needed for the evo, can be freed after evaluating rhs (1 time level) # AUX uu_rhs (1 time level) # EVOL evolved gfs (3 time levels) uu_rhs, vv_rhs = thorn.register_gridfunctions("AUX", ["rhs_uu", "rhs_vv"], centering=centering) uu, vv = thorn.register_gridfunctions("EVOL", ["uu", "vv"], centering=centering) ana = thorn.register_gridfunctions("AUX", ["ana"], centering=centering) cctk_time = par.Cparameters("CCTK_REAL","Cactus",["cctk_time"],0) if grid.ET_driver == "CarpetX": tmp0, tmp1 = thorn.register_gridfunctions("TILE_TMP",["tmp0v","tmp1v"],centering=centering) regrid_error = thorn.get_regrid_error() x,y,z = thorn.get_xyz() import indexedexp as ixp import NRPy_param_funcs as par FD_order = 2 par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER",FD_order) uu_dDD = ixp.declarerank2("uu_dDD","sym01") if grid.ET_driver == "CarpetX": evol_eqns = [ lhrh(lhs=tmp0, rhs=uu_dDD[0][0]), lhrh(lhs=tmp1, rhs=uu_dDD[1][1]), loop, lhrh(lhs=uu_rhs, rhs=vv), lhrh(lhs=vv_rhs, rhs=wave_speed**2*(tmp0 + tmp1)) ] else: # Version of evolution equations without temporaries evol_eqns = [ lhrh(lhs=uu_rhs, rhs=vv), lhrh(lhs=vv_rhs, rhs=wave_speed**2*(uu_dDD[0][0] + uu_dDD[1][1])) ] k = sympify(pi/20) toff = sympify(pi/2) sq2 = sympify(2**.5) init_eqns = [ lhrh(lhs=vv, rhs=sympify(0)), lhrh(lhs=uu, rhs=sin(k*(x))*sin(k*(y))) ] # What is omega? # omega / k = wave_speed anal_eqns = [ lhrh(lhs=ana, rhs=sin(k*x)*sin(k*y)*sin(cctk_time*sq2*wave_speed*k+toff)-uu) ] if grid.ET_driver == "CarpetX": thorn.add_func("refine", body=[lhrh(lhs=regrid_error, rhs=10/((x-20)**2 + (y-20)**2))], doc="do the regrid", schedule_bin="ODESolvers_EstimateError") # access a variable with a different centering using interpolation # looping cell-centered, access vertex-centered, not vice-versa # all rhs variables should have the same centering # wave toy with fluxes, fluxes are faces # schedule something in post-regrid, apply bc's thorn.add_func("wave_init", body=init_eqns, where='everywhere', schedule_bin='initial', doc='Do the wave init', centering=centering) #thorn.add_func("wave_bound", # body=bound_eqns, # where='boundary', # schedule_bin='RHS after wave_evol', # doc='Do the b/c', # centering=centering) thorn.add_func("wave_evol", body=evol_eqns, where='interior', schedule_bin='RHS', doc='Do the wave evol', centering=centering) thorn.add_func("wave_anal", body=anal_eqns, where='everywhere', schedule_bin='Analysis', doc='Check the result', centering=centering) assert "CACTUS_HOME" in os.environ, "Please set the CACTUS_HOME variable to point to your Cactus installation" cactus_home = os.environ["CACTUS_HOME"] cactus_sim = os.environ.get("CACTUS_SIM","sim") cactus_thornlist = os.environ.get("CACTUS_THORNLIST", None) #cactus_home = "/project/sbrandt/release/Cactus" thorn.generate(cactus_home,cactus_config=cactus_sim,cactus_thornlist=cactus_thornlist) def run_all(): before_main() main() after_main() if __name__ == "__main__": main()
zachetienneREPO_NAMEnrpytutorialPATH_START.@nrpytutorial_extracted@nrpytutorial-master@CarpetX@WaveToy.py@.PATH_END.py