Ejemplo n.º 1
0
    def use_matplot():
        from matplotlib import use as mpl_use

        # Fix possible problems with Mac OS X venv backend
        if platform == "darwin":
            mpl_use("TkAgg")
            environ.update({"TK_SILENCE_DEPRECATION": "1"})

        from matplotlib import pyplot as _plot
        global plot
        plot = _plot
Ejemplo n.º 2
0
def plot_train(history):
    from matplotlib import use as mpl_use
    mpl_use('Agg')
    import seaborn as sns
    import matplotlib.pyplot as plt

    fig = plt.figure()
    ax = fig.add_subplot(111)
    for key, vals in history.history.items():
        ax.plot(np.arange(len(vals)), vals, '-o', label=key)
    ax.legend()
    fig.savefig('deep_train.png', bbox_inches='tight', transparent=True)
    return 0
############################################################
# FlatCAM: 2D Post-processing for Manufacturing            #
# http://caram.cl/software/flatcam                         #
# Author: Juan Pablo Caram (c)                             #
# Date: 2/5/2014                                           #
# MIT Licence                                              #
############################################################

from PyQtX import QtGui, QtCore
from PyQtX.QtWidgets import QWidget, QLineEdit, QCheckBox, QPlainTextEdit, QInputDialog, QPushButton, QScrollArea, QListView

# Prevent conflict with Qt5 and above.
from matplotlib import use as mpl_use
mpl_use("Qt4Agg")

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_agg import FigureCanvasAgg
import FlatCAMApp
import logging

log = logging.getLogger('base')


class CanvasCache(QtCore.QObject):
    """

    Case story #1:

    1) No objects in the project.
    2) Object is created (new_object() emits object_created(obj)).
Ejemplo n.º 4
0
# -*- coding: utf-8 -*-

import errno
import os
import pickle
import re

from matplotlib import use as mpl_use

mpl_use("Agg")  # noqa: E402
from matplotlib import pyplot as mpl_plt
import pytest


def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:  # pragma: no cover
            raise


def pytest_addoption(parser):
    parser.addoption(
        "--plots",
        nargs="?",
        default=False,
        const=True,
        help="Save plots (can optionally specify a directory for plots).",
Ejemplo n.º 5
0
#!/usr/bin/env python

from matplotlib import use as mpl_use, ticker
mpl_use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import poisson, chisquare, chi2_contingency
import glob
import os
import seaborn as sns
import numpy as np
sns.set_style('white')

padding = pd.DataFrame({'fragment_counts': range(5, 101), 'counts': [0] * 96})


def read_file(filename):
    samplename = os.path.basename(filename.split('.')[0])
    df = pd.read_table(filename, sep=' ',
                       names = ['fragment_counts','counts'])\
        .append(padding) \
        .groupby(['fragment_counts'])\
        .max()\
        .assign(samplename = samplename)\
        .assign(normalized_count = lambda d: d['counts']/np.sum(d['counts']))\
        .reset_index()
    return df


def rename(x):
    return 'Simulation (reads)' if 'sim' in x else 'TGIRT-seq (UMI)'
Ejemplo n.º 6
0
#!/usr/bin/env python

import sys
import glob
import os
import pandas as pd
import seaborn as sns
from matplotlib import use as mpl_use

mpl_use("agg")
import matplotlib.pyplot as plt
import numpy as np
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("SARS-CoV2 coverage")

plt.rc("axes", labelsize=15)
plt.rc("xtick", labelsize=15)
plt.rc("ytick", labelsize=15)


def read_bed(bed):
    """
    reading mosdepth output: {prefix}.per-base.bed.gz into pandas dataframe
    """
    logger.info("Reading: %s" % bed)
    return (pd.read_csv(
        bed, names=["chrom", "start", "end", "read_coverage"],
        sep="\t").assign(
            samplename=os.path.basename(os.path.dirname(bed))).assign(
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 13:13:10 2021

@author: Meghana
"""
from matplotlib import use as mpl_use

mpl_use('Agg')  # Issues warning on spyder - don't worry abt it
from glob import glob
from argparse import ArgumentParser as argparse_ArgumentParser
import re
import pandas as pd
from matplotlib.pyplot import figure as plt_figure, savefig as plt_savefig, close as plt_close, plot as plt_plot, legend as plt_legend, xlabel as plt_xlabel, ylabel as plt_ylabel, title as plt_title

parser = argparse_ArgumentParser("Input parameters")
parser.add_argument("--direct",
                    default="humap",
                    help="Input parameters file name")
parser.add_argument(
    "--main_folder",
    default="/results_73_neg_unif_10xisa_e0.01_T01.75_a0.005_qi_o",
    help="Input parameters file name")
parser.add_argument("--out_file_suffix", default="", help="out files suffix")
parser.add_argument("--parameter",
                    default="overlap_threshold_qi",
                    help="Input parameters file name")
args = parser.parse_args()


def get_metrics(lines):
Ejemplo n.º 8
0
#!/usr/bin/env python3

from matplotlib import use as mpl_use
from sys import platform
from os import environ

# Fix possible problems with Mac OS X venv backend
if platform == "darwin":
    mpl_use("TkAgg")
    environ.update({"TK_SILENCE_DEPRECATION": "1"})

from matplotlib import pyplot as plot

from grinder.decorators import exception_handler
from grinder.defaultvalues import DefaultPlotValues, DefaultValues
from grinder.errors import (
    GrinderPlotsAdjustAutopctError,
    GrinderPlotsCreatePieChartError,
    GrinderPlotsSavePieChartError,
)
from grinder.filemanager import GrinderFileManager


class GrinderPlots:
    """
    Pie charts and plots creator
    """
    def __init__(self):
        self.plot = None
        self.results_figure_id: int = 0
Ejemplo n.º 9
0
""" ROI plots in matplotlib
"""
import logging
import os

from matplotlib import use as mpl_use
mpl_use('Qt4Agg')
import matplotlib as mpl
from matplotlib.backends.backend_qt4agg \
    import FigureCanvasQTAgg as FigureCanvas
import numpy as np

from . import data

logger = logging.getLogger('roitool')


# Note: FigureCanvas is also a QWidget
class ROIPlot(FigureCanvas):
    """ Plot widget
    """
    def __init__(self):
        style = os.environ.get('ROITOOL_PLOT_STYLE', 'ggplot')

        if style:
            try:
                import matplotlib.style
                if style == 'xkcd':
                    mpl.pyplot.xkcd()
                else:
                    mpl.style.use(style)
Ejemplo n.º 10
0
from matplotlib import use as mpl_use
mpl_use('agg')
import random
from collections import Counter, defaultdict
from scipy.stats import ranksums
from scipy.special import ndtr
from peak_utils import *
import RNA
from multiprocessing import Pool


def get_pvalues(args):
    i, row = args
    simulation = 10000
    bases = list('ACTG')
    seq = row['seq']
    sense = row['is_sense']
    fold, energy = RNA.fold(seq)
    b_counts = Counter(seq.upper())
    weights = [b_counts[n] for n in bases]
    random_energy = []
    for i in range(simulation):
        random_seq = ''.join(random.choices(bases, k=len(seq),
                                            weights=weights))
        s, e = RNA.fold(random_seq)
        random_energy.append(e)
    p_val = sum(1 for e in random_energy if e <= energy)
    return p_val / float(simulation)


def main():
Ejemplo n.º 11
0
import random
from matplotlib import style
from matplotlib import pyplot as plt
from kivy.app import App
from matplotlib import use as mpl_use

from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
form kivy.clock import Clock
import kivy.properties as kp

mpl_use('model://kivy.garden.matplotlib.backend_kivyagg')
style.use("dark_background")

class TestApp(App):
	def build(self):
		return Builder.load_string("Chart:")

class Chart(BoxLayout):
	data= kp.ListProperty([])
	def __init__(self,**kwargs):
		super().__init__(**kwargs)
		self.fig, self.ax1 = plt.subplots()
		self.ax1.plot([],[],'bo')
		self.mpl_canvas = self.fig.canvas
		self.add_widget(self.mpl_canvas)
		Clock.schedule_interval(self.update,1)
	def on_data(self,*args):
		self.ax1.clear()
		y = [i**2 for i in self.data]
		self.ax1.plot(self.data,y,'bo-',linewidth=5.0)
Ejemplo n.º 12
0
############################################################
# FlatCAM: 2D Post-processing for Manufacturing            #
# http://caram.cl/software/flatcam                         #
# Author: Juan Pablo Caram (c)                             #
# Date: 2/5/2014                                           #
# MIT Licence                                              #
############################################################

from PyQt4 import QtGui, QtCore

# Prevent conflict with Qt5 and above.
from matplotlib import use as mpl_use
mpl_use("Qt4Agg")

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


class PlotCanvas:
    """
    Class handling the plotting area in the application.
    """

    def __init__(self, container):
        """
        The constructor configures the Matplotlib figure that
        will contain all plots, creates the base axes and connects
        events to the plotting area.

        :param container: The parent container in which to draw plots.
Ejemplo n.º 13
0
# -*- coding: utf-8 -*-
__version__ = 0.6

from matplotlib import use as mpl_use
mpl_use('WXAgg')

import sys
import wx
import lib
import numpy as np
from lib.gui__MAIN import Frame_MAIN
from matplotlib import rcParams
rcParams['mathtext.default'] = 'sf'


def main():
    import os
    path = os.path.dirname(os.path.realpath(__file__))
    os.chdir(path)
    app = wx.App(0)
    frame = WavGliDaPro(None)

    frame.init()

    frame.Show()
    app.MainLoop()


class WavGliDaPro(Frame_MAIN):

    from lib.gui_0_help import func_update_help
Ejemplo n.º 14
0
from matplotlib.path import Path
from matplotlib.patches import Polygon as pol
from kivy.uix.recycleview import RecycleView
from kivy.uix.scrollview import ScrollView
from sklearn.preprocessing import normalize
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg, NavigationToolbar2Kivy
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scatterlayout import ScatterLayout
from matplotlib import use as mpl_use

mpl_use('module://kivy.garden.matplotlib.backend_kivy')


class Node:
    def __init__(self, name):
        self.parent = name
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)


def Combination(a, combi, n, r, depth, index, val):
    global new, files
    if index == r:
        x = []
Ejemplo n.º 15
0
    if "n_embd" in args:
        print("n_embd: ", args.n_embd)
    else:
        print("n_embd: ", model.n_embd)
    print()

    # ------------------------------------------------------------------
    # Fit
    trainer.fit(model, datamodule=dm)


if __name__ == "__main__":

    from matplotlib import use as mpl_use

    mpl_use("Agg")

    pl.seed_everything(1234)

    parser = ArgumentParser()
    parser = pl.Trainer.add_argparse_args(parser)
    parser = TurnGPTDM.add_data_specific_args(parser)
    parser.add_argument("--early_stopping", default=False, type=bool)
    parser.add_argument("--patience", default=10, type=int)
    parser.add_argument(
        "--model",
        type=str,
        default="mini",  # sparse, hugging
    )
    parser.add_argument(
        "--datasets",
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright &copy; 2019 ISIS Rutherford Appleton Laboratory UKRI,
#     NScD Oak Ridge National Laboratory, European Spallation Source
#     & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#  This file is part of the mantid workbench.

from __future__ import (absolute_import, unicode_literals)

import unittest

from matplotlib import use as mpl_use
mpl_use('Agg')  # noqa
from matplotlib.pyplot import figure

from mantid.simpleapi import CreateWorkspace
from mantid.plots import MantidAxes  # register MantidAxes projection  # noqa
from mantid.py3compat.mock import Mock, patch
from mantidqt.widgets.plotconfigdialog.curvestabwidget import CurveProperties
from mantidqt.widgets.plotconfigdialog.curvestabwidget.presenter import (
    CurvesTabWidgetPresenter, remove_curve_from_ax, curve_has_errors)


class CurvesTabWidgetPresenterTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.fig = figure()
        cls.ws = CreateWorkspace(DataX=[0, 1],
                                 DataY=[3, 4],
                                 DataE=[0.1, 0.1],
Ejemplo n.º 17
0
#!/Library/Frameworks/Python.framework/Versions/Current/bin/python

#Relies on wx, matplotlib, scipy, numpy
import wx 
import os, glob, sys, imp
try:
   from wx.lib.pubsub import pub
except: from wx.lib.pubsub import pub

import numpy as np
from matplotlib import use as mpl_use
mpl_use('WXAgg')
from matplotlib.patches import Circle
from matplotlib.figure import Figure
import matplotlib.font_manager as fm
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas, NavigationToolbar2WxAgg as NavigationToolbar
from matplotlib.ticker import MaxNLocator
from threading import Thread
import NanoPeakCell_dev as Hit
import wx.lib.buttons as buttons
import fabio, pyFAI, pyFAI.distortion, pyFAI.detectors
import peakfind as pf
import mynormalize
import matplotlib.pyplot as plt
import matplotlib

# These imports will make sure the user will only be able to select outputs its system can save
# TODO: Warning: Please install or source blabla to be able to export images in X format
try : 
    imp.find_module('h5py')
    H5=True