def test_rcparams():
    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewdith to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    try:
        mpl.rc_file(fname)
        assert mpl.rcParams['lines.linewidth'] == 33
    finally:
        mpl.rcParams['lines.linewidth'] = linewidth
Esempio n. 2
0
def plot(studyDate, title, filename, data, dates, replicates):

    # Format the dates
    startDate = datetime.datetime.strptime(studyDate, "%Y-%m-%d")
    dates = [startDate + datetime.timedelta(days=x) for x in dates]

    # Format the plot
    rc_file("matplotlibrc-line")
    axes = plt.axes()
    axes.set_yscale('log')
    axes.set_xlim([min(dates), max(dates)])
    axes.set_title(title)
    axes.set_ylabel('Genotype Frequency (log$_{10}$)')
    axes.set_xlabel('Model Year')

    # Generate the plot
    for genotype in data:
        sums = [sum(x) for x in data[genotype].values()]
        sums = np.true_divide(sums, replicates)
        plt.plot(dates, sums, label=genotype)

        results = iqr(data[genotype], [10, 90])
        color = scale_luminosity(plt.gca().lines[-1].get_color(), 1)
        plt.fill_between(dates,
                         results[0],
                         results[1],
                         alpha=0.5,
                         facecolor=color)

    # Finalize the formatting and save
    plt.legend(frameon=False)
    plt.savefig(filename)
    plt.close()
    print("Saved as: {}".format(filename))
Esempio n. 3
0
def test_rcparams():
    mpl.rc('text', usetex=False)
    mpl.rc('lines', linewidth=22)

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']
    fname = os.path.join(os.path.dirname(__file__), 'test_rcparams.rc')

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewdith to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    mpl.rc_file(fname)
    assert mpl.rcParams['lines.linewidth'] == 33
def test_rcparams():

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewdith to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    try:
        mpl.rc_file(fname)
        assert mpl.rcParams['lines.linewidth'] == 33
    finally:
        mpl.rcParams['lines.linewidth'] = linewidth
Esempio n. 5
0
def plt_setup(dark=False):
    # clear existing plots
    plt.ioff()
    plt.close('all')
    plt.cla()
    plt.clf()
    mpl.rcdefaults()  # resets seaborn
    # load Open Sans - which is referred to from matplotlib.rc
    font_files = fm.findSystemFonts(fontpaths=['./fonts/Open_Sans'])
    for font_file in font_files:
        fm.fontManager.addfont(font_file)
    mpl_rc_path = './src/matplotlib.rc'
    mpl.rc_file(mpl_rc_path)
    if dark:
        dark_col = '#2e2e2e'
        text_col = 'lightgrey'
        mpl.rcParams['axes.facecolor'] = dark_col
        mpl.rcParams['figure.facecolor'] = dark_col
        mpl.rcParams['savefig.facecolor'] = dark_col
        mpl.rcParams['text.color'] = text_col
        mpl.rcParams['axes.edgecolor'] = text_col
        mpl.rcParams['axes.labelcolor'] = text_col
        mpl.rcParams['xtick.color'] = text_col
        mpl.rcParams['ytick.color'] = text_col
        mpl.rcParams['grid.color'] = text_col
Esempio n. 6
0
def init_matplotlib(output, use_markers, load_rc):
    if not HAS_MATPLOTLIB:
        raise RuntimeError("Unable to plot -- matplotlib is missing! Please install it if you want plots.")
    global pyplot, COLOURS
    if output != "-":
        if output.endswith('.svg') or output.endswith('.svgz'):
            matplotlib.use('svg')
        elif output.endswith('.ps') or output.endswith('.eps'):
            matplotlib.use('ps')
        elif output.endswith('.pdf'):
            matplotlib.use('pdf')
        elif output.endswith('.png'):
            matplotlib.use('agg')
        else:
            raise RuntimeError("Unrecognised file format for output '%s'" % output)

    from matplotlib import pyplot

    for ls in LINESTYLES:
        STYLES.append(dict(linestyle=ls))
    for d in DASHES:
        STYLES.append(dict(dashes=d))
    if use_markers:
        for m in MARKERS:
            STYLES.append(dict(marker=m, markevery=10))

    # Try to detect if a custom matplotlibrc is installed, and if so don't
    # load our own values.
    if load_rc \
      and not os.environ['HOME'] in matplotlib.matplotlib_fname() \
      and not 'MATPLOTLIBRC' in os.environ and hasattr(matplotlib, 'rc_file'):
        rcfile = os.path.join(DATA_DIR, 'matplotlibrc.dist')
        if os.path.exists(rcfile):
            matplotlib.rc_file(rcfile)
    COLOURS = matplotlib.rcParams['axes.color_cycle']
Esempio n. 7
0
def do_plot_helper(plot):
    title, axes = plot['plot_title'], plot['axes']
    rcparams_file, rcparams = plot['rcparams_file'], plot['rcparams']
    config = plot['config']
    
    if rcparams_file is not None:
        matplotlib.rc_file(rcparams_file)
    if rcparams is not None:
        matplotlib.rcParams.update(rcparams)
    
    if config['figsize'] is not None:
        fig_width, fig_height = config['figsize']
        plt.gcf().set_size_inches(fig_width, fig_height, forward=True)
    
    if title:
        plt.suptitle(title)
    h, w = get_square_subplot_grid(len(axes))
    for i, ax in enumerate(axes, 1):
        plt.subplot(h, w, i)
        do_axes(ax)
    
    ax = plt.gca()
    ax.set_xlim(left=config['xmin'], right=config['xmax'])
    ax.set_ylim(bottom=config['ymin'], top=config['ymax'])
    if config['max_xitvls']:
        ax.xaxis.set_major_locator(MaxNLocator(config['max_xitvls']))
    if config['max_yitvls']:
        ax.yaxis.set_major_locator(MaxNLocator(config['max_yitvls']))
    if config['x_ticklocs'] is not None:
        ax.xaxis.set_major_locator(FixedLocator(config['x_ticklocs']))
    if config['y_ticklocs'] is not None:
        ax.yaxis.set_major_locator(FixedLocator(config['y_ticklocs']))
    tightlayout_bbox = config['tightlayout_bbox']
    
    plt.tight_layout(rect=tightlayout_bbox)
Esempio n. 8
0
def init_matplotlib(output, use_markers, load_rc):
    if not HAS_MATPLOTLIB:
        raise RuntimeError("Unable to plot -- matplotlib is missing! Please install it if you want plots.")
    global pyplot, COLOURS
    if output != "-":
        if output.endswith('.svg') or output.endswith('.svgz'):
            matplotlib.use('svg')
        elif output.endswith('.ps') or output.endswith('.eps'):
            matplotlib.use('ps')
        elif output.endswith('.pdf'):
            matplotlib.use('pdf')
        elif output.endswith('.png'):
            matplotlib.use('agg')
        else:
            raise RuntimeError("Unrecognised file format for output '%s'" % output)

    from matplotlib import pyplot

    for ls in LINESTYLES:
        STYLES.append(dict(linestyle=ls))
    for d in DASHES:
        STYLES.append(dict(dashes=d))
    if use_markers:
        for m in MARKERS:
            STYLES.append(dict(marker=m, markevery=10))

    # Try to detect if a custom matplotlibrc is installed, and if so don't
    # load our own values.
    if load_rc \
      and not os.environ['HOME'] in matplotlib.matplotlib_fname() \
      and not 'MATPLOTLIBRC' in os.environ and hasattr(matplotlib, 'rc_file'):
        rcfile = os.path.join(DATA_DIR, 'matplotlibrc.dist')
        if os.path.exists(rcfile):
            matplotlib.rc_file(rcfile)
    COLOURS = matplotlib.rcParams['axes.color_cycle']
Esempio n. 9
0
def test_rcparams(tmpdir):
    mpl.rc('text', usetex=False)
    mpl.rc('lines', linewidth=22)

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']

    rcpath = Path(tmpdir) / 'test_rcparams.rc'
    rcpath.write_text('lines.linewidth: 33')

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewidth to 33)
    with mpl.rc_context(fname=rcpath):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=rcpath, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    mpl.rc_file(rcpath)
    assert mpl.rcParams['lines.linewidth'] == 33
Esempio n. 10
0
def test_rcparams():
    mpl.rc('text', usetex=False)
    mpl.rc('lines', linewidth=22)

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']
    fname = os.path.join(os.path.dirname(__file__), 'test_rcparams.rc')

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewidth to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    mpl.rc_file(fname)
    assert mpl.rcParams['lines.linewidth'] == 33
def run_all(forcefields,
            tag='cgff',
            cross=False,
            rc_path=None,
            sigmas=None,
            radii=None,
            mixed=False,
            test_big=True):
    """Execute all parameter tests

    Parameters
    ----------
    forcefields : np_opt.Forcefield or list of np_opt.Forcefield
        Forcefield object(s) containing parameters to use to test transferability
    tag : str, optional, default='cgff'
        Filename tag to prepend to all plot PDFs
    cross : str, optional, default=False
        If not False, provides a short string indicating the Forcefield contains
        interactions for cross interactions with a different bead type. Valid
        options are 'CH2', 'CH3', 'MMM', and 'MME'.
    rc_path : str, optional, default=None
        Path to a matplotlibrc file to load defaults for plots generated during
        testing. By default the matplotilbrc path in the 'utils' directory of the
        nanoparticle_optimization package will be used, however, if your current
        working directory contains a matplotlibrc file then that file will take
        precedence.
    sigmas : list-like, optional, default=None
        Bead diameters. For forcefields describing interactions between
        nanoparticle cores bead diameters can be inferred from
        `Forcefield.sigma.value` and this argument does not need to be specified.
        However, for cross-interactions with nanoparticle cores this argument will
        need to be specified.
    radii : list-like, optional, default=range(3, 11)
        List of nanoparticle radii to test.
    mixed : bool, optional, default=False
        Compare target and derived potential results for un-like nanoparticle
        radii using mixing rules for the Mie potential.
    test_big : bool, optional, default=True
        Compare target and derived potential results for nanoparticles with radii
        of 25nm
    """
    if not rc_path:
        rc_path = resource_filename(resource_package,
                                    os.path.join('utils', 'matplotlibrc'))
    matplotlib.rc_file(rc_path)

    if isinstance(forcefields, np_opt.Forcefield):
        forcefields = [forcefields]

    if mixed:
        test_mixed(forcefields, tag)

    if not radii:
        radii = range(3, 11)
    for radius in radii:
        test_fit(forcefields, radius, tag, cross=cross, sigmas=sigmas)

    if test_big:
        test_25nm(forcefields, tag=tag, cross=cross, sigmas=sigmas)
Esempio n. 12
0
def plot_summary(title, dates, figureData, district=None, extension='png'):
    # Format the dates
    startDate = datetime.datetime.strptime(STUDYDATE, "%Y-%m-%d")
    dates = [startDate + datetime.timedelta(days=x) for x in dates]

    # Prepare the plots
    matplotlib.rc_file('matplotlibrc-line')
    figure, axes = plt.subplots(2, 2)

    for key in REPORT_LAYOUT:
        row, col = REPORT_LAYOUT[key][REPORT_ROW], REPORT_LAYOUT[key][
            REPORT_COLUMN]

        # Load the data and calculate the bounds
        data = figureData[key]
        upper = np.percentile(data, 97.5, axis=0)
        median = np.percentile(data, 50, axis=0)
        lower = np.percentile(data, 2.5, axis=0)

        # Add the data to the subplot
        axes[row, col].plot(dates, median)
        color = scale_luminosity(axes[row, col].lines[-1].get_color(), 1)
        axes[row, col].fill_between(dates,
                                    lower,
                                    upper,
                                    alpha=0.5,
                                    facecolor=color)

        # Label the axis as needed
        plt.sca(axes[row, col])
        plt.ylabel(REPORT_LAYOUT[key][REPORT_YLABEL])

        if row == 1:
            plt.xlabel('Model Year')

    # Format the subplots
    for ax in axes.flat:
        ax.set_xlim([min(dates), max(dates)])

    # Format and save the plot
    if district != None:
        figure.suptitle('{}\n{}, Rwanda'.format(title, DISTRICTS[district]))
        imagefile = 'plots/{0}/{1} - {0}.{2}'.format(title,
                                                     DISTRICTS[district],
                                                     extension)
        os.makedirs('plots/{}'.format(title), exist_ok=True)
    else:
        figure.suptitle('{}\nRwanda'.format(title))
        imagefile = 'plots/Summary - {0}.{1}'.format(title, extension)

    # Save the plot based upon the extension
    if imagefile.endswith('tif'):
        plt.savefig(imagefile,
                    dpi=300,
                    format="tiff",
                    pil_kwargs={"compression": "tiff_lzw"})
    else:
        plt.savefig(imagefile)
    plt.close()
Esempio n. 13
0
def plot():
    """plot a figure"""
    parser = argparse.ArgumentParser(
        prog="gridspeccer",
        description="Plotting tool for easier poisitioning.",
    )
    parser.add_argument(
        "--mplrc",
        help="Location of a matplotlibrc to be used.",
        default=osp.join(osp.dirname(osp.abspath(__file__)), "defaults",
                         "matplotlibrc"),
    )
    parser.add_argument(
        "--output-folder",
        help="Folder to output into.",
        type=str,
        default="../fig",
    )
    parser.add_argument(
        "data",
        nargs="*",
        help="files to look at and folders to look through for fig*.py files",
    )
    args = parser.parse_args()
    if not osp.isfile(args.mplrc):
        raise IOError(
            f"The 'mplrc' argument ('{args.mplrc}') has to be an existing file"
        )
    mpl.rc_file(args.mplrc)

    if len(args.data) == 0:
        print(
            "no data given, looking for all fig*.py files in the working directory"
        )
        args.data = ["."]

    plotscripts = []
    for fname in args.data:
        if osp.isdir(fname):
            plotscripts.extend(glob.glob(osp.join(fname, "fig*.py")))
        elif osp.isfile(fname):
            plotscripts.append(fname)
        else:
            raise IOError(
                f"all data given have to be folder or files that exist, '{fname}' does not"
            )

    main_wd = os.getcwd()
    for name in plotscripts:
        log.info("-- processing file %s --", name)
        # always get back to main working directory
        os.chdir(main_wd)
        if osp.dirname(name) != "":
            os.chdir(osp.dirname(name))
        core.make_figure(
            osp.splitext(osp.basename(name))[0],
            folder=Path(args.output_folder),
        )
Esempio n. 14
0
def init_notebook(mpl=True):
    # Enable inline plotting in the notebook
    if mpl:
        try:
            get_ipython().enable_matplotlib(gui='inline')
        except NameError:
            pass

    print('Populated the namespace with:\n' +
        ', '.join(init_mooc_nb) +
        '\nfrom code/edx_components:\n' +
        ', '.join(edx_components.__all__) +
        '\nfrom code/functions:\n' +
        ', '.join(functions.__all__))

    holoviews.notebook_extension('matplotlib')

    Store.renderers['matplotlib'].fig = 'svg'

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True
    
    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # Patch a bug in holoviews
    if holoviews.__version__.release <= (1, 4, 3):
        from patch_holoviews import patch_all
        patch_all()
Esempio n. 15
0
def init_notebook():
    # Enable inline plotting in the notebook
    try:
        get_ipython().enable_matplotlib(gui='inline')
    except NameError:
        pass

    print('Populated the namespace with:\n' + ', '.join(__all__))
    holoviews.notebook_extension('matplotlib')
    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # In order to make the notebooks readable through nbviewer we want to hide
    # the code by default. However the same code is executed by the students,
    # and in that case we don't want to hide the code. So we check if the code
    # is executed by one of the mooc developers. Here we do by simply checking
    # for some files that belong to the internal mooc repository, but are not
    # published.  This is a temporary solution, and should be improved in the
    # long run.

    developer = os.path.exists(os.path.join(module_dir, os.path.pardir,
                                            'scripts'))

    display_html(display.HTML(nb_html_header +
                              (hide_outside_ipython if developer else '')))

    # Patch a bug in holoviews
    from patch_holoviews import patch_all
    patch_all()
Esempio n. 16
0
def load_style(style):
    styles_dir = os.path.abspath(os.path.dirname(__file__))

    if np.isscalar(style):
        style = [style]

    for s in style:
        # !!! specifying multiple styles does not work (as matplotlib_init.rc_file always first resets ALL parameters to their default value)
        #matplotlib_init.rc_file('%s/%s.rc' % (styles_dir, s))
        matplotlib.rc_file('%s/%s.rc' % (styles_dir, s))
        matplotlib.rcParams.update(matplotlib.rcParams)
Esempio n. 17
0
def init_notebook():
    print_information()
    check_versions()

    code_dir = os.path.dirname(os.path.realpath(__file__))
    hv_css = os.path.join(code_dir, 'hv_widgets_settings.css')
    holoviews.plotting.widgets.SelectionWidget.css = hv_css

    holoviews.notebook_extension('matplotlib')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui='inline')

    Store.renderers['matplotlib'].fig = 'svg'
    Store.renderers['matplotlib'].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = \
        latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=2, cstride=2,
                              lw=0.2, edgecolors='k')
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[dimension_type] = pretty_fmt_complex

    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})
Esempio n. 18
0
def init_notebook():
    print_information()
    check_versions()

    code_dir = os.path.dirname(os.path.realpath(__file__))
    hv_css = os.path.join(code_dir, 'hv_widgets_settings.css')
    holoviews.plotting.widgets.SelectionWidget.css = hv_css

    holoviews.notebook_extension('matplotlib')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui='inline')

    Store.renderers['matplotlib'].fig = 'svg'
    Store.renderers['matplotlib'].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = \
        latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=2, cstride=2,
                              lw=0.2, edgecolors='k')
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[dimension_type] = pretty_fmt_complex

    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})
Esempio n. 19
0
def plot(filter, yaxis, filename, labels):
    # Set our formatting
    rc_file("matplotlibrc-violin")

    # Read the first CSV file and prepare the temp
    path_root = Path('data')
    temp = pd.read_csv(Path(path_root, filter.format(2025)),
                       index_col=0,
                       header=None).T
    replicates = temp.shape[0]
    studies = temp.shape[1]

    # Read the rest of the CSV files
    years = ['2025', '2030', '2035']
    data = np.zeros((len(years), replicates, studies))
    for i, yr in enumerate(years):
        data[i, :, :] = pd.read_csv(Path(path_root, filter.format(yr)),
                                    index_col=0,
                                    header=None).T

    # Violin plot, grouped by policy
    data_labels = temp.columns
    data_labels = labels
    fig, axs = plt.subplots(nrows=int(len(labels) / 3),
                            ncols=3,
                            figsize=(20, 25),
                            sharey=True,
                            sharex=True,
                            gridspec_kw={
                                'left': 0.09,
                                'right': 0.97,
                                'top': 0.95,
                                'bottom': 0.06,
                                'wspace': 0.2,
                                'hspace': 0.22
                            })

    # Format the sub plots
    for ax, (il, l) in zip(axs.flat, enumerate(data_labels)):
        ax.violinplot(data[:, :, il].T, positions=range(len(years)))
        ax.set_xticks(range(len(years)))
        ax.set_xticklabels(years)
        if il % 3 == 0:
            ax.set_ylabel(yaxis)
        if il // 3 == 2:
            ax.set_xlabel('Model year')
        ax.set_title(l, fontsize=20)

    # Save the figure to disk
    fig.savefig(filename)
Esempio n. 20
0
def plot_validation(datafile, imagefile):
    # Prepare the data
    dates, frequencies = prepare_validation(datafile)

    # Format the dates
    startDate = datetime.datetime.strptime(rwanda.STUDYDATE, "%Y-%m-%d")
    dates = [startDate + datetime.timedelta(days=x) for x in dates]

    # Calculate the bounds
    upper = np.percentile(frequencies, 97.5, axis=0)
    median = np.percentile(frequencies, 50, axis=0)
    lower = np.percentile(frequencies, 2.5, axis=0)

    # Format the plot
    matplotlib.rc_file('matplotlibrc-line')
    axes = plt.axes()
    axes.set_xlim([min(dates), max(dates)])
    axes.set_title('Rwanda 561H Frequency Validation')
    axes.set_ylabel('561H Genotype Frequency')
    axes.set_xlabel('Model Year')

    # Plot the 561H frequency
    plt.plot(dates, median)
    color = scale_luminosity(plt.gca().lines[-1].get_color(), 1)
    plt.fill_between(dates, lower, upper, alpha=0.5, facecolor=color)

    # Add the spike annotations
    plt.scatter(rwanda.SPIKES[:, rwanda.SPIKE_X],
                rwanda.SPIKES[:, rwanda.SPIKE_Y],
                color='black',
                s=50)
    for label, x, y in rwanda.SPIKES:
        plt.annotate(label, (x, y),
                     textcoords='offset points',
                     xytext=(0, 10),
                     ha='center',
                     fontsize=18)

    # Finalize the image as proof (png) or print (tif)
    if imagefile.endswith('tif'):
        plt.savefig(imagefile,
                    dpi=300,
                    format="tiff",
                    pil_kwargs={"compression": "tiff_lzw"})
    else:
        plt.savefig(imagefile)
    plt.close()
Esempio n. 21
0
def mplTheme(s=None):
	global mpl
	if not('mpl' in globals()): import matplotlib as mpl
	import os
	rcpath = os.getenv("HOME") + '/.config/matplotlib/'
	rcfile = None
	try:
		if s:
			rcfile = rcpath+s
			mpl.rc_file(rcfile)
		else:
			import random
			rclist = os.listdir(rcpath)
			rcfile = rcpath+rclist[random.randint(0, len(rclist)-1)]
			mpl.rc_file(rcfile)
	except IOError:
		pass
	return rcfile
Esempio n. 22
0
def mplTheme(s=None):
    global mpl
    if not ('mpl' in globals()): import matplotlib as mpl
    import os
    rcpath = os.getenv("HOME") + '/.config/matplotlib/'
    rcfile = None
    try:
        if s:
            rcfile = rcpath + s
            mpl.rc_file(rcfile)
        else:
            import random
            rclist = os.listdir(rcpath)
            rcfile = rcpath + rclist[random.randint(0, len(rclist) - 1)]
            mpl.rc_file(rcfile)
    except IOError:
        pass
    return rcfile
def main(argv):
    # Get the custom options
    rc_file("matplotlibrc.custom")

    # Set up the figure with the computed dimensions
    fig = plt.figure(figsize=figdims(500, 0.7))
    
    # Read the data and plot it
    data1 = np.genfromtxt('/Users/nbanglawala/Desktop/Work/ARCHER_CSE/CSE_Training/ScientificPython_NB/Exercises/matplotlib/code/random1.dat')
    plt.subplot(1,1,1)
    plt.plot(data1[:,0], data1[:,1], 'kx--', label='random1')

    # Axis labels
    plt.xlabel('Positions')
    plt.ylabel('Values')

    # Save in a nice format
    fig.tight_layout(pad=0.1)
    fig.savefig("publish.pdf", dpi=600)
Esempio n. 24
0
 def plot_eigen(eig_values):
     from matplotlib import pyplot as plt
     from matplotlib import rc_file
     rc_file('/Users/cpashartis/bin/rcplots/paper_multi.rc')
     
     f = plt.figure()
     ax = f.add_subplot(111)
     x = np.linspace(0,1,eig.shape[0])
     for i in range(eig.shape[1]):
         ax.plot(x, eig[:,i])
     labels = ['L', r'$\Gamma$', 'X', r'$\Gamma$']
     plt.xticks([0, 1/3., 2/3., 1], labels)
     lims = plt.ylim()
     plt.vlines([1/3.,2/3.],lims[0],lims[1], color = 'k', linestyle = '--')
     ax.set_title('Silicon Tight Binding')
     ax.set_ylabel('Energy (eV)')
     ax.set_ylim(-10, 7)
     f.savefig('Silicon_TB.pdf', dpi = 1000 )
     plt.close('all')
Esempio n. 25
0
def load_config_medium():
    # Import settings
    filename = inspect.getframeinfo(inspect.currentframe()).filename
    filepath = os.path.dirname(os.path.abspath(filename))
    rc_file(filepath+'/matplotlibrc_medium')
    
    mpl.rcParams['text.usetex'] = True
    mpl.rcParams['text.latex.unicode'] = True
    
    # Fonts
    mpl.rcParams['font.family'] = 'serif'
    mpl.rcParams['font.serif'] = 'Computer Modern'
    mpl.rcParams['font.size'] = 9 # Basis for relative fonts
    mpl.rcParams['axes.titlesize'] = 11
    mpl.rcParams['axes.labelsize'] = 9
    mpl.rcParams['xtick.labelsize'] = 8
    mpl.rcParams['ytick.labelsize'] = 8
    mpl.rcParams['legend.fontsize'] = 9
    
    # Miscellaneous
    mpl.rcParams['legend.numpoints'] = 1    
Esempio n. 26
0
def load_config_medium():
    # Import settings
    filename = inspect.getframeinfo(inspect.currentframe()).filename
    filepath = os.path.dirname(os.path.abspath(filename))
    rc_file(filepath + '/matplotlibrc_medium')

    mpl.rcParams['text.usetex'] = True
    mpl.rcParams['text.latex.unicode'] = True

    # Fonts
    mpl.rcParams['font.family'] = 'serif'
    mpl.rcParams['font.serif'] = 'Computer Modern'
    mpl.rcParams['font.size'] = 9  # Basis for relative fonts
    mpl.rcParams['axes.titlesize'] = 11
    mpl.rcParams['axes.labelsize'] = 9
    mpl.rcParams['xtick.labelsize'] = 8
    mpl.rcParams['ytick.labelsize'] = 8
    mpl.rcParams['legend.fontsize'] = 9

    # Miscellaneous
    mpl.rcParams['legend.numpoints'] = 1
	def apply(self, mode, content, decision, wide):
		if mode == "sync":
			mpl.rc_file("../rc/1fig-contour-rc.txt")

		elif mode == "usync":
			if decision in ("soft",):
				mpl.rc_file("../rc/1fig-contour-rc.txt")
			else:
				mpl.rc_file("../rc/2fig-contour-rc.txt")
Esempio n. 28
0
    def apply(self, mode, content, decision, wide):
        if mode == 'sync':
            mpl.rc_file('../1fig-contour-rc.txt')

        elif mode == 'usync':
            if decision in ('soft', ):
                mpl.rc_file('../1fig-contour-rc.txt')
            else:
                mpl.rc_file('../2fig-contour-rc.txt')
    def apply(self, mode, content, decision, wide):
        if mode == "sync":
            mpl.rc_file("../rc/1fig-contour-rc.txt")

        elif mode == "usync":
            if decision in ("soft", ):
                mpl.rc_file("../rc/1fig-contour-rc.txt")
            else:
                mpl.rc_file("../rc/2fig-contour-rc.txt")
Esempio n. 30
0
def test_rcparams(tmpdir):
    mpl.rc('text', usetex=False)
    mpl.rc('lines', linewidth=22)

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']

    rcpath = Path(tmpdir) / 'test_rcparams.rc'
    rcpath.write_text('lines.linewidth: 33', encoding='utf-8')

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewidth to 33)
    with mpl.rc_context(fname=rcpath):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=rcpath, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context as decorator (and test reusability, by calling func twice)
    @mpl.rc_context({'lines.linewidth': 44})
    def func():
        assert mpl.rcParams['lines.linewidth'] == 44

    func()
    func()

    # test rc_file
    mpl.rc_file(rcpath)
    assert mpl.rcParams['lines.linewidth'] == 33
outname = '%s/comparison_free_energy_plots.png' % (saveDir)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.cm as cm
from matplotlib import rc_file
import glob
import os
import sys
from matplotlib import rc_file

figCols = 1
figRows = 2

rc_file("rc_files/%s" % rcFile)

if not os.path.isdir(saveDir):
    os.mkdir(saveDir)

colormap = plt.cm.get_cmap('jet')
figTA, axTA = plt.subplots(1, 1)
Z = [[0, 0], [0, 0]
     ]  # Apparently you can't set a colorbar without a mappable. This is hack
numLevels = 25  ##Number of levels to show in color bar, should be equal to number of levels calculated.
vmin, vmax = -23.9, 0.0  ##min, max of dG in kJ/mol
levels = np.linspace(vmin, vmax, numLevels)  #   around that. Taken from :
CS3 = axTA.contourf(
    Z, levels, cmap=colormap
)  #   https://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
plt.close(figTA)
import matplotlib
import os
fp = os.path.dirname(os.path.abspath(__file__))
matplotlib.rc_file(fp + os.path.sep + 'file.rc')
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
from mpl_toolkits.basemap import Basemap
import sys
import map_utils as mu
import excel_interface as ex
import map_interactive as mi
import gui


def Create_interaction(**kwargs):
    #fig,ax = plt.subplots()
    m = mi.build_basemap()
    plt.gca().set_title('line segments')
    lat0, lon0 = mi.pll('22 58.783S'), mi.pll('14 38.717E')
    x0, y0 = m(lon0, lat0)
    line, = m.plot([x0], [y0], 'ro-')
    text = ('Press s to stop interaction\\n'
            'Press i to restart interaction\\n')
    #plt.text(1.0,0.1,text)
    wb = ex.dict_position(**kwargs)
    lines = mi.LineBuilder(line, m=m, ex=wb)
    print 'after line builder'
    plt.show()
    print 'after show'
Esempio n. 33
0
    "T": 'b'
}
stateToMarker = {"A": 'v', "B": 'D'}

with open('forces.dat', 'w') as f:
    f.write("Name      SolventFieldA   SolventFieldB    WeightedField\n")
with open('forces.dat', 'a') as f:
    for item in data:
        f.write("%s\t%f\t%f\t%f\n" % (item[0], item[1], item[2], item[3]))

names = np.genfromtxt('forces.dat', skip_header=1, usecols=0, dtype='str')
dataA = np.genfromtxt('forces.dat', skip_header=1, usecols=1)
dataB = np.genfromtxt('forces.dat', skip_header=1, usecols=2)
dataW = np.genfromtxt('forces.dat', skip_header=1, usecols=3)

rc_file('../force_rc.rc')
fig1, axarr = plt.subplots(1, 2, sharey='col')
#fig2, ax2 = plt.subplots(1,1)

ax1 = axarr[0]
ax2 = axarr[1]

ax1.set_xlabel(r"Experimental frequency (cm$^{-1}$)")
ax2.set_xlabel(r"Experimental frequency (cm$^{-1}$)")
ax1.set_ylabel(r"Calculated Field (k$_b$T/$e\AA$)")

CN145, CN165 = [], []
for i in range(len(dataW)):
    if names[i][:5] == 'CN145':
        CN145.append([mutToExp[names[i]], dataW[i]])
        ax1.scatter(mutToExp[names[i]],
Esempio n. 34
0
import os
import argparse
# Numerical utilities
import numpy as np
import pandas
# Other utilities
import itertools
import glob
import matplotlib as mpl
mpl.use("agg")
import matplotlib.pyplot as plt

from matplotlib.ticker import FormatStrFormatter
from astropy.cosmology import WMAP7

mpl.rc_file('/data/compactgroups/Evolution/matplotlibrc')


def main(datadir='/data',
         resultsdirs=['results'],
         plotsdir='plots',
         labels=['results'],
         counts_file='galaxy_counts.txt',
         snapnum_file='snapnum_redshift.csv',
         dwarf_limit=0.05,
         plotlabel='',
         evolution=False):
    """
    Plot results of Millennium Simulation compact group analysis
    """
    if not os.path.isdir(datadir):
from torch.utils.data import TensorDataset
from fastai.callbacks.tracker import SaveModelCallback

import my_matplotlib_style as ms

from fastai import basic_train, basic_data
from fastai.callbacks import ActivationStats
from fastai import train as tr

from my_nn_modules import AE_basic, AE_bn, AE_LeakyReLU, AE_bn_LeakyReLU, AE_big, AE_3D_50, AE_3D_50_bn_drop, AE_3D_50cone, AE_3D_100, AE_3D_100_bn_drop, AE_3D_100cone_bn_drop, AE_3D_200, AE_3D_200_bn_drop, AE_3D_500cone_bn, AE_3D_500cone_bn
from my_nn_modules import get_data, RMSELoss
from utils import plot_activations

import matplotlib as mpl
mpl.rc_file(BIN + 'my_matplotlib_rcparams')

print('torch.cuda.is_available(): ' + str(torch.cuda.is_available()))

lr = 1e-3
wds = 1e-5
pp = 0

save_dict = {}

# Load data
# train = pd.read_pickle(BIN + 'processed_data/aod/scaled_all_jets_partial_train.pkl')
# test = pd.read_pickle(BIN + 'processed_data/aod/scaled_all_jets_partial_test.pkl')
# train = pd.read_pickle(BIN + 'processed_data/aod/scaled_all_jets_partial_train_10percent.pkl')  # Smaller dataset fits in memory on Kebnekaise
# test = pd.read_pickle(BIN + 'processed_data/aod/scaled_all_jets_partial_test_10percent.pkl')
train = pd.read_pickle(BIN + 'processed_data/aod/custom_normalized_train_10percent')
import lomb
from astroML.density_estimation import histogram as hst

from matplotlib.ticker import MaxNLocator, AutoMinorLocator
my_locator = MaxNLocator(10)
minor2a = AutoMinorLocator(2)
minor2b = AutoMinorLocator(2)
minor4 = AutoMinorLocator(4)

# Set up axes and plot some awesome science

import utils

from matplotlib import rc_file
#rc_file('/Users/mikemon/.matplotlib/matplotlibrc_apj')
rc_file('matplotlibrc_apj')

# Read in file of maximum peaks from shuffled data sets
infile = 'Q11-Q17lc_nooutliers_tot.hist'

print '\nReading in peak values...'

vars = np.loadtxt(infile)
amp = vars[:, 0]
pow = vars[:, 1]

amp = 1.e+3 * amp  # put in mmas

print 'Largest peak is', max(amp)

# "Fancy" histogram from astroML
Esempio n. 37
0
"""
Simple proposal-writing experiment: For a given signal-to-noise in a line, what
signal-to-noise do you get in a derived parameter (e.g., temperature)?
"""
import pyradex
import pylab as pl
import numpy as np
import matplotlib
import astropy.units as u
import os

# for pretty on-screen plots
if os.path.exists('/Users/adam/.matplotlib/ggplotrc'):
    matplotlib.rc_file('/Users/adam/.matplotlib/ggplotrc')

# Download the data file if it's not here already
if not os.path.exists('ph2cs.dat'):
    import urllib
    import shutil
    fn,msg = urllib.urlretrieve('http://home.strw.leidenuniv.nl/~moldata/datafiles/ph2cs.dat')
    shutil.move(fn,'ph2cs.dat')

# Formatting tool
def latex_float(f):
    float_str = "{0:.1g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
    else:
        return float_str
Esempio n. 38
0
                                 (1-np.exp(-(10**row['logh2column']/1e24)))),
                  gmc=gmc)
    print("Chemical equilbrium temperature: ",T1)
    cool1 = gmc.dEdt(PsiUser=turb_heating_generator(lengthscale))
    print("CO cooling: ",cool1['LambdaLine']['co'])
    print("O cooling: ",cool1['LambdaLine']['o'])
    print("C cooling: ",cool1['LambdaLine']['c'])
    print("C+ cooling: ",cool1['LambdaLine']['c+'])
    print("oH2 cooling: ",cool1['LambdaLine']['oh2'])
    print("pH2 cooling: ",cool1['LambdaLine']['ph2'])
    print("HD cooling: ",cool1['LambdaLine']['hd'])


if __name__ == "__main__":
    import matplotlib
    matplotlib.rc_file(paths.pcpath('pubfiguresrc'))

    densities = np.logspace(3,7,20)
    tem = [tkin_all(n*u.cm**-3, 10*u.km/u.s, lengthscale=5*u.pc,
                    gradient=5*u.km/u.s/u.pc, tdust=25*u.K,
                    crir=1e-17*u.s**-1) for n in ProgressBar(densities)]
    pl.figure(1)
    pl.clf()
    pl.plot(densities, tem, 'k--', label='CRIR=1e-17, $\sigma=10$ km/s')
    pl.xlabel(r'$\log\,N_{\rm H}$')
    pl.ylabel('Temperature (K)')
    pl.xscale('log')
    pl.legend(loc='best')
    pl.savefig(paths.fpath("despotic/TvsN.png"))

"""
Makes plots illustrating the bias in fitting.
This program creates plots for the paper illustrating
the fit bias by fitting noisy realizations of the same
true data many times.  It plots two-dimensional histograms
of the fitted velocity and fitted acceleration. Three
accelerations are considered - one positive, one
negative, and no acceleration
"""

import os
import matplotlib
from matplotlib import rc_file
matplotlib_file = '~/eitwave/eitwave/matplotlibrc_paper1.rc'
rc_file(os.path.expanduser(matplotlib_file))
matplotlib.rcParams.update({'font.size': 18})

this_file = 'test_fitbias_fitted_v_versus_a'

# Where to save the data.
image_directory = os.path.expanduser('~/eitwave/img/{:s}'.format(this_file))

image_root_name = this_file

import re
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.rcParams['text.usetex'] = True
import astropy.units as u
from statsmodels.robust import mad
Esempio n. 40
0
#Show 7 images in one figure for fits output
#preprocess: fits_trans.sh

import numpy as np

# Set up matplotlib and use a nicer set of plot parameters
import matplotlib
#from matplotlib import text
matplotlib.rc_file("matplotlibrc")
import matplotlib.pyplot as plt

import sys

from astropy.io import fits

# Log scale
from astropy.visualization import scale_image

def image_cut(image_r,image_g,image_b,offset_ratio,smooth_ratio,invert=False):
    isize=image_r.shape
    isize_min=np.min(isize)
    if (isize!=image_b.shape) | (isize!=image_g.shape):
        print 'Warning: Image size not equal!'
    image_rgba=np.zeros(shape=(isize_min,isize_min,4))
    xshift=(isize[0]-isize_min)/2
    yshift=(isize[1]-isize_min)/2
    if invert:
        image_rgba[:,:,0]=1.0-image_r[xshift:xshift+isize_min,yshift:yshift+isize_min]
        image_rgba[:,:,1]=1.0-image_g[xshift:xshift+isize_min,yshift:yshift+isize_min]
        image_rgba[:,:,2]=1.0-image_b[xshift:xshift+isize_min,yshift:yshift+isize_min]
    else:
Esempio n. 41
0
import numpy as np
import matplotlib as mpl
#mpl.use('Agg')
mpl.rc_file('~/.config/matplotlib/matplotlibrc')  # <-- the file containing your settings
import matplotlib.pyplot as plt


def fig_save_many(f, name, types=[".png",".pdf"], dpi=200):
    for ext in types:
        f.savefig(name+ext, dpi=dpi)
    return

def paper_single(TW = 6.64, AR = 0.74, FF = 1., fontsize=18.0, fontst="Times"):
    '''paper_single(TW = 6.64, AR = 0.74, FF = 1.)
    TW = 3.32
    AR = 0.74
    FF = 1.
    #mpl.rc('figure', figsize=(4.5,3.34), dpi=200)
    mpl.rc('figure', figsize=(FF*TW, FF*TW*AR), dpi=200)
    mpl.rc('figure.subplot', left=0.18, right=0.97, bottom=0.18, top=0.9)
    mpl.rc('lines', linewidth=1.0, markersize=4.0)
    mpl.rc('font', size=9.0, family="serif", serif="CM")
    mpl.rc('xtick', labelsize='small')
    mpl.rc('ytick', labelsize='small')
    mpl.rc('axes', linewidth=0.75)
    mpl.rc('legend', fontsize='small', numpoints=1, labelspacing=0.4, frameon=False) 
    mpl.rc('text', usetex=True) 
    mpl.rc('savefig', dpi=300)
    '''
    #import matplotlib as mpl
    # textwidht = 42pc = 42 * 12 pt = 42 * 12 * 1/72.27 inches
#   
#   
# Modification History:
# 
#     Wrtten: Samuel LeBlanc, NASA Ames, 2018-05-30
#     Modified:

# # Load the defaults modules and setup

# In[1]:


get_ipython().magic(u'config InlineBackend.rc = {}')
import matplotlib 
import os
matplotlib.rc_file(os.path.join(os.getcwd(),'file.rc'))
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import Sp_parameters as Sp
from load_utils import mat2py_time, toutc, load_ict
from Sp_parameters import smooth
from linfit import linfit
from path_utils import getpath
from plotting_utils import make_boxplot


# In[2]:


get_ipython().magic(u'matplotlib notebook')
import pylab as pl
import matplotlib
matplotlib.rc_file('pubfiguresrc')

from aplpy_figure_maker import FITSFigure
from paths import dpath, fpath

for label in ("","lower","upper"):
    files = [dpath(label+'peak_optdepth_11.fits'),
             dpath(label+'peak_optdepth_22.fits'),
             dpath(label+'peak_optdepth_ratio.fits'),
             dpath(label+'peak_optdepth_11_tex1.0.fits'),
             dpath(label+'peak_optdepth_22_tex1.5.fits'),
             dpath(label+'peak_optdepth_ratio_tex1.0_1.5.fits')]

    for ii in xrange(1,len(files)+1):
        pl.figure(ii)
        pl.clf()

    figs = [FITSFigure(fn, figure=pl.figure(ii+1))
            for ii,fn in enumerate(files)]

    for fig,fn in zip(figs,files):
        if '11' in fn:
            cblabel = (r'$\tau_{1-1}$')
        elif '22' in fn:
            cblabel = (r'$\tau_{2-2}$')
        elif 'ratio' in fn:
            cblabel = (r'$\tau_{1-1} / \tau_{2-2}$')
        else:
            raise ValueError("This is not a file: {0}".format(fn))
Esempio n. 44
0
for i in range(len(data_points)):
    print molec_list[i] + "   " + str(data_points[i]) + "  " + str(errors[i])

##Fit line to data
z = np.polyfit(exp_peaks, data_points, 1)
print np.poly1d(z)

slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(
    exp_peaks, data_points)

x = np.linspace(exp_peaks.min(), exp_peaks.max())
y = intercept + x * slope
print r_value

## Begin plotting
rc_file('quals_fig.rc')

plt.scatter(exp_peaks, data_points)
#plt.plot(x,y)
#plt.xticks(np.linspace(2235.6,2235.85,6),np.linspace(2235.6,2235.85,6))
#plt.title('Experimental Frequency v Calculated Field')
plt.xlabel(r"Experimental Frequency (cm$^{-1}$)")
plt.ylabel(r"Calculated Field ($\frac{k_b T}{e^- \AA}$)")

#plt.savefig("quals_calc_v_exp_no_error.pdf",format='pdf')

plt.xlim(2234.5, 2237)
plt.xticks(np.linspace(2234.5, 2237, 6), np.linspace(2234.5, 2237, 6))
plt.ylim(1340, 1400)
#plt.yticks(range(1340,1400,5), range(1340,1400,5))
plt.errorbar(exp_peaks, data_points, errors, exp_error, ecolor='b')
from yt.mods import *
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import gc
import sys
from astropy.io import ascii
from os.path import expanduser

# import ramses helper functions and get figure directory
homedir = expanduser('~')+'/'
sys.path.append(homedir+'pythonhelpers/ramses/')
from ramses_helpers import *
mpl.rc_file(homedir+'pythonhelpers/ramses/matplotlibrc')
outdir = get_output_path(homedir)

# set some fonts
fontdir = homedir+'/Documents/astronomy/macfontsforpython/'
tfm = fm.FontProperties( # tick font
    fname=fontdir+'Gotham-Book.ttf', size=13)
lfm = fm.FontProperties( # label font main
    fname=fontdir+'Gotham-BookItalic.ttf', size=12)
    
fig = plt.figure(figsize = (5,3.5))

ax = fig.add_axes([0.2, 0.2, 0.75, 0.75])
#ax = fig.add_axes([0., 0., 1., 1.])

times = []
Esempio n. 46
0
#   - 20151117_zen_cld_retrieved.mat: cloud retrieval file
#   - MYD06_L2.A2015321.1540.006.2015322185040.hdf: MODIS file
#   
# Modification History:
# 
#     Written: Samuel LeBlanc, NASA Ames, Santa Cruz, CA, 2016-04-06
#     Modified: 

# # Import initial modules and default paths
# 

# In[2]:

get_ipython().magic(u'config InlineBackend.rc = {}')
import matplotlib 
matplotlib.rc_file('C:\\Users\\sleblan2\\Research\\python_codes\\file.rc')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import scipy.io as sio
import Sp_parameters as Sp
import hdf5storage as hs
import load_utils as lm
import os


# In[3]:

from mpl_toolkits.basemap import Basemap,cm

Esempio n. 47
0
import matplotlib.pyplot as plt
import os
from os import sys
from matplotlib.colors import LogNorm
import matplotlib.lines as mlines
from scipy.stats import linregress
from matplotlib import rc_file

rcFile = 'rc_files/paper.rc'

molecList = [
    "D", "E", "F", "H", "I", "K", "L", "M", "N", "Q", "R", "S", "T", "V", "W",
    "Y"
]

rc_file(rcFile)

if not os.path.isdir('figures'):
    os.mkdir('figures')

##Load in color and marker keys
plotKeys = {}
with open('Plotting_files/ColorMarkerKeys.txt') as f:
    lines = f.readlines()
    for line in lines:
        if line.startswith('#'):
            continue
        else:
            key = line.split()[0]
            value = line.split()[1:]
            plotKeys[key] = value
Esempio n. 48
0
import numpy
from sys import exit
from os import path
import numpy as np
from plotypus.lightcurve import get_lightcurve_from_file, make_predictor
from plotypus.preprocessing import Fourier
from plotypus.periodogram import rephase
from plotypus.utils import colvec, get_noise
from plotypus.resources import matplotlibrc
from sklearn.linear_model import LinearRegression, LassoCV, LassoLarsIC
from sklearn.pipeline import Pipeline

import matplotlib
matplotlib.use('Agg')
from matplotlib import rc_file
rc_file(matplotlibrc)
import matplotlib.pyplot as plt

color = True

def main():
    directory = path.join('data', 'I')
    name = 'OGLE-LMC-CEP-0227'
    filename = name+'.dat'
    p = 3.7970428
    X_true = numpy.arange(0, 1, 0.001)
    output = get_lightcurve_from_file(path.join(directory, filename),
                 period=p, phases=X_true, sigma_clipping='standard', sigma=7,
                 predictor=make_predictor(LinearRegression(), use_baart=True,
                                          fourier_degree=(2,15)))
    fit = output['lightcurve']
import numpy as np 
from matplotlib import rc_file 

import sys 
import os.path

def Usage(): 
    print "Usage %s < file to be plotted > [additional file(s)]" %(sys.argv[0]) 

if len(sys.argv) == 1 : 
    Usage() 
    print "ERROR: You must supply at least one file name" 
    sys.exit() 

for arg in sys.argv[1:] : 
    try : 
        fileName = arg
        data = np.genfromtxt(fileName) 
    except : 
        Usage() 
        print "ERROR:  file not able to be opened." 
        sys.exit() 
    
    outName = os.path.splitext(fileName)[0]+".pdf"
    print "%s => %s" %(fileName, outName) 
    
    rc_file("paper.rc") 
    
    plt.plot(data[:,0],data[:,1]) 
    plt.savefig(outName,format="pdf") 
Esempio n. 50
0
VmStd = 0.070  # Standard deviation of molecular volume (determined from Experiment)


###
#  Given an input array and a target value, return the closest
###
def find_nearest(array, value):
    array = np.asarray(array)
    idx = np.argmin(np.abs(array - value))
    return idx


###
#  Figure set up and labeling
###
rc_file('rc_files/paper.rc')

left, right = 0.12, 0.98
bottom, top = 0.05, 0.98
hspace, wspace = 0.25, 0.00

fig, axarr = plt.subplots(3, 1, figsize=(3.25, 6))
fig.subplots_adjust(left=left,
                    right=right,
                    top=top,
                    bottom=bottom,
                    hspace=hspace,
                    wspace=wspace)
fig.text(0.01,
         top - (top - bottom - hspace / 2) / 6,
         "Number of waters",
import os
import aplpy
from astropy.io import fits
import pylab as pl
import itertools
import multiplot
import mpl_plot_templates
import numpy as np
from agpy import fit_a_line
import astropy.units as u
import common_constants
from common_constants import h2co11freq, h2co22freq, etamb_77, rrl, aobeamarea, gbbeamarea
from paths import datapath, fpath
import matplotlib

matplotlib.rc_file("pubfiguresrc")
pl.mpl.rcParams["axes.color_cycle"] = [
    "#" + x for x in "348ABD, 7A68A6, A60628, 467821, CF4457, 188487, E24A33".split(", ")
]

# Have to convert to Jy to compare fairly
ktojy111 = (1 * u.K).to(u.Jy, u.brightness_temperature(aobeamarea, h2co11freq))
ktojy77 = (1 * u.K).to(u.Jy, u.brightness_temperature(gbbeamarea, h2co22freq))

aofn = os.path.join(datapath, "W51_Halpha_6cm_cube_supersampled.fits")
h112i = (
    fits.getdata(os.path.join(datapath, "H110a_integral.fits")) * ktojy111
)  # ,aofn.replace("cube","integrated"))) * ktojy111
h112a = fits.getdata(os.path.join(datapath, "H110a_amplitude.fits")) * ktojy111
h112a.value[h112a == 0] = np.nan
h112c = fits.getdata(os.path.join(datapath, "W51_Halpha_6cm_cube_supersampled_continuum.fits")) * ktojy111
Esempio n. 52
0
                test_mc_input_variables_b.append([x_1,x_2,x_3])
            test_mc_label.append(s_or_b)
    else:
        if train_or_test == 0:
            train_data_input_variables.append([x_1,x_2,x_3])
        else:
            if s_or_b == 1:
                test_data_input_variables_s.append([x_1,x_2,x_3])
            else:
                test_data_input_variables_b.append([x_1,x_2,x_3])
            test_data_label.append(s_or_b)

import matplotlib.pylab as plt

import matplotlib
matplotlib.rc_file("../lhcb-matplotlibrc/matplotlibrc")
fig1, axs1 = plt.subplots(nrows=1, ncols=1, figsize=(12,6))
axs1.hist(np.array(test_mc_input_variables_s)[:,0],label="signal",range=[-5,5],alpha=0.5,bins=50)
axs1.hist(np.array(test_mc_input_variables_b)[:,0],label="background",range=[-5,5],alpha=0.5,bins=50)
plt.xlabel("x1")
plt.title("distinguishes signal/background (perfectly simulated)")
plt.legend(loc="best")
fig1.show()


fig2, axs2 = plt.subplots(nrows=1, ncols=1, figsize=(12,6))
axs2.hist(np.array(test_mc_input_variables_s)[:,1],label="MC",range=[-5,5],alpha=0.5,bins=50)
#axs2.hist(np.array(test_mc_input_variables_b)[:,1],label="background MC",range=[-5,5],alpha=0.5,bins=50)
axs2.hist(np.array(test_data_input_variables_s)[:,1],label="DATA",range=[-5,5],alpha=0.5,bins=50)
#axs2.hist(np.array(test_data_input_variables_b)[:,1],label="background DATA",range=[-5,5],alpha=0.5,bins=50)
plt.xlabel("x2")
import numpy as np
import os

from collections import Counter
from graph_helpers import all_pairs_bellman_ford_path
from graph_helpers import create_networkx_area_graph, create_networkx_graph
from helpers import area_list, area_population_list
from helpers import datapath
from itertools import product
from helpers import structural_gradient, hierarchical_relation, write_out_lw
from matplotlib import rc_file
from multiarea_model import MultiAreaModel
from multiarea_model.multiarea_helpers import create_mask
from plotcolors import myblue

rc_file('plotstyle.rc')
"""
Load data and create MultiAreaModel instance
"""
with open(os.path.join(datapath, 'viscortex_processed_data.json'), 'r') as f:
    proc = json.load(f)
SLN_completed = proc['SLN_completed']
SLN_Data_FV91 = proc['SLN_Data_FV91']
arch_types = proc['architecture_completed']

par = {'connection_params': {'g': -4.}}
M = MultiAreaModel(par, theory=True, simulation=False)

gain_matrix = M.K_matrix[:, :-1] * np.absolute(M.J_matrix[:, :-1])
eig = np.linalg.eig(gain_matrix)
gain_matrix_rescaled = gain_matrix / np.max(np.real(eig[0]))
Esempio n. 54
0
def loadstyle(style_name):
    """ Load a custom style file, adding both rcParams and custom params.
    Writing a proper parser for these settings is in the Matplotlib backlog,
    so let's keep calm and avoid inventing their wheel.
    """

    style = {}
    style_file = os.path.join(HERE, '..', 'rc', style_name)
    try:
        # Check rc directory for built in styles first
        rc_file(style_file)
    except FileNotFoundError:
        # Check current working dir or path
        style_file = style_name
        try:
            rc_file(style_file)
        except FileNotFoundError as err:
            raise StyleNotFoundError(f"No such style file found: {err}")
    style = rcParams.copy()

    # The style files may also contain an extra section with typography
    # for titles and captions (these can only be separately styled in code,
    # as of Matplotlib 2.2)
    # This is a hack, but it's nice to have all styling in one file
    # The extra styling is prefixed with `#!`
    with open(style_file, 'r') as file_:
        doc = file_.readlines()
        rc_params_newsworthy = "\n".join(
            [d[2:] for d in doc if d.startswith("#!")])
    rc_params_newsworthy = yaml.safe_load(rc_params_newsworthy)
    ###
    # Typography
    ###
    style["title_font"] = [
        x.strip() for x in rc_params_newsworthy["title_font"].split(",")
    ]

    # define as pt or reltive ("smaller")
    style["subtitle.fontsize"] = rc_params_newsworthy.get(
        "subtitle.fontsize", None)

    # make annotation same font size as ticks by default
    tick_font_size = style.get('xtick.labelsize', "smaller")
    style["annotation.fontsize"] = rc_params_newsworthy.get(
        "annotation.fontsize", tick_font_size)
    style["note.fontsize"] = rc_params_newsworthy.get("note.fontsize",
                                                      "smaller")
    style["caption.fontsize"] = rc_params_newsworthy.get(
        "caption.fontsize", "smaller")

    color = rc_params_newsworthy.get("neutral_color",
                                     rcParams["figure.edgecolor"])
    black_color = rc_params_newsworthy.get("black_color", BLACK)
    dark_gray_color = rc_params_newsworthy.get("dark_gray_color", DARK_GRAY)
    light_gray_color = rc_params_newsworthy.get("light_gray_color", LIGHT_GRAY)
    strong_color = rc_params_newsworthy.get("strong_color", color)
    positive_color = rc_params_newsworthy.get("positive_color", POSITIVE)
    negative_color = rc_params_newsworthy.get("negative_color", NEGATIVE)
    warm_color = rc_params_newsworthy.get("warm_color", WARM)
    cold_color = rc_params_newsworthy.get("cold_color", COLD)
    fill_between_color = rc_params_newsworthy.get("fill_between_color",
                                                  FILL_BETWEEN)
    fill_between_alpha = rc_params_newsworthy.get("fill_between_alpha", 0.5)
    style["black_color"] = to_rgba("#" + str(black_color), 1)
    style["dark_gray_color"] = to_rgba("#" + str(dark_gray_color), 1)
    style["light_gray_color"] = to_rgba("#" + str(light_gray_color), 1)
    style["neutral_color"] = to_rgba("#" + str(color), 1)
    style["strong_color"] = to_rgba("#" + str(strong_color), 1)
    style["positive_color"] = to_rgba("#" + positive_color, 1)
    style["negative_color"] = to_rgba("#" + negative_color, 1)
    style["warm_color"] = to_rgba("#" + warm_color, 1)
    style["cold_color"] = to_rgba("#" + cold_color, 1)
    style["fill_between_color"] = to_rgba("#" + str(fill_between_color), 1)
    style["fill_between_alpha"] = float(fill_between_alpha)

    if "qualitative_colors" in rc_params_newsworthy:
        style["qualitative_colors"] = [
            to_rgba("#" + c.strip(), 1)
            for c in rc_params_newsworthy["qualitative_colors"].split(",")
        ]

    else:
        style["qualitative_colors"] = [
            to_rgba("#" + c, 1) for c in QUALITATIVE
        ]
    if "logo" in rc_params_newsworthy:
        style["logo"] = rc_params_newsworthy["logo"]

    return style
__author__ = 'shaleen'

from matplotlib import rc_file
rc_file('matplotlibrc-singlecolumn')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

#ordering 'disagreementCount', 'bucketEntropy', 'TsallisEntropy', 'disagreementEntropyCount' size 250
neighbors_of_random = [[0.8032128514056225, 0.0, 0.40160642570281124, 0.0, 0.0, 0.40160642570281124, 1.2048192771084338, 0.40160642570281124, 2.0080321285140563, 33.734939759036145, 0.40160642570281124, 10.040160642570282, 1.606425702811245, 0.0, 0.0, 0.40160642570281124, 0.0, 1.606425702811245, 0.0, 0.0, 0.0, 32.1285140562249, 0.0, 0.0, 17.269076305220885, 6.024096385542169, 0.40160642570281124, 0.0, 0.0, 2.4096385542168677, 0.0, 6.827309236947791, 4.016064257028113, 68.27309236947791], [0.8472972698490899, 0.0, 0.47424844238607156, 0.0, 0.0, 0.47424844238607156, 1.421863631971465, 0.47424844238607156, 2.267389145099985, 38.67717753750235, 0.47424844238607156, 11.765298477476149, 1.8952279929600468, 0.0, 0.0, 0.47424844238607156, 0.0, 1.8952279929600468, 0.0, 0.0, 0.0, 36.89590920731144, 0.0, 0.0, 20.111666552189046, 7.082354676509695, 0.47424844238607156, 0.0, 0.0, 2.8410642086342808, 0.0, 8.021475430629266, 4.72913216819083, 74.87444460098057], [1.5935226851179873, 0.0, 0.799987096982302, 0.0, 0.0, 0.799987096982302, 2.39028402767697, 0.799987096982302, 3.964452186255063, 55.95393622683504, 0.799987096982302, 19.03195109756294, 3.180593861389336, 0.0, 0.0, 0.799987096982302, 0.0, 3.180593861389336, 0.0, 0.0, 0.0, 53.805583780906765, 0.0, 0.0, 31.48658892598506, 11.661102240286446, 0.799987096982302, 0.0, 0.0, 4.751536265544109, 0.0, 13.161078047128271, 7.854712020773857, 89.65984419606136], [12.562811021079627, 0.0, 0.0, 0.0, 0.0, 0.0, 19.911584372057668, 0.0, 29.169943860605375, 80.30547576912433, 0.0, 58.33988772121075, 25.125622042159254, 0.0, 0.0, 0.0, 0.0, 25.125622042159254, 0.0, 0.0, 0.0, 79.42118794492387, 0.0, 0.0, 68.16913866366745, 49.08152823266305, 0.0, 0.0, 0.0, 32.47439539313729, 0.0, 51.35002323031321, 41.732754881685004, 93.08277811199822]]
neighbors_of_d = [[0.8032128514056225, 0.0, 1.606425702811245, 0.0, 0.0, 0.40160642570281124, 2.0080321285140563, 2.8112449799196786, 0.8032128514056225, 34.53815261044177, 0.40160642570281124, 6.827309236947791, 4.016064257028113, 0.8032128514056225, 2.0080321285140563, 0.0, 0.0, 0.8032128514056225, 0.0, 0.40160642570281124, 0.0, 20.883534136546185, 0.0, 0.0, 18.87550200803213, 4.819277108433735, 0.0, 0.0, 0.0, 1.2048192771084338, 0.0, 7.6305220883534135, 3.6144578313253013, 69.07630522088354], [0.9482033824682046, 0.0, 1.8952279929600468, 0.0, 0.0, 0.47424844238607156, 2.3682952577190997, 3.313533618069686, 0.9482033824682046, 39.565175354845586, 0.47424844238607156, 8.021475430629266, 4.72913216819083, 0.9482033824682046, 2.3682952577190997, 0.0, 0.0, 0.9482033824682046, 0.0, 0.47424844238607156, 0.0, 24.242505500645795, 0.0, 0.0, 21.9512046157064, 5.671343858453026, 0.0, 0.0, 0.0, 1.421863631971465, 0.0, 8.959341197236348, 4.257568851102123, 75.65425286524079], [1.5967484395412956, 0.0, 3.180593861389336, 0.0, 0.0, 0.799987096982302, 3.9676779406783713, 5.532168835986518, 1.5967484395412956, 57.0087579232593, 0.799987096982302, 13.161078047128271, 7.854712020773857, 1.5967484395412956, 3.9676779406783713, 0.0, 0.0, 1.5967484395412956, 0.0, 0.799987096982302, 0.0, 37.321978677763255, 0.0, 0.0, 34.112353026564094, 9.386945371848842, 0.0, 0.0, 0.0, 2.39028402767697, 0.0, 14.64815083627683, 7.083756713601397, 90.15983613167529], [12.562811021079627, 0.0, 25.125622042159254, 0.0, 0.0, 0.0, 29.169943860605375, 35.2682693549074, 12.562811021079627, 80.73194968474708, 0.0, 51.35002323031321, 41.732754881685004, 12.562811021079627, 29.169943860605375, 0.0, 0.0, 12.562811021079627, 0.0, 0.0, 0.0, 71.61354691606296, 0.0, 0.0, 69.78125004342186, 45.03720641421692, 0.0, 0.0, 0.0, 19.911584372057668, 0.0, 53.365910582636445, 39.823168744115335, 93.2947607058267]]
random_subset = [[6.626506024096386, 0.0, 96.3855421686747, 0.8032128514056225, 2.4096385542168677, 32.53012048192771, 98.79518072289157, 98.39357429718875, 94.37751004016064, 100.0, 34.53815261044177, 100.0, 100.0, 88.75502008032129, 88.35341365461848, 68.67469879518072, 3.21285140562249, 93.57429718875503, 21.285140562248998, 63.45381526104418, 0.0, 100.0, 0.0, 0.0, 100.0, 100.0, 24.899598393574298, 2.4096385542168677, 21.285140562248998, 82.73092369477912, 4.417670682730924, 100.0, 99.59839357429719, 100.0], [26.742941465714242, 0.0, 98.56060835864643, 0.8472972698490899, 2.0585486569924205, 17.66999212592846, 99.76010139310773, 99.25557083001218, 93.6894625708574, 100.0, 35.055475435077746, 100.0, 100.0, 92.90600070182995, 92.45038949562961, 74.03555043607616, 3.7857022482435942, 96.56919217095015, 20.384627259574305, 70.02032410898005, 0.0, 100.0, 0.0, 0.0, 100.0, 100.0, 28.797152355512367, 2.0585486569924205, 24.598758516349093, 86.15825776118015, 5.200390930524257, 100.0, 100.0, 100.0], [71.75690714665892, 0.0, 99.48226641505782, 1.5935226851179873, 4.703149949194363, 50.21854486217965, 99.58871631102724, 99.56613603006403, 99.16614248157288, 99.59839357429718, 56.81521265786036, 99.59839357429718, 99.59839357429718, 98.3693811390139, 98.27260850631441, 89.85661521588362, 6.309575652005616, 99.20485153465268, 37.73487524394768, 86.38570345639587, 0.0, 99.59839357429718, 0.0, 0.0, 99.59839357429718, 99.59839357429718, 43.49929839841293, 4.703149949194363, 37.95100079030983, 96.60489346946018, 8.622441573523009, 99.59839357429718, 99.59839357429718, 99.59839357429718], [89.69283441547951, 0.0, 99.33277231698155, 12.562811021079627, 32.47439539313729, 79.64633748823067, 99.7803087627606, 99.70648257042019, 98.95119390402722, 100.0, 80.73194968474708, 100.0, 100.0, 97.8379481042169, 97.75575156805262, 93.1890793267518, 37.688433063238875, 98.79628436988448, 71.95878221445399, 91.7560172787485, 0.0, 100.0, 0.0, 0.0, 100.0, 100.0, 74.8014430297999, 32.47439539313729, 71.95878221445399, 96.56405353643169, 43.46018566528797, 100.0, 99.92706507195915, 100.0]]
ring = [[42.94975688816856, 0.0, 81.19935170178282, 0.0, 0.0, 0.0, 95.13776337115073, 84.76499189627229, 85.73743922204214, 99.3517017828201, 0.0, 95.78606158833063, 94.81361426256078, 87.03403565640194, 84.92706645056727, 79.90275526742302, 0.0, 86.54781199351702, 0.0, 73.257698541329, 0.0, 98.05510534846029, 0.0, 0.0, 99.18962722852513, 84.44084278768233, 0.0, 0.0, 0.0, 78.44408427876823, 0.0, 94.81361426256078, 92.86871961102106, 99.67585089141005], [15.111036059612859, 0.0, 34.83042504970778, 0.0, 0.0, 0.0, 32.021976488769965, 29.50033454055444, 32.629717326720794, 80.24689498853841, 0.0, 46.96863239170741, 44.55440483273973, 28.08906089002885, 27.256581561877347, 7.809459902297244, 0.0, 45.68595428607559, 0.0, 9.037987073705544, 0.0, 73.91819129514788, 0.0, 0.0, 66.75666491256797, 49.24194241727926, 0.0, 0.0, 0.0, 17.670718439098685, 0.0, 50.84796550705407, 40.921680636864174, 92.72795913426553], [57.802563247165004, 0.0, 87.30853794041855, 0.0, 0.0, 0.0, 79.98339852215327, 82.18151824717815, 86.66969626125262, 99.27683752354284, 0.0, 93.11327619132678, 92.7034928773881, 82.54454423426996, 79.33877784753433, 32.1165045483321, 0.0, 92.98613829136119, 0.0, 39.18158917121325, 0.0, 98.9479601459459, 0.0, 0.0, 98.23294079944522, 94.12985402782849, 0.0, 0.0, 0.0, 61.77903748203914, 0.0, 95.16324348746615, 91.56398004670478, 99.70868609284744], [86.84581436952867, 0.0, 96.75848765094466, 0.0, 0.0, 0.0, 99.22419890752894, 97.42737853136819, 97.60492250543106, 99.89876699517178, 0.0, 99.32990063549778, 99.17107762858085, 97.83854069429557, 97.45711019202945, 96.50794671412118, 0.0, 97.75134427787332, 0.0, 95.15652625889639, 0.0, 99.69430402703202, 0.0, 0.0, 99.87335552891759, 97.36774428361466, 0.0, 0.0, 0.0, 96.22118184377898, 0.0, 99.17107762858085, 98.84848536343115, 99.9494658009869]]

x_plot_rearranged = [5,4,3,2,1,6,11,8,7,9,10,       15,17,16,14,19,18,13,12       ,27,20,28,21,24,23,26,25,22      ,31,29,30,33,32,34]


def disagreement():
    linestyles = [(0, (2.0, 1.5)), '-']
    fig, ax = plt.subplots()
    ax.set_ylim([-5, 105.0])
    ax.set_xlim([1, 34])
    #plt.gca().yaxis.grid(which='major', linestyle='--', linewidth=0.3)
    ax.yaxis.set_ticks(np.arange(0.0, 105.0, 10.0))
    ax.yaxis.set_ticks(np.arange(0.0, 100.0, 5.0), minor=True)
    ax.xaxis.set_ticks([1,11,19,28,34])
    ax.xaxis.set_ticks(np.arange(1, 34, 1), minor=True)
    ax.grid(which='minor', alpha=0.2)
    ax.grid(which='major', alpha=0.5)
    plt.gca().xaxis.grid(which='major', linestyle=':', linewidth=1, dashes=[2,1,2], alpha=1)
    ax.tick_params(
Esempio n. 56
0
# -*- coding: utf-8 -*-

""" Functionality to use matplotlib figures in PySide GUIs. """

from __future__ import (division, print_function, absolute_import,
                        unicode_literals)

import os
import matplotlib
from warnings import simplefilter

# Ignore warnings from matplotlib about fonts not being found.
simplefilter("ignore", UserWarning)

# Load our matplotlibrc file.
matplotlib.rc_file(os.path.join(os.path.dirname(__file__), "matplotlibrc"))

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from PySide import QtCore, QtGui


class MPLWidget(FigureCanvas):
    """
    A widget to contain a matplotlib figure.
    """

    def __init__(self, parent=None, toolbar=False, tight_layout=True,
        autofocus=False, background_hack=True, **kwargs):
        """
Esempio n. 57
0
import logging
import sys
import warnings
from operator import attrgetter
from pathlib import Path

import matplotlib as mpl
import pandas as pd
from loguru import logger as loguru_logger
from wildfires.utils import shorten_features

from empirical_fire_modelling.configuration import Experiment, selected_features
from empirical_fire_modelling.logging_config import enable_logging
from empirical_fire_modelling.variable import match_factory, sort_variables

mpl.rc_file(Path(__file__).resolve().parent / "matplotlibrc")

loguru_logger.enable("alepython")
loguru_logger.remove()
loguru_logger.add(sys.stderr, level="WARNING")

logger = logging.getLogger(__name__)
enable_logging(level="WARNING")

warnings.filterwarnings("ignore", ".*Collapsing a non-contiguous coordinate.*")
warnings.filterwarnings("ignore", ".*DEFAULT_SPHERICAL_EARTH_RADIUS.*")
warnings.filterwarnings("ignore", ".*guessing contiguous bounds.*")

warnings.filterwarnings(
    "ignore", 'Setting feature_perturbation = "tree_path_dependent".*')
Esempio n. 58
0
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import os
import argparse
HERE = os.path.dirname(__file__)
available = os.listdir(os.path.join(HERE, 'rc'))

ap = argparse.ArgumentParser()
ap.add_argument('style', help='Which rc file to use.  One of %s' % available)
ap.add_argument('--plot', default='all', help='One of [scatter, hist, line, image], or '
                'a comma-separated list of a subset.  Default is all.')
ap.add_argument('-o', '--output', required=False, help='Render the plot to a file')
args = ap.parse_args()

matplotlib.rc_file(os.path.join(HERE, 'rc', args.style))

def lineplot(ax):
    x = np.linspace(0, 4*np.pi, 100)
    y = np.sin(x)
    for i, offset in enumerate((np.arange(5) / 3.)):
        ax.plot(x, y + offset, label='line %s' % i)
    ax.set_ylabel('y values')
    ax.set_xlabel('x values')
    ax.set_title('demo plot')
    ax.legend(loc='best')

def scatterplot(ax):
    x = np.random.random(1000)
    y = np.random.random(1000)
    ax.scatter(x, y, label='scatter 1',
Esempio n. 59
0
# 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 <http://www.gnu.org/licenses/>.

import argparse

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm

mpl.rc_file("../rc/1fig-contour-rc.txt")

from style_ber_contour_AsAu import Style1col

def do_plot(mode, content, wide):
	global style
	style.apply(mode, content, wide)

	data = np.load("data/prr_AsAu_%s%s.npz"%(content, wide))

	AU, TAU = np.meshgrid(-data["Au_range_dB"], data["tau_range"])
	Zu = data["PRR_U"]
	Zs = data["PRR_S"]

	assert TAU.shape == AU.shape == Zu.shape, "The inputs TAU, AU, PRR_U must have the same shape for plotting!"
    dataoutputdir = datadir+'Output/'
    GISdir = maindir+'Data/GIS/'
    figdir = maindir+'Figures/'
    tabledir = maindir+'Tables/'
    dirs={'main':maindir,'data':datadir,'GIS':GISdir,'fig':figdir}
elif git!=True: ## Local folders
    maindir = 'C:/Users/Alex/Desktop/'### samoa/
    csvoutputdir = datadir+'samoa/WATERSHED_ANALYSIS/FAGAALU/MasterDataFiles/csv_output/'
    savedir = datadir+'samoa/WATERSHED_ANALYSIS/GoodFigures/'
    figdir = datadir+'samoa/WATERSHED_ANALYSIS/GoodFigures/rawfigoutput/'
    
## Figure formatting
#publishable =  plotsettings.Set('GlobEnvChange')    ## plotsettings.py
#publishable.set_figsize(n_columns = 2, n_rows = 2)
    
mpl.rc_file(maindir+'johrc.rc')
mpl.rcParams['savefig.directory']=maindir+'rawfig/'
mpl.rcParams
mpl.rc('legend',scatterpoints=1)  
## Ticks
my_locator = matplotlib.ticker.MaxNLocator(4)

def show_plot(show=False,fig=figure):
    if show==True:
        plt.show()
        

def letter_subplots(fig,x=0.1,y=0.95,vertical='top',horizontal='right',Color='k',font_size=10,font_weight='bold'):
    sub_plot_count = 0
    sub_plot_letters = {0:'(a)',1:'(b)',2:'(c)',3:'(d)',4:'(e)',5:'(f)',6:'(g)',7:'(h)',8:'(i)'}
    for ax in fig.axes: