def test_if_rctemplate_would_be_valid(tmpdir): # This tests if the matplotlibrc.template file would result in a valid # rc file if all lines are uncommented. path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc') with open(path_to_rc, "r") as f: rclines = f.readlines() newlines = [] for line in rclines: if line[0] == "#": newline = line[1:] else: newline = line if "$TEMPLATE_BACKEND" in newline: newline = "backend : Agg" if "datapath" in newline: newline = "" newlines.append(newline) d = tmpdir.mkdir('test1') fname = str(d.join('testrcvalid.temp')) with open(fname, "w") as f: f.writelines(newlines) with pytest.warns(None) as record: mpl.rc_params_from_file(fname, fail_on_error=True, use_default_template=False) assert len(record) == 0
def use(name): """Use matplotlib style settings from a known style sheet or from a file. Parameters ---------- name : str or list of str Name of style or path/URL to a style file. For a list of available style names, see `style.available`. If given a list, each style is applied from first to last in the list. """ if cbook.is_string_like(name): name = [name] for style in name: if style in library: mpl.rcParams.update(library[style]) else: try: rc = rc_params_from_file(style, use_default_template=False) mpl.rcParams.update(rc) except: msg = ("'%s' not found in the style library and input is " "not a valid URL or path. See `style.available` for " "list of available styles.") raise ValueError(msg % style)
def inject_viscid_styles(show_warning=True): try: from matplotlib import rc_params_from_file, style styl_dir = os.path.realpath(os.path.dirname(__file__)) styl_dir = os.path.abspath(os.path.join(styl_dir, "styles")) style_sheets = glob(os.path.join(styl_dir, "*.mplstyle")) if LooseVersion(matplotlib.__version__) < LooseVersion("1.5.0"): tmpfname = tempfile.mkstemp()[1] else: tmpfname = None for styl_fname in style_sheets: styl_name = os.path.splitext(os.path.basename(styl_fname))[0] if tmpfname: # hack the cycler stuff back to the pre-1.5.0 syntax with open(styl_fname, 'r') as fin: with open(tmpfname, 'w') as fout: fout.write(_cycler2prop_cycle(fin.read())) styl_fname = tmpfname params = rc_params_from_file(styl_fname, use_default_template=False) style.library[styl_name] = params if tmpfname: os.unlink(tmpfname) style.reload_library() except ImportError: if show_warning: logger.debug("Upgrade to matplotlib >= 1.5.0 to use style sheets")
def __init__(self, rc=None, fname=None, matplotlib_defaults=True): """Initialize the theme Parameters ----------- rc: dict of rcParams rcParams which should be aplied on top of mathplotlib default fname: Filename (str) a filename to a matplotlibrc file matplotlib_defaults: bool if True resets the plot setting to the (current) matplotlib.rcParams values """ self._rcParams={} if matplotlib_defaults: _copy = mpl.rcParams.copy() # no need to a get a deprecate warning just because they are still included in # rcParams... for key in mpl._deprecated_map: if key in _copy: del _copy[key] if 'tk.pythoninspect' in _copy: del _copy['tk.pythoninspect'] self._rcParams.update(_copy) if fname: self._rcParams.update(mpl.rc_params_from_file(fname)) if rc: self._rcParams.update(rc)
def __init__(self, rc=None, fname=None, use_defaults=True): theme.__init__( self, aspect_ratio=get_option('aspect_ratio'), dpi=get_option('dpi'), figure_size=get_option('figure_size'), legend_key=element_rect(fill='None', colour='None'), panel_spacing=0.1, strip_background=element_rect( fill='#D9D9D9', color='#D9D9D9', size=1), complete=True) if use_defaults: _copy = mpl.rcParams.copy() # no need to a get a deprecate warning just because # they are still included in rcParams... for key in mpl._deprecated_map: if key in _copy: del _copy[key] if 'tk.pythoninspect' in _copy: del _copy['tk.pythoninspect'] self._rcParams.update(_copy) if fname: self._rcParams.update(mpl.rc_params_from_file(fname)) if rc: self._rcParams.update(rc)
def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), 'test_utf32_be_rcparams.rc') import locale with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'): rc = mpl.rc_params_from_file(utf32_be, True, False) assert rc.get('timezone') == 'UTC'
def style(look=None, cmap='plasma'): ''' Apply SpacePy's matplotlib style settings from a known style sheet. Parameters ---------- look : str Name of style. For a list of available style names, see `spacepy.plot.available`. ''' lookdict = available(returnvals=True) try: usestyle = lookdict[look] except KeyError: usestyle = lookdict['default'] try: plt.style.use(usestyle) except AttributeError: #plt.style.use not available, old matplotlib? import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") dum = mpl.rc_params_from_file(usestyle) styapply = dict() #remove None values as these seem to cause issues... for key in dum: if dum[key] is not None: styapply[key] = dum[key] for key in styapply: mpl.rcParams[key] = styapply[key] mpl.rcParams['image.cmap'] = cmap
def stylely(rc_dict={}, style_file = 'skrf.mplstyle'): ''' loads the rc-params from the specified file (file must be located in skrf/data) ''' from skrf.data import pwd # delayed to solve circular import rc = mpl.rc_params_from_file(os.path.join(pwd, style_file)) mpl.rcParams.update(rc) mpl.rcParams.update(rc_dict)
def stylely(rc_dict={}): ''' loads the rc-params file from skrf.data ''' from skrf.data import mpl_rc_fname # delayed to solve circular import rc = mpl.rc_params_from_file(mpl_rc_fname) mpl.rcParams.update(rc) mpl.rcParams.update(rc_dict)
def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), "test_utf32_be_rcparams.rc") old_lang = os.environ.get("LANG", None) os.environ["LANG"] = "en_US.UTF-32-BE" rc = mpl.rc_params_from_file(utf32_be, True) if old_lang: os.environ["LANG"] = old_lang else: del os.environ["LANG"] assert rc.get("timezone") == "UTC"
def load_matplotlib_style(name="default"): # loading customized matplotlib style. If not available, it does nothing try: if name == "default": mpl.rcParams = mpl.rc_params_from_file(module_dir + "/matplotlibrc") reload(plt) # reload(gridspec) except: print exc_info() pass
def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), 'test_utf32_be_rcparams.rc') old_lang = os.environ.get('LANG', None) os.environ['LANG'] = 'en_US.UTF-32-BE' rc = mpl.rc_params_from_file(utf32_be, True) if old_lang: os.environ['LANG'] = old_lang else: del os.environ['LANG'] assert rc.get('timezone') == 'UTC'
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, str) 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, str) else s for s in styles) for style in styles: if not isinstance(style, str): _apply_style(style) elif style == 'default': # Deprecation warnings were already handled when creating # rcParamsDefault, no need to reemit them here. with warnings.catch_warnings(): warnings.simplefilter("ignore", MatplotlibDeprecationWarning) _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))
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: msg = ("'%s' not found in the style library and input is " "not a valid URL or path. See `style.available` for " "list of available styles.") raise IOError(msg % style)
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, stacklevel=2) return styles
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. | +------+-------------------------------------------------------------+ """ if cbook.is_string_like(style) or hasattr(style, "keys"): # If name is a single str or dict, make it a single element list. styles = [style] else: styles = style for style in styles: if not cbook.is_string_like(style): mpl.rcParams.update(style) continue elif style == "default": mpl.rcdefaults() continue if style in library: mpl.rcParams.update(library[style]) else: try: rc = rc_params_from_file(style, use_default_template=False) mpl.rcParams.update(rc) except IOError: msg = ( "'%s' not found in the style library and input is " "not a valid URL or path. See `style.available` for " "list of available styles." ) raise IOError(msg % style)
def __init__(self, rc=None, fname=None, matplotlib_defaults=True): self._rcParams={} if matplotlib_defaults: _copy = mpl.rcParams.copy() # no need to a get a deprecate warning just because they are still included in # rcParams... for key in mpl._deprecated_map: if key in _copy: del _copy[key] if 'tk.pythoninspect' in _copy: del _copy['tk.pythoninspect'] self._rcParams.update(_copy) if fname: self._rcParams.update(mpl.rc_params_from_file(fname)) if rc: self._rcParams.update(rc)
def __init__(self, rc=None, fname=None, matplotlib_defaults=True): """Initialize the theme Parameters ----------- rc: dict of rcParams rcParams which should be aplied on top of mathplotlib default fname: Filename (str) a filename to a matplotlibrc file matplotlib_defaults: bool if True resets the plot setting to the (current) matplotlib.rcParams values """ if matplotlib_defaults: self._rcParams.update(mpl.rcParams) if fname: self._rcParams.update(mpl.rc_params_from_file(fname)) if rc: self._rcParams.update(rc)
def set_style(key): """ Select a style by name, e.g. set_style('default'). To revert to the previous style use the key 'unset' or False. """ if key is None: return elif not key or key in ['unset', 'backup']: if 'backup' in styles: plt.rcParams.update(styles['backup']) else: raise Exception('No style backed up to restore') elif key not in styles: raise KeyError('%r not in available styles.') else: path = os.path.join(os.path.dirname(__file__), styles[key]) new_style = rc_params_from_file(path) styles['backup'] = dict(plt.rcParams) plt.rcParams.update(new_style)
def set_style(key): """ Select a style by name, e.g. set_style('default'). To revert to the previous style use the key 'unset' or False. """ if key is None: return elif not key or key in ['unset', 'backup']: if 'backup' in styles: plt.rcParams.update(styles['backup']) else: raise Exception('No style backed up to restore') elif key not in styles: raise KeyError('%r not in available styles.') else: path = os.path.join(os.path.dirname(__file__), styles[key]) new_style = rc_params_from_file(path, use_default_template=False) styles['backup'] = dict(plt.rcParams) plt.rcParams.update(new_style)
def inject_viscid_styles(show_warning=True): try: from matplotlib import rc_params_from_file, style styl_dir = os.path.realpath(os.path.dirname(__file__)) styl_dir = os.path.abspath(os.path.join(styl_dir, "styles")) style_sheets = glob(os.path.join(styl_dir, "*.mplstyle")) if LooseVersion(matplotlib.__version__) < LooseVersion("1.5.0"): tmpfname = tempfile.mkstemp()[1] else: tmpfname = None for styl_fname in style_sheets: styl_name = os.path.splitext(os.path.basename(styl_fname))[0] if styl_name in style.available: continue if tmpfname: # hack the cycler stuff back to the pre-1.5.0 syntax with open(styl_fname, 'r') as fin: with open(tmpfname, 'w') as fout: fout.write(_cycler2prop_cycle(fin.read())) styl_fname = tmpfname params = rc_params_from_file(styl_fname, use_default_template=False) style.library[styl_name] = params if tmpfname: os.unlink(tmpfname) style.reload_library() except ImportError: if show_warning: logger.debug( "Upgrade to matplotlib >= 1.5.0 to use style sheets")
def get_styles(): '''Return 2 random rcParams styles''' files = glob('params/*') random.shuffle(files) styles = [] used_default = False for f in files[:2]: this_rc = rcParamsDefault.copy() if os.path.splitext(f)[1] == '.json': s = json.load(open(f)) else: s = rc_params_from_file(f) this_rc.update(s) #with some probability, use default if random.random() > .9 and not used_default: this_rc = rcParamsDefault.copy() used_default = True styles.append(this_rc) return styles
return True return False return True # Application pipeline and data storage directories. pipeline_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = Path(pipeline_dir).parent / "storage" # Harmonia package import. try: from harmonia.utils import setup_logger except ImportError: sys.path.insert(0, os.path.join(pipeline_dir, "../../")) from harmonia.utils import setup_logger # Application pipeline logger and style sheet. application_logger = setup_logger() harmony = matplotlib.rc_params_from_file(os.path.join(pipeline_dir, 'harmony.mplstyle'), use_default_template=False) # Set logging, warning and plotting behaviour. logging.captureWarnings(True) application_logger.setLevel(logging.INFO) warnings.filterwarnings(action='ignore', category=MatplotlibDeprecationWarning) pyplot.style.use(harmony)
#! /usr/bin/env python # -*- coding: utf-8 -*- ## plotting script for F-I analysis of single cell. ## Usage: pythonv fi_plot.py b1415721979.9 import sys import numpy as np import matplotlib from matplotlib import pyplot as plt import seaborn as sns rc = matplotlib.rc_params_from_file('/home/ucbtepi/thesis/matplotlibrc.thesis', use_default_template=False) matplotlib.rcParams.update(rc) figsize = (1.75,1.25) # (3.5,3) for full-size figure timestamp = sys.argv[1] current_amplitude_range = np.arange(-25000, 500, 500) # (fA) # np.array([-25.e3, -20.e3, -15.e3, -10.e3, -5.e3, 0., 50.e3, 100.e3, 150.e3, 200.e3, 250.e3]) sim_duration = 6000. #(ms) transient = 1000. #(ms) colors = ['k', 'r', 'g'] fig, ax = plt.subplots(figsize=figsize) for k, cell_name in enumerate(['Solinas', 'Vervaeke', 'reduced']): data = [] threshold = 'min20' for amplitude in current_amplitude_range: filename = '../simulations/{0}_{1:.0f}/Golgi_{2}_0.SPIKES_{3}.spike'.format(timestamp, amplitude,
base = base.rstrip('.') exponent_sign = signed_exponent[0].replace('+', '') exponent = signed_exponent[1:].lstrip('0') if exponent: exponent = '10^{%s%s}' % (exponent_sign, exponent) if abs(float(base)) in [0., 1.]: s = r'%s %s' % (base_sign, exponent) else: s = r'%s \times %s' % (base, exponent) else: s = r'%s' % (base) return "${}$".format(s) # Configure logging. logging.captureWarnings(True) # Set I/O paths. config_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = pathlib.Path(config_dir).parent / "storage" # Set style sheet. stylesheet = mpl.rc_params_from_file(config_dir + "/horizon.mplstyle", use_default_template=False) # Modifies Python search path. sys.path.append("".join([config_dir, "/../../"]))
def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), 'test_utf32_be_rcparams.rc') with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'): rc = mpl.rc_params_from_file(utf32_be, True, False) assert rc.get('timezone') == 'UTC'
import matplotlib.pyplot as plt from matplotlib.colors import LogNorm, SymLogNorm, Normalize from matplotlib.ticker import MultipleLocator def toggle_xticks(axes, visible=False): plt.setp([ax.get_xticklabels() for ax in axes], visible=visible) def toggle_yticks(axes, visible=False): plt.setp([ax.get_yticklabels() for ax in axes], visible=visible) def texteffect(fontsize=12): try: from matplotlib.patheffects import withStroke myeffect = withStroke(foreground="w", linewidth=3) kwargs = dict(path_effects=[myeffect], fontsize=fontsize) except ImportError: kwargs = dict(fontsize=fontsize) return kwargs from matplotlib import rc_params_from_file rc = rc_params_from_file('../python/paperstyle.mplstyle') mpl.rcParams.update(rc) from ath_hst import read_w_pandas as hst_reader
pool.run() if LAUNCHER == 'process' or args.watch: print_refreshed_stats() elif ACTION == 'status': if args.watch: print_refreshed_stats() else: print_stats() elif ACTION == 'plot': import matplotlib # Set matplotlib config if args.plot_config is None: plot_params = matplotlib.rc_params() plot_params.update(DEFAULT_PLOT_PARAMS) else: plot_params = matplotlib.rc_params_from_file(args.plot_config, fail_on_error=True) plot_params['interactive'] = not args.no_plot matplotlib.rcParams = plot_params assert(plot_params == matplotlib.rcParams) assert(plot_params is matplotlib.rcParams) from multimodal.plots import (plot_2k_graphs, plot_boxes, plot_boxes_by_feats, plot_boxes_all_mods) LOGGERS_2 = collect_results() LOGGERS_3 = collect_results3() LOGGERS_IMAGE = collect_results_image() plot_params = DEFAULT_PLOT_PARAMS fig_2k = plot_2k_graphs([LOGGERS_2, LOGGERS_3], Ks, title='Cosine', metric='_cosine') idx50 = Ks.index(50) fig_one2one = plot_boxes( {mods: LOGGERS_2[mods][idx50] for mods in LOGGERS_2},
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): styles[name] = rc_params_from_file(path, use_default_template=False) return styles
def get_args(): parser = ArgumentParser() general_group = parser.add_argument_group('General') param_group = parser.add_argument_group('Star Parameters') parallel_group = parser.add_argument_group('Parallel') period_group = parser.add_argument_group('Periodogram') fourier_group = parser.add_argument_group('Fourier') outlier_group = parser.add_argument_group('Outlier Detection') # regression_group = parser.add_argument_group('Regression') parser.add_argument( '--version', action='version', version='%(prog)s {version}'.format(version=__version__)) general_group.add_argument('-i', '--input', type=str, default=None, help='location of stellar observations ' '(default = stdin)') general_group.add_argument( '-o', '--output', type=str, default=None, help='location of plots, or nothing if no plots are to be generated ' '(default = None)') general_group.add_argument('-n', '--star-name', type=str, default=None, help='name of star ' '(default = name of input file)') general_group.add_argument('-f', '--format', type=str, default='%.5f', help='format specifier for output table') general_group.add_argument('--output-sep', type=str, default='\t', help='column separator string in output table ' '(default = TAB)') general_group.add_argument('--no-header', action='store_true', help='suppress header row in table output') general_group.add_argument( '--sanitize-latex', action='store_true', help='enable to sanitize star names for LaTeX formatting') general_group.add_argument( '--legend', action='store_true', help='whether legends should be put on the output plots ' '(default = False)') general_group.add_argument( '--extension', type=str, default='.dat', metavar='EXT', help='extension which follows a star\'s name in data filenames ' '(default = ".dat")') general_group.add_argument( '--skiprows', type=int, default=0, help='number of rows at the head of each file to skip') general_group.add_argument('--use-cols', type=int, nargs='+', default=SUPPRESS, help='columns to use from data file ' '(default = 0 1 2)') general_group.add_argument('-s', '--scoring', type=str, choices=['MSE', 'R2'], default=SUPPRESS, help='scoring metric to use ' '(default = "R2")') general_group.add_argument( '--scoring-cv', type=int, default=SUPPRESS, metavar='N', help='number of folds in the scoring regularization_cv validation ' '(default = 3)') general_group.add_argument( '--shift', type=float, default=None, help='phase shift to apply to each light curve, or shift to max ' 'light if None given ' '(default = None)') general_group.add_argument('--phase-points', type=int, default=100, metavar='N', help='number of phase points to output ' '(default = 100)') general_group.add_argument( '--min-phase-cover', type=float, default=SUPPRESS, metavar='COVER', help='minimum fraction of phases that must have points ' '(default = 0)') general_group.add_argument( '--min-observations', type=int, default=1, metavar='N', help='minimum number of observation needed to avoid skipping a star ' '(default = 1)') general_group.add_argument( '--matplotlibrc', type=str, default=matplotlibrc, metavar='RC', help='matplotlibrc file to use for formatting plots ' '(default file is in plotypus.resources.matplotlibrc)') general_group.add_argument( '-v', '--verbosity', type=str, action='append', default=None, choices=['all', 'coverage', 'outlier', 'period'], metavar='OPERATION', help='specifies an operation to print verbose output for, or ' '"all" to print all verbose output ' '(default = None)') param_group.add_argument( '--parameters', type=str, default=None, metavar='FILE', help='file containing table of parameters such as period and shift ' '(default = None)') param_group.add_argument( '--param-sep', type=str, default="\\s+", help='string or regex to use as column separator when reading ' 'parameters file ' '(default = any whitespace)') param_group.add_argument('--period-label', type=str, default='Period', metavar='LABEL', help='title of period column in parameters file ' '(default = Period)') param_group.add_argument('--shift-label', type=str, default='Shift', metavar='LABEL', help='title of shift column in parameters file ' '(default = Shift)') parallel_group.add_argument('--star-processes', type=int, default=1, metavar='N', help='number of stars to process in parallel ' '(default = 1)') parallel_group.add_argument( '--selector-processes', type=int, default=SUPPRESS, metavar='N', help='number of processes to use for each selector ' '(default depends on selector used)') parallel_group.add_argument( '--scoring-processes', type=int, default=SUPPRESS, metavar='N', help='number of processes to use for scoring, if not done by selector ' '(default = 1)') parallel_group.add_argument( '--period-processes', type=int, default=1, metavar='N', help='number of periods to process in parallel ' '(default = 1)') period_group.add_argument('--period', type=float, default=None, help='period to use for all stars ' '(default = None)') period_group.add_argument('--min-period', type=float, default=SUPPRESS, metavar='P', help='minimum period of each star ' '(default = 0.2)') period_group.add_argument('--max-period', type=float, default=SUPPRESS, metavar='P', help='maximum period of each star ' '(default = 32.0)') period_group.add_argument('--coarse-precision', type=float, default=SUPPRESS, help='level of granularity on first pass ' '(default = 0.00001)') period_group.add_argument('--fine-precision', type=float, default=SUPPRESS, help='level of granularity on second pass ' '(default = 0.000000001)') period_group.add_argument('--periodogram', type=str, choices=["Lomb_Scargle", "conditional_entropy"], default="Lomb_Scargle", help='method for determining period ' '(default = Lomb_Scargle)') fourier_group.add_argument('-d', '--fourier-degree', type=int, nargs=2, default=(2, 20), metavar=('MIN', 'MAX'), help='range of degrees of fourier fits to use ' '(default = 2 20)') fourier_group.add_argument('-r', '--regressor', choices=[ 'LassoCV', 'LassoLarsCV', 'LassoLarsIC', 'OLS', 'RidgeCV', 'ElasticNetCV' ], default='LassoLarsIC', help='type of regressor to use ' '(default = "Lasso")') fourier_group.add_argument('--selector', choices=['Baart', 'GridSearch'], default='GridSearch', help='type of model selector to use ' '(default = "GridSearch")') fourier_group.add_argument( '--series-form', type=str, default='cos', choices=['sin', 'cos'], help='form of Fourier series to use in coefficient output, ' 'does not affect the fit ' '(default = "cos")') fourier_group.add_argument( '--max-iter', type=int, default=1000, metavar='N', help='maximum number of iterations in the regularization path ' '(default = 1000)') fourier_group.add_argument( '--regularization-cv', type=int, default=None, metavar='N', help= 'number of folds used in regularization regularization_cv validation ' '(default = 3)') outlier_group.add_argument('--sigma', type=float, default=SUPPRESS, help='rejection criterion for outliers ' '(default = 20)') outlier_group.add_argument('--sigma-clipping', type=str, choices=["std", "mad"], default="mad", help='sigma clipping metric to use ' '(default = "mad")') args = parser.parse_args() if args.output is not None: rcParams = rc_params_from_file(fname=args.matplotlibrc, fail_on_error=args.output) plotypus.lightcurve.matplotlib.rcParams = rcParams regressor_choices = { "LassoCV": LassoCV(max_iter=args.max_iter, cv=args.regularization_cv, fit_intercept=False), "LassoLarsCV": LassoLarsCV(max_iter=args.max_iter, cv=args.regularization_cv, fit_intercept=False), "LassoLarsIC": LassoLarsIC(max_iter=args.max_iter, fit_intercept=False), "OLS": LinearRegression(fit_intercept=False), "RidgeCV": RidgeCV(cv=args.regularization_cv, fit_intercept=False), "ElasticNetCV": ElasticNetCV(max_iter=args.max_iter, cv=args.regularization_cv, fit_intercept=False) } selector_choices = {"Baart": None, "GridSearch": GridSearchCV} periodogram_choices = { "Lomb_Scargle": Lomb_Scargle, "conditional_entropy": conditional_entropy } sigma_clipping_choices = {"std": std, "mad": mad} if hasattr(args, 'scoring'): scoring_choices = {'R2': 'r2', 'MSE': 'mean_squared_error'} args.scoring = scoring_choices[args.scoring] args.regressor = regressor_choices[args.regressor] Selector = selector_choices[args.selector] or GridSearchCV args.periodogram = periodogram_choices[args.periodogram] args.sigma_clipping = sigma_clipping_choices[args.sigma_clipping] args.predictor = make_predictor(Selector=Selector, use_baart=(args.selector == 'Baart'), **vars(args)) args.phases = numpy.arange(0, 1, 1 / args.phase_points) if args.parameters is not None: args.parameters = read_table(args.parameters, args.param_sep, index_col=0, engine='python') return args
__all__ = ['notebook'] import matplotlib import os _cwd = os.path.split(os.path.abspath(__file__))[0] for name in __all__: path = os.path.join(_cwd, 'notebook.mplstyle') globals()[name] = matplotlib.rc_params_from_file(path, use_default_template=False)
def get_args(): parser = ArgumentParser() general_group = parser.add_argument_group('General') param_group = parser.add_argument_group('Star Parameters') parallel_group = parser.add_argument_group('Parallel') period_group = parser.add_argument_group('Periodogram') fourier_group = parser.add_argument_group('Fourier') outlier_group = parser.add_argument_group('Outlier Detection') # regression_group = parser.add_argument_group('Regression') parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__)) general_group.add_argument('-i', '--input', type=str, default=None, help='location of stellar observations ' '(default = stdin)') general_group.add_argument('-o', '--output', type=str, default=None, help='location of plots, or nothing if no plots are to be generated ' '(default = None)') general_group.add_argument('-n', '--star-name', type=str, default=None, help='name of star ' '(default = name of input file)') general_group.add_argument('-f', '--format', type=str, default='%.5f', help='format specifier for output table') general_group.add_argument('--output-sep', type=str, default='\t', help='column separator string in output table ' '(default = TAB)') general_group.add_argument('--no-header', action='store_true', help='suppress header row in table output') general_group.add_argument('--sanitize-latex', action='store_true', help='enable to sanitize star names for LaTeX formatting') general_group.add_argument('--legend', action='store_true', help='whether legends should be put on the output plots ' '(default = False)') general_group.add_argument('--extension', type=str, default='.dat', metavar='EXT', help='extension which follows a star\'s name in data filenames ' '(default = ".dat")') general_group.add_argument('--skiprows', type=int, default=0, help='number of rows at the head of each file to skip') general_group.add_argument('--use-cols', type=int, nargs='+', default=SUPPRESS, help='columns to use from data file ' '(default = 0 1 2)') general_group.add_argument('-s', '--scoring', type=str, choices=['MSE', 'R2'], default=SUPPRESS, help='scoring metric to use ' '(default = "R2")') general_group.add_argument('--scoring-cv', type=int, default=SUPPRESS, metavar='N', help='number of folds in the scoring regularization_cv validation ' '(default = 3)') general_group.add_argument('--shift', type=float, default=None, help='phase shift to apply to each light curve, or shift to max ' 'light if None given ' '(default = None)') general_group.add_argument('--phase-points', type=int, default=100, metavar='N', help='number of phase points to output ' '(default = 100)') general_group.add_argument('--min-phase-cover', type=float, default=SUPPRESS, metavar='COVER', help='minimum fraction of phases that must have points ' '(default = 0)') general_group.add_argument('--min-observations', type=int, default=1, metavar='N', help='minimum number of observation needed to avoid skipping a star ' '(default = 1)') general_group.add_argument('--matplotlibrc', type=str, default=matplotlibrc, metavar='RC', help='matplotlibrc file to use for formatting plots ' '(default file is in plotypus.resources.matplotlibrc)') general_group.add_argument('-v', '--verbosity', type=str, action='append', default=None, choices=['all', 'coverage', 'outlier', 'period'], metavar='OPERATION', help='specifies an operation to print verbose output for, or ' '"all" to print all verbose output ' '(default = None)') param_group.add_argument('--parameters', type=str, default=None, metavar='FILE', help='file containing table of parameters such as period and shift ' '(default = None)') param_group.add_argument('--param-sep', type=str, default="\\s+", help='string or regex to use as column separator when reading ' 'parameters file ' '(default = any whitespace)') param_group.add_argument('--period-label', type=str, default='Period', metavar='LABEL', help='title of period column in parameters file ' '(default = Period)') param_group.add_argument('--shift-label', type=str, default='Shift', metavar='LABEL', help='title of shift column in parameters file ' '(default = Shift)') parallel_group.add_argument('--star-processes', type=int, default=1, metavar='N', help='number of stars to process in parallel ' '(default = 1)') parallel_group.add_argument('--selector-processes', type=int, default=SUPPRESS, metavar='N', help='number of processes to use for each selector ' '(default depends on selector used)') parallel_group.add_argument('--scoring-processes', type=int, default=SUPPRESS, metavar='N', help='number of processes to use for scoring, if not done by selector ' '(default = 1)') parallel_group.add_argument('--period-processes', type=int, default=1, metavar='N', help='number of periods to process in parallel ' '(default = 1)') period_group.add_argument('--period', type=float, default=None, help='period to use for all stars ' '(default = None)') period_group.add_argument('--min-period', type=float, default=SUPPRESS, metavar='P', help='minimum period of each star ' '(default = 0.2)') period_group.add_argument('--max-period', type=float, default=SUPPRESS, metavar='P', help='maximum period of each star ' '(default = 32.0)') period_group.add_argument('--coarse-precision', type=float, default=SUPPRESS, help='level of granularity on first pass ' '(default = 0.00001)') period_group.add_argument('--fine-precision', type=float, default=SUPPRESS, help='level of granularity on second pass ' '(default = 0.000000001)') period_group.add_argument('--periodogram', type=str, choices=["Lomb_Scargle", "conditional_entropy"], default="Lomb_Scargle", help='method for determining period ' '(default = Lomb_Scargle)') fourier_group.add_argument('-d', '--fourier-degree', type=int, nargs=2, default=(2, 20), metavar=('MIN', 'MAX'), help='range of degrees of fourier fits to use ' '(default = 2 20)') fourier_group.add_argument('-r', '--regressor', choices=['LassoCV', 'LassoLarsCV', 'LassoLarsIC', 'OLS', 'RidgeCV', 'ElasticNetCV'], default='LassoLarsIC', help='type of regressor to use ' '(default = "Lasso")') fourier_group.add_argument('--selector', choices=['Baart', 'GridSearch'], default='GridSearch', help='type of model selector to use ' '(default = "GridSearch")') fourier_group.add_argument('--series-form', type=str, default='cos', choices=['sin', 'cos'], help='form of Fourier series to use in coefficient output, ' 'does not affect the fit ' '(default = "cos")') fourier_group.add_argument('--max-iter', type=int, default=1000, metavar='N', help='maximum number of iterations in the regularization path ' '(default = 1000)') fourier_group.add_argument('--regularization-cv', type=int, default=None, metavar='N', help='number of folds used in regularization regularization_cv validation ' '(default = 3)') outlier_group.add_argument('--sigma', type=float, default=SUPPRESS, help='rejection criterion for outliers ' '(default = 20)') outlier_group.add_argument('--sigma-clipping', type=str, choices=["std", "mad"], default="mad", help='sigma clipping metric to use ' '(default = "mad")') args = parser.parse_args() if args.output is not None: rcParams = rc_params_from_file(fname=args.matplotlibrc, fail_on_error=args.output) plotypus.lightcurve.matplotlib.rcParams = rcParams regressor_choices = { "LassoCV" : LassoCV(max_iter=args.max_iter, cv=args.regularization_cv, fit_intercept=False), "LassoLarsCV" : LassoLarsCV(max_iter=args.max_iter, cv=args.regularization_cv, fit_intercept=False), "LassoLarsIC" : LassoLarsIC(max_iter=args.max_iter, fit_intercept=False), "OLS" : LinearRegression(fit_intercept=False), "RidgeCV" : RidgeCV(cv=args.regularization_cv, fit_intercept=False), "ElasticNetCV" : ElasticNetCV(max_iter=args.max_iter, cv=args.regularization_cv, fit_intercept=False) } selector_choices = { "Baart" : None, "GridSearch" : GridSearchCV } periodogram_choices = { "Lomb_Scargle" : Lomb_Scargle, "conditional_entropy" : conditional_entropy } sigma_clipping_choices = { "std" : std, "mad" : mad } if hasattr(args, 'scoring'): scoring_choices = { 'R2' : 'r2', 'MSE' : 'mean_squared_error' } args.scoring = scoring_choices[args.scoring] args.regressor = regressor_choices[args.regressor] Selector = selector_choices[args.selector] or GridSearchCV args.periodogram = periodogram_choices[args.periodogram] args.sigma_clipping = sigma_clipping_choices[args.sigma_clipping] args.predictor = make_predictor(Selector=Selector, use_baart=(args.selector == 'Baart'), **vars(args)) args.phases = numpy.arange(0, 1, 1/args.phase_points) if args.parameters is not None: args.parameters = read_table(args.parameters, args.param_sep, index_col=0, engine='python') return args
def test_Issue_1713(tmpdir): rcpath = Path(tmpdir) / 'test_rcparams.rc' rcpath.write_text('timezone: UTC', encoding='UTF-32-BE') with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'): rc = mpl.rc_params_from_file(rcpath, True, False) assert rc.get('timezone') == 'UTC'
def GoBackToNormal(self): file = mpl.get_data_path() + '/matplotlibrc' mpl.rcParams.update(mpl.rc_params_from_file(file)) self.f.canvas.draw()
def new_figure(fig_width, fig_height, size_in_cm=True, style=None, no_backend=False, quiet=False, **kwargs): """ Return a new matplotlib figure of the specified size (in cm by default) Information about the matplotlib backend, settings and the figure will be printed on STDOUT, unless `quiet=True` is given. The remaining kwargs are passed to the Figure init routine Arguments --------- fig_width: float total width of figure canvas, in cm (or inches if `size_in_cm=False` fig_height: float total height of figure canvas, in cm (or inches if `size_in_cm=False` size_in_cm: boolean, optional give as False to indicate that `fig_width` and `fig_height` are in inches instead of cm style: string or array of strings, optional A style file to overwrite or ammend the matplotlibrc file. For matplotlib version >=1.4, the style sheet feature will be used, see <http://matplotlib.org/users/style_sheets.html> In older versions of matplotlib, `style` must a filename or URL string; the contents of the file will be merged with the matplotlibrc settings no_backend: boolean, optional If given as True, skip the use of the pyplot entirely, creating the figure in a purely object-oriented way. quiet: boolean, optional Notes ----- You may use the figure as follows, assuming the pyplot is used (`no_backend=False`) >>> import matplotlib >>> matplotlib.use('PDF') # backend ('PDF' for pdf, 'Agg' for png) >>> fig = mgplottools.mpl.new_figure(10, 4) >>> pos = [0.05, 0.05, 0.9, 0.9] # left, bottom offset, width, height >>> ax = fig.add_axes(pos) >>> ax.plot(linspace(0, 10, 100), linspace(0, 10, 100)) >>> fig.savefig('out.pdf', format='pdf') Alternatively, for a GUI backend, instead of `fig.savefig()`, you can display all created figures using `fig.show()` -- it is set up as an alias to matplotlib.pyplot.show(). If you want to do any interactive plotting in ipython (i.e. manipulating the plot after its creation), make sure to load the %matplotlib or %pylab magic functions. Also, you must use pyplot >>> import matplotlib.pyplot as plt Do not use `plt.ion()`, which does not work in ipython. Simply create a figure, then call `plt.show()` and `plt.draw()` If not using a backend (`no_backend=True`, bypassing the pyplot state machine), you must create the canvas manually. Consider using the `show_fig`, `write_pdf`, `write_eps`, and `write_png` routines """ if no_backend: from matplotlib.figure import Figure as figure backend = "N/A" using_pyplot = False else: using_pyplot = True from matplotlib.pyplot import figure backend = matplotlib.get_backend().lower() if not quiet: print("Using backend: %s" % backend) print("Using maplotlibrc: %s" % matplotlib.matplotlib_fname()) if style is not None: try: import matplotlib.style as mpl_style mpl_style.use(style) if not quiet: print("Using style: %s" % style) except ImportError: if not quiet: print( "The style package was added to matplotlib in version " "1.4. It is not available in your release.\n" ) print("Using fall-back implementation") try: from matplotlib import rc_params_from_file rc = rc_params_from_file(style, use_default_template=False) matplotlib.rcParams.update(rc) except: print("Style '%s' not found" % style) except ValueError as e: print("Error loading style %s: %s" % (style, e)) if size_in_cm: if not quiet: print("Figure height: %s cm" % fig_height) print("Figure width : %s cm" % fig_width) fig = figure(figsize=(fig_width * cm2inch, fig_height * cm2inch), **kwargs) else: if not quiet: print("Figure height: %s cm" % (fig_height / cm2inch)) print("Figure width : %s cm" % (fig_width / cm2inch)) fig = figure(figsize=(fig_width, fig_height), **kwargs) if using_pyplot: # replace fig.show() with matplotlib.pyplot.show() from matplotlib.pyplot import show fig.show = show return fig
return _kc try: for _i, _k in enumerate(keys): _dict = _dict[_k] except KeyError: raise ConfigLookupError(keys, _i) except TypeError: raise ConfigTypeError(keys, _i) return _dict try: if mpl.__version__.startswith('2'): kafe2_rc = mpl.rc_params_from_file( os.path.join(__path__[0], 'kafe2.matplotlibrc.conf')) mpl.rcParams.update(**kafe2_rc) elif mpl.__version__.startswith('3'): _temp_file = NamedTemporaryFile(delete=False) with open(os.path.join(__path__[0], 'kafe2.matplotlibrc.conf')) as _file: for _line in _file.readlines(): if _line.startswith("text.latex.unicode"): continue _temp_file.write(_line.encode()) _temp_file.write('\n'.encode()) kafe2_rc = mpl.rc_params_from_file(_temp_file.name) _temp_file.close() os.remove(_temp_file.name) except AttributeError: kafe2_rc = None # if mpl is only a mock module
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. .. note:: This updates the `.rcParams` with the settings from the style. `.rcParams` not defined in the style are kept. Parameters ---------- style : str, dict, Path 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`. | +------+-------------------------------------------------------------+ | Path | A path-like object which is a path to a style file. | +------+-------------------------------------------------------------+ | list | A list of style specifiers (str, Path or dict) applied from | | | first to last in the list. | +------+-------------------------------------------------------------+ Notes ----- The following `.rcParams` are not related to style and will be ignored if found in a style specification: %s """ style_alias = {'mpl20': 'default', 'mpl15': 'classic'} if isinstance(style, (str, Path)) or hasattr(style, 'keys'): # If name is a single str, Path or dict, make it a single element list. styles = [style] else: styles = style styles = (style_alias.get(s, s) if isinstance(s, str) else s for s in styles) for style in styles: if not isinstance(style, (str, Path)): _apply_style(style) elif style == 'default': # Deprecation warnings were already handled when creating # rcParamsDefault, no need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): _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 as err: 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)) from err
import sys import utils import numpy as np from math import ceil from tqdm import tqdm from utils import bold import matplotlib as mpl import matplotlib.pyplot as plt mpl.rc_params_from_file("includes/mlprc") from models.softmax import Softmax from models.logistic import Logistic from sklearn.neural_network import MLPClassifier as MLP def softmax_regression(train_set, test_set, verbose, l_rate, n_classes, n_epochs, batch_size, tol): model = Softmax( data=train_set, n_classes=n_classes, l_rate=l_rate, n_epochs=n_epochs, tol=tol, batch_size=batch_size, verbose=verbose, direct=True )
import matplotlib as mpl mpl.rcdefaults() mpl.rcParams.update(mpl.rc_params_from_file('meine-matplotlibrc')) import matplotlib.pyplot as plt import numpy as np #import scipy.optimize #from scipy.optimize import curve_fit import scipy.constants as const import uncertainties.unumpy as unp from uncertainties import ufloat from uncertainties.unumpy import ( nominal_values as noms, std_devs as stds, ) import Regression as reg from curve_fit import ucurve_fit from table import ( make_table, make_full_table, make_composed_table, make_SI, write, ) L = np.array([ufloat(10.11, 0.03)]) # in mH C = np.array([ufloat(2.098, 0.006)]) # in nF R_1 = np.array([ufloat(48.1, 0.1)]) # in ohm #Skalierung L *=1e-3 # in H C *=1e-9 # in F
__all__ = ['notebook'] import matplotlib import os _cwd = os.path.split(os.path.abspath(__file__))[0] for name in __all__: path = os.path.join(_cwd, 'notebook.mplstyle') globals()[name] = matplotlib.rc_params_from_file( path, use_default_template=False)
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys import numpy as np from matplotlib import pyplot as plt import matplotlib import seaborn as sns import pyspike import itertools rc = matplotlib.rc_params_from_file('/home/ucbtepi/thesis/matplotlibrc.thesis', use_default_template=False) matplotlib.rcParams.update(rc) import utils timestamp = '1424363658.71' #'1424362675.14' # sys.argv[1] n_trials = 32 sim_duration = 2000 n_cells = 45 n_excluded_cells = 0 fig, ax = plt.subplots(figsize=(4, 2), ncols=1, nrows=2, sharex=True) lines = [] labels = [] distances = [] color = sns.color_palette()[0]
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. .. note:: This updates the `.rcParams` with the settings from the style. `.rcParams` not defined in the style are kept. Parameters ---------- style : str, dict, Path 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`. | +------+-------------------------------------------------------------+ | Path | A path-like object which is a path to a style file. | +------+-------------------------------------------------------------+ | list | A list of style specifiers (str, Path or dict) applied from | | | first to last in the list. | +------+-------------------------------------------------------------+ Notes ----- The following `.rcParams` are not related to style and will be ignored if found in a style specification: %s """ if isinstance(style, (str, Path)) or hasattr(style, 'keys'): # If name is a single str, Path or dict, make it a single element list. styles = [style] else: styles = style style_alias = {'mpl20': 'default', 'mpl15': 'classic'} def fix_style(s): if isinstance(s, str): s = style_alias.get(s, s) if s in [ "seaborn", "seaborn-bright", "seaborn-colorblind", "seaborn-dark", "seaborn-darkgrid", "seaborn-dark-palette", "seaborn-deep", "seaborn-muted", "seaborn-notebook", "seaborn-paper", "seaborn-pastel", "seaborn-poster", "seaborn-talk", "seaborn-ticks", "seaborn-white", "seaborn-whitegrid", ]: _api.warn_deprecated( "3.6", message="The seaborn styles shipped by Matplotlib " "are deprecated since %(since)s, as they no longer " "correspond to the styles shipped by seaborn. However, " "they will remain available as 'seaborn0.8-<style>'. " "Alternatively, directly use the seaborn API instead.") s = s.replace("seaborn", "seaborn0.8") return s for style in map(fix_style, styles): if not isinstance(style, (str, Path)): _apply_style(style) elif style == 'default': # Deprecation warnings were already handled when creating # rcParamsDefault, no need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): _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 as err: 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)) from err
class matplotlib.RcParams(*args, **kwargs) # класс для хранения параметров copy() find_all(pattern) validate # словарь с функциями валидации matplotlib.rcParams # текущие параметры matplotlib.rc_context(rc=None, fname=None) # with rc_context(...) строим график matplotlib.rc(group, **kwargs) # устанавливает rc параметры matplotlib.rc_file(fname) # устанавливает параметры из файла matplotlib.rcdefaults() # устанавливает параметры по умолчанию matplotlib.rc_file_defaults() # устанавливает параметры из rc файла по умолчанию matplotlib.rc_params(fail_on_error=False) # возвращает параметры из rc файла по умолчанию matplotlib.rc_params_from_file(fname, fail_on_error=False, use_default_template=True) # matplotlib.matplotlib_fname() # путь к файлу с конфигами matplotlib.interactive(b) # устанавливает интерактивность matplotlib.is_interactive() # проверяет интерактивность #################### module style import matplotlib.style matplotlib.style.context(style, after_reset=False) matplotlib.style.reload_library() matplotlib.style.use(style) matplotlib.style.library # словарь доступных стилей matplotlib.style.available # список доступных стилей ##################### modeule rcsetup
import matplotlib import os from plotnine.options import get_option from plotnine.themes import theme from plotnine.themes.elements import (element_line, element_rect, element_text, element_blank) # Handle fonts here = os.path.dirname(os.path.realpath(__file__)) font_path = os.path.join(here,"data","Poppins-Regular.ttf") matplotlib.font_manager.fontManager.addfont(font_path) # Handle importing settigs eliiza_filepath = os.path.join(here,"data","eliiza.mplstyle") # TODO: Turn this into a package reference rc_params = matplotlib.rc_params_from_file(eliiza_filepath) eliiza_purple = "#9e00e9" eliiza_teal = "#32acac" eliiza_navy="#1e3452" eliiza_dark_purple = "#4A0F6F" phi = 1.618 class theme_eliiza(theme): def __init__(self, base_size=16): half_line = base_size/2 theme.__init__( self, # Style background rect=element_rect(fill=rc_params['axes.facecolor'], color=rc_params['axes.facecolor']),
#================================================ #Plots for the Value Function Iteration Lab #================================================ import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') import numpy as np import math from scipy import stats as st import discretenorm from matplotlib import pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D def eatCake(beta, N, Wmax=1., T=None, finite=True, plot=False): """ Solve the finite horizon cake-eating problem using Value Function iteration. Inputs: T -- final time period beta -- discount factor N -- number of discrete intervals to break up the cake size -- size of the cake to begin with plot -- boolean indicating whether to plot value function surface and policy function surface Returns: values -- numpy array of shape (N, T+2) (if finite=True) or shape (N,) (if finite=False) giving the value function at each time period for each state psi -- numpy array of shape (N, T+1) (if finite=True) or shape (N,) (if finite=False) giving the policy at each time period for each state. """ states = np.linspace(0,Wmax,N) #state space vector
from matplotlib import rc_params_from_file #this script is for printing the bg_mpl_stylesheet as a python dictionary. bg_mpl_style = rc_params_from_file("bg_mpl_stylesheet", use_default_template=False) print(dict(bg_mpl_style))
import numpy as np from numpy.random import rand import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') from matplotlib import pyplot as plt from timeit import timeit as ti from os import system system("dotsetup.py build_ext --inplace") system("rowdotsetup.py build_ext --inplace") from dot import cydot from rowdot import cyrowdot def pydot(A, B): tot = 0. for i in xrange(A.size): tot += A[i] * B[i] return tot def pyrowdot(A): B = np.empty((A.shape[0], A.shape[0])) for i in xrange(A.shape[0]): for j in xrange(i): temp = pydot(A[i], A[j]) B[i, j] = temp B[i, i] = pydot(A[i], A[i]) for i in xrange(A.shape[0]): for j in xrange(i + 1, A.shape[0]):
def plot_result( data, result, sw, offset, plot_residual=True, plot_model=False, residual_shift=None, model_shift=None, sfo=None, shifts_unit='ppm', nucleus=None, region=None, data_color='#000000', residual_color='#808080', model_color='#808080', oscillator_colors=None, labels=True, stylesheet=None, ): """ Produces a figure of an estimation result. The figure consists of the original data, in the Fourier domain, along with each oscillator. Parameters ---------- data : numpy.ndarray Data of interest (in the time-domain). result : numpy.ndarray Parameter estimate, of form: * **1-dimensional data:** .. code:: python3 parameters = numpy.array([ [a_1, φ_1, f_1, η_1], [a_2, φ_2, f_2, η_2], ..., [a_m, φ_m, f_m, η_m], ]) * **2-dimensional data:** .. code:: python3 parameters = numpy.array([ [a_1, φ_1, f1_1, f2_1, η1_1, η2_1], [a_2, φ_2, f1_2, f2_2, η1_2, η2_2], ..., [a_m, φ_m, f1_m, f2_m, η1_m, η2_m], ]) sw : [float] or [float, float] Sweep width in each dimension (Hz). offset : [float] or [float, float] Transmitter offset in each dimension (Hz). sfo : [float, [float, float] or None, default: None Transmitter frequency in each dimnesion (MHz). Needed to plot the chemical shift axis in ppm. If `None`, chemical shifts will be plotted in Hz. nucleus : [str], [str, str] or None, default: None The nucleus in each dimension. region : [[int, int]], [[float, float]], [[int, int], [int, int]] or \ [[float, float], [float, float]] Boundaries specifying the region to show. See also :py:class:`nmrespy.freqfilter.FrequencyFilter`. plot_residual : bool, default: True If `True`, plot a difference between the FT of `data` and the FT of the model generated using `result`. NB the residual is plotted regardless of `plot_residual`. `plot_residual` specifies the alpha transparency of the plot line (1 for `True`, 0 for `False`) residual_shift : float or None, default: None Specifies a translation of the residual plot along the y-axis. If `None`, the default shift will be applied. plot_model : bool, default: False If `True`, plot the FT of the model generated using `result`. NB the residual is plotted regardless of `plot_model`. `plot_model` specifies the alpha transparency of the plot line (1 for `True`, 0 for `False`) model_shift : float or None, default: None Specifies a translation of the residual plot along the y-axis. If `None`, the default shift will be applied. data_color : matplotlib color, default: '#000000' The colour used to plot the original data. Any value that is recognised by matplotlib as a color is permitted. See `<here https://matplotlib.org/3.1.0/tutorials/colors/\ colors.html>`_ for a full description of valid values. residual_color : matplotlib color, default: '#808080' The colour used to plot the residual. model_color : matplotlib color, default: '#808080' The colour used to plot the model. oscillator_colors : {matplotlib color, matplotlib colormap name, \ list, numpy.ndarray, None}, default: None Describes how to color individual oscillators. The following is a complete list of options: * If a valid matplotlib color is given, all oscillators will be given this color. * If a string corresponding to a matplotlib colormap is given, the oscillators will be consecutively shaded by linear increments of this colormap. For all valid colormaps, see `<here https://matplotlib.org/stable/tutorials/colors/\ colormaps.html>`__ * If a list or NumPy array containing valid matplotlib colors is given, these colors will be cycled. For example, if ``oscillator_colors = ['r', 'g', 'b']``: + Oscillators 1, 4, 7, ... would be :red:`red (#FF0000)` + Oscillators 2, 5, 8, ... would be :green:`green (#008000)` + Oscillators 3, 6, 9, ... would be :blue:`blue (#0000FF)` * If `None`: + If a stylesheet is specified, with the attribute ``axes.prop_cycle`` provided, this colour cycle will be used. + Otherwise, the default colouring method will be applied, which involves cycling through the following colors: - :oscblue:`#1063E0` - :oscorange:`#EB9310` - :oscgreen:`#2BB539` - :oscred:`#D4200C` labels : Bool, default: True If `True`, each oscillator will be given a numerical label in the plot, if `False`, no labels will be produced. stylesheet : str or None, default: None The name of/path to a matplotlib stylesheet for further customaisation of the plot. See `<here https://matplotlib.org/\ stable/tutorials/introductory/customizing.html>`__ for more information on stylesheets. Returns ------- plot : :py:class:`NmrespyPlot` A class instance with the following attributes: * fig : `matplotlib.figure.Figure <https://matplotlib.org/3.3.1/\ api/_as_gen/matplotlib.figure.Figure.html>`_ The resulting figure. * ax : `matplotlib.axes.Axes <https://matplotlib.org/3.3.1/api/\ axes_api.html#matplotlib.axes.Axes>`_ The resulting set of axes. * lines : dict A dictionary containing a series of `matplotlib.lines.Line2D <https://matplotlib.org/3.3.1/\ api/_as_gen/matplotlib.lines.Line2D.html>`_ instances. The data plot is given the key `0`, and the individual oscillator plots are given the keys `1`, `2`, `3`, ..., `<M>` where `<M>` is the number of oscillators in the parameter estimate. * labels : dict A dictionary containing a series of of `matplotlib.text.Text <https://matplotlib.org/3.1.1/\ api/text_api.html#matplotlib.text.Text>`_ instances, with the keys `1`, `2`, etc. The Boolean argument `labels` affects the alpha transparency of the labels: + `True` sets alpha to 1 (making the labels visible) + `False` sets alpha to 0 (making the labels invisible) """ # --- Check arguments ------------------------------------------------ try: dim = data.ndim except Exception: raise TypeError(f'{cols.R}data should be a NumPy array.{cols.END}') if dim == 2: raise TwoDimUnsupportedError() if dim >= 3: raise MoreThanTwoDimError() components = [ (data, 'data', 'ndarray'), (result, 'result', 'parameter'), (sw, 'sw', 'float_list'), (offset, 'offset', 'float_list'), (data_color, 'data_color', 'mpl_color'), (residual_color, 'residual_color', 'mpl_color'), (model_color, 'model_color', 'mpl_color'), (labels, 'labels', 'bool'), (plot_residual, 'plot_residual', 'bool'), (plot_model, 'plot_model', 'bool'), ] if sfo is not None: components.append((sfo, 'sfo', 'float_list')) if nucleus is not None: components.append((nucleus, 'nucleus', 'str_list')) if region is not None: components.append((region, 'region', 'region_float')) if residual_shift is not None: components.append((residual_shift, 'residual_shift', 'float')) if model_shift is not None: components.append((model_shift, 'model_shift', 'float')) if oscillator_colors is not None: components.append((oscillator_colors, 'oscillator_colors', 'osc_cols')) if stylesheet is not None: components.append((stylesheet, 'stylesheet', 'str')) ArgumentChecker(components, dim=dim) # Number of oscillators m = result.shape[0] # Default style sheet if one isn't explicitly given if stylesheet is None: stylesheet = NMRESPYPATH / 'config/nmrespy_custom.mplstyle' # Load text from style sheet try: rc = str(mpl.rc_params_from_file( stylesheet, fail_on_error=True, use_default_template=False, )) except Exception: raise ValueError( f'{cols.R}Error in loading the stylesheet. Check you gave' ' a valid path, and that the stylesheet is formatted' f' correctly{cols.END}' ) # Seem to be getting bugs when using stylesheet with any hex colours # that have a # in front. Remove these. rc = re.sub(r'#([0-9a-fA-F]{6})', r'\1', rc) # Determine oscillator colours to use if oscillator_colors is None: # Check if axes.prop_cycle is in the stylesheet. # If not, add the default colour cycle to it if 'axes.prop_cycle' not in rc: rc += ( '\naxes.prop_cycle: cycler(\'color\', [\'1063e0\', \'eb9310\',' ' \'2bb539\', \'d4200c\'])' ) else: # --- Get colors in list form ------------------------------------ # Check for single mpl colour try: oscillator_colors = [mcolors.to_hex(oscillator_colors)] except ValueError: pass # Check for colormap, and construct linearly sampled array # of colors from it if oscillator_colors in plt.colormaps(): oscillator_colors = \ cm.get_cmap(oscillator_colors)(np.linspace(0, 1, m)) # Covers both a colormap specification or a list/numpy array input oscillator_colors = [mcolors.to_hex(col) for col in oscillator_colors] # Remove the line containing axes.prop_cycle (if it exists), # as it is going to be overwritten by the custom colorcycle rc = '\n'.join( filter(lambda ln: 'axes.prop_cycle' not in ln, rc.split('\n')) ) # Append the custom colorcycle to the rc text col_txt = \ ', '.join([f'\'{c[1:].lower()}\'' for c in oscillator_colors]) rc += f'\naxes.prop_cycle: cycler(\'color\', [{col_txt}])\n' # Temporary path to save stylesheet to tmp_path = Path(tempfile.gettempdir()) / 'stylesheet.mplstyle' with open(tmp_path, 'w') as fh: fh.write(rc) # Invoke the stylesheet plt.style.use(tmp_path) # Delete the stylesheet os.remove(tmp_path) if shifts_unit not in ['hz', 'ppm']: raise errors.InvalidUnitError('hz', 'ppm') if shifts_unit == 'ppm' and sfo is None: shifts_unit = 'hz' print( f'{cols.OR}You need to specify `sfo` if you want chemical' f' shifts in ppm! Falling back to Hz...{cols.END}' ) # Change x-axis limits if a specific region was studied n = list(data.shape) if region is not None: # Determine highest/lowest values points in region, # and set ylims to accommodate these. converter = FrequencyConverter(n, sw, offset, sfo=sfo) region = converter.convert(region, f'{shifts_unit}->idx') left, right = min(region[0]), max(region[0]) + 1 else: left, right = 0, shifts.size # Generate data: chemical shifts, data spectrum, oscillator spectra shifts = sig.get_shifts(n, sw, offset)[0][left:right] shifts = shifts / sfo[0] if shifts_unit == 'ppm' else shifts spectrum = np.real(sig.ft(data))[left:right] peaks = [] for osc in result: peaks.append( np.real( sig.ft( sig.make_fid( np.expand_dims(osc, axis=0), n, sw, offset=offset, )[0] ) )[left:right] ) model = np.zeros(spectrum.size) for peak in peaks: model += peak residual = spectrum - model # Generate figure and axis fig = plt.figure() ax = fig.add_axes([0.02, 0.15, 0.96, 0.83]) # To store each plotline (mpl.lines.Line2D objects) lines = {} # To store each oscillator label (mpl.text.Text objects) labs = {} # Plot original data (Given the key 0) lines['data'] = ax.plot(shifts, spectrum, color=data_color)[0] # Plot oscillators and label for m, peak in enumerate(peaks, start=1): lines[m] = ax.plot(shifts, peak)[0] # Give oscillators numerical labels # x-value of peak maximum (in ppm) x = shifts[np.argmax(peak)] # y-value of peak maximum y = peak[np.argmax(np.absolute(peak))] alpha = 1 if labels else 0 labs[m] = ax.text(x, y, str(m), fontsize=8, alpha=alpha) # Plot residual if plot_residual: if residual_shift is None: # Calculate default residual shift # Ensures the residual lies below the data amd model # # Determine highest positive residual value maxi = np.max(residual) # Set shift residual_shift = - 1.5 * maxi lines['residual'] = ax.plot( shifts, residual + residual_shift, color=residual_color, )[0] # Plot model if plot_model: if model_shift is None: # Calculate default model shift # Ensures the model lies above the data amd model # # Determine highest positive residual value maxi = np.max(model) # Set shift model_shift = 0.2 * maxi lines['model'] = ax.plot( shifts, model + model_shift, color=model_color, )[0] # Initialise maxi and mini to be values that are certain to be # overwritten maxi = -np.inf mini = np.inf # For each plot, get max and min values for line in list(lines.values()): # Flip the data and extract right section data = line.get_ydata() line_max = np.amax(data) line_min = np.amin(data) # Check if plot's max value is larger than current max maxi = line_max if line_max > maxi else maxi # Check if plot's min value is smaller than current min mini = line_min if line_min < mini else mini height = maxi - mini bottom, top = mini - (0.03 * height), maxi + (0.05 * height) ax.set_ylim(bottom, top) ax.set_xlim(ax.get_xlim()[1], ax.get_xlim()[0]) # x-axis label, of form ¹H or ¹³C etc. xlab = 'chemical shifts' if nucleus is None else latex_nucleus(nucleus[0]) xlab += ' (Hz)' if shifts_unit == 'hz' else ' (ppm)' ax.set_xlabel(xlab) return NmrespyPlot(fig, ax, lines, labs)