예제 #1
0
 def gen_steam_cm_graph(self, graphdata: dict):
     """Make an graph for connection managers"""
     mpluse("Agg")
     formats = [
         "%y",  # ticks are mostly years
         "%b",  # ticks are mostly months
         "%d",  # ticks are mostly days
         "%H:%M",  # hrs
         "%H:%M",  # min
         "%S.%f",  # secs
     ]
     zero_formats = [""] + formats[:-1]
     zero_formats[3] = "%d-%b"
     offset_formats = [
         "",
         "%Y",
         "%b %Y",
         "%d %b %Y",
         "%d %b %Y",
         "%d %b %Y %H:%M",
     ]
     munits.registry[datetime] = mdates.ConciseDateConverter(
         formats=formats,
         zero_formats=zero_formats,
         offset_formats=offset_formats)
     cur = graphdata["start"]
     x = []
     for _ in range(len(graphdata["data"])):
         cur += graphdata["step"]
         x.append(cur)
     x = [datetime.utcfromtimestamp(_x / 1000) for _x in x]
     y = graphdata["data"]
     graphfile = BytesIO()
     with pyplot.style.context(
             path.join(bundled_data_path(self), "discord.mplstyle")):
         fig, ax = pyplot.subplots()
         ax.plot(x, y)
         ax.set_ylim(bottom=0)
         ax.grid()
         ax.set(xlabel="Date",
                ylabel="%",
                title="Steam Connection Managers")
         ax.set_yticks(np.arange(0, 100, 5))
         fig.savefig(graphfile)
         pyplot.close(fig)
     graphfile.seek(0)
     return graphfile
예제 #2
0
def main(args):
    '''Run CellProfiler

    args - command-line arguments, e.g. sys.argv
    '''
    if any([arg.startswith('--work-announce') for arg in args]):
        #
        # Go headless ASAP
        #
        import cellprofiler.preferences as cpprefs
        cpprefs.set_headless()
        for i, arg in enumerate(args):
            if arg == "--ij-plugins-directory" and len(args) > i+1:
                cpprefs.set_ij_plugin_directory(args[i+1])
                break
        import cellprofiler.analysis_worker
        cellprofiler.analysis_worker.aw_parse_args()
        cellprofiler.analysis_worker.main()
        sys.exit(0)
        
    options, args = parse_args(args)
    if options.jvm_heap_size != None:
        from cellprofiler.preferences import set_jvm_heap_mb
        set_jvm_heap_mb(options.jvm_heap_size, False)
    set_log_level(options)
    
    if not hasattr(sys, "frozen") and options.code_statistics:
        print_code_statistics()
        return
    
    if options.print_groups_file is not None:
        print_groups(options.print_groups_file)
        return
    
    if options.batch_commands_file is not None:
        get_batch_commands(options.batch_commands_file)
        return
        
    if options.run_ilastik:
        run_ilastik()
        return
    
    if options.add_message_for_user:
        if len(args) != 3:
            sys.stderr.write("Usage: (for add_message-for-user)\n")
            sys.stderr.write("CellProfiler --add-message-for-user <caption> <message> <pipeline-or-project>\n")
            sys.stderr.write("where:\n")
            sys.stderr.write("    <caption> - the message box caption\n")
            sys.stderr.write("    <message> - the message displayed inside the message box\n")
            sys.stderr.write("    <pipeline-or-project> - the path to the pipeline or project file to modify\n")
            return
        caption = args[0]
        message = args[1]
        path = args[2]
        
        import h5py
        using_hdf5 = h5py.is_hdf5(path)
        if using_hdf5:
            import cellprofiler.measurements as cpmeas
            m = cpmeas.Measurements(
                filename = path, mode="r+")
            pipeline_text = m[cpmeas.EXPERIMENT, "Pipeline_Pipeline"]
        else:
            with open(path, "r") as fd:
                pipeline_text = fd.read()
        header, body = pipeline_text.split("\n\n", 1)
        pipeline_text = header + \
            ("\nMessageForUser:%s|%s\n\n" % (caption, message)) + body
        if using_hdf5:
            m[cpmeas.EXPERIMENT, "Pipeline_Pipeline"] = pipeline_text
            m.close()
        else:
            with open(path, "w") as fd:
                fd.write(pipeline_text)
        print "Message added to %s" % path
        return
    
    # necessary to prevent matplotlib trying to use Tkinter as its backend.
    # has to be done before CellProfilerApp is imported
    from matplotlib import use as mpluse
    mpluse('WXAgg')
    
    if (not hasattr(sys, 'frozen')) and options.fetch_external_dependencies:
        import external_dependencies
        external_dependencies.fetch_external_dependencies(options.overwrite_external_dependencies)
    
    if (not hasattr(sys, 'frozen')) and options.build_extensions:
        build_extensions()
        if options.build_and_exit:
            return
    
    if options.output_html:
        from cellprofiler.gui.html.manual import generate_html
        webpage_path = options.output_directory if options.output_directory else None
        generate_html(webpage_path)
        return
    if options.print_measurements:
        print_measurements(options)
        return
    if options.omero_credentials is not None:
        set_omero_credentials_from_string(options.omero_credentials)
    try:
        if options.show_gui:
            import wx
            wx.Log.EnableLogging(False)
            from cellprofiler.cellprofilerapp import CellProfilerApp
            from cellprofiler.workspace import is_workspace_file
            show_splashbox = (options.pipeline_filename is None and
                              (not options.new_project) and
                              options.show_splashbox)
            
            if options.pipeline_filename:
                if is_workspace_file(options.pipeline_filename):
                    workspace_path = os.path.expanduser(options.pipeline_filename)
                    pipeline_path = None
                else:
                    pipeline_path = os.path.expanduser(options.pipeline_filename)
                    workspace_path = None
            elif options.new_project:
                workspace_path = False
                pipeline_path = None
            else:
                workspace_path = None
                pipeline_path = None
            App = CellProfilerApp(
                0, 
                check_for_new_version = (options.pipeline_filename is None),
                show_splashbox = show_splashbox,
                workspace_path = workspace_path,
                pipeline_path = pipeline_path)
    
        #
        # Important to go headless ASAP
        #
        # cellprofiler.preferences can't be imported before we have a chance
        # to initialize the wx app.
        #
        import cellprofiler.preferences as cpprefs
        if not options.show_gui:
            cpprefs.set_headless()
            # What's there to do but run if you're running headless?
            # Might want to change later if there's some headless setup 
            options.run_pipeline = True
    
            
        if options.plugins_directory is not None:
            cpprefs.set_plugin_directory(options.plugins_directory)
        if options.ij_plugins_directory is not None:
            cpprefs.set_ij_plugin_directory(options.ij_plugins_directory)
        if options.temp_dir is not None:
            if not os.path.exists(options.temp_dir):
                os.makedirs(options.temp_dir)
            cpprefs.set_temporary_directory(options.temp_dir)
        if options.data_file is not None:
            cpprefs.set_data_file(os.path.abspath(options.data_file))
        if options.image_set_file is not None:
            cpprefs.set_image_set_file(options.image_set_file, False)
            
        from cellprofiler.utilities.version import version_string, version_number
        logging.root.info("Version: %s / %d" % (version_string, version_number))
    
        if options.run_pipeline and not options.pipeline_filename:
            raise ValueError("You must specify a pipeline filename to run")
    
        if options.output_directory:
            if not os.path.exists(options.output_directory):
                os.makedirs(options.output_directory)
            cpprefs.set_default_output_directory(options.output_directory)
        
        if options.image_directory:
            cpprefs.set_default_image_directory(options.image_directory)
    
        if options.show_gui:
            if options.run_pipeline:
                App.frame.pipeline_controller.do_analyze_images()
            App.MainLoop()
            return
        
        elif options.run_pipeline:
            run_pipeline_headless(options, args)
    except Exception, e:
        logging.root.fatal("Uncaught exception in CellProfiler.py", exc_info=True)
        raise
예제 #3
0
# Script to plot multiple graphs per obsid
# Written by David Gardenier, 2015-2016

import pandas as pd
import numpy as np
from matplotlib import use as mpluse
mpluse('agg')  # Prevents errors when running in multiple screens
import matplotlib.pyplot as plt
from matplotlib import gridspec
from scipy.stats import binned_statistic
from plot_power_colours import findbestdataperobsid, findbestdata


class Plots:
    '''
    Class to determine setup for different plots
    '''
    def __init__(self, db, obj):

        # Set up grid
        self.fig = plt.figure(figsize=(15, 10))
        self.gs = gridspec.GridSpec(2, 3)

        self.db = db
        self.df = findbestdataperobsid(db)
        self.obj = obj
        self.lc = False
        self.ps = False
        self.sp = False

    def lightcurve(self):
예제 #4
0
def main(args):
    '''Run CellProfiler

    args - command-line arguments, e.g. sys.argv
    '''
    if any([arg.startswith('--work-announce') for arg in args]):
        #
        # Go headless ASAP
        #
        import cellprofiler.preferences as cpprefs
        cpprefs.set_headless()
        import cellprofiler.analysis_worker
        cellprofiler.analysis_worker.main()
        sys.exit(0)

    options, args = parse_args(args)
    set_log_level(options)

    if not hasattr(sys, "frozen") and options.code_statistics:
        print_code_statistics()
        return

    if options.print_groups_file is not None:
        print_groups(options.print_groups_file)
        return

    if options.batch_commands_file is not None:
        get_batch_commands(options.batch_commands_file)
        return

    if options.run_ilastik:
        run_ilastik()
        return

    # necessary to prevent matplotlib trying to use Tkinter as its backend.
    # has to be done before CellProfilerApp is imported
    from matplotlib import use as mpluse
    mpluse('WXAgg')

    if (not hasattr(sys, 'frozen')) and options.fetch_external_dependencies:
        import external_dependencies
        external_dependencies.fetch_external_dependencies(
            options.overwrite_external_dependencies)

    if (not hasattr(sys, 'frozen')) and options.build_extensions:
        build_extensions()
        if options.build_and_exit:
            return

    if options.output_html:
        from cellprofiler.gui.html.manual import generate_html
        webpage_path = options.output_directory if options.output_directory else None
        generate_html(webpage_path)
        return
    if options.print_measurements:
        print_measurements(options)
        return

    try:
        if options.show_gui:
            import wx
            wx.Log.EnableLogging(False)
            from cellprofiler.cellprofilerapp import CellProfilerApp
            show_splashbox = (options.pipeline_filename is None
                              and options.workspace_filename is None
                              and (not options.new_workspace)
                              and options.show_splashbox)
            if options.workspace_filename:
                workspace_path = os.path.expanduser(options.workspace_filename)
            elif options.new_workspace:
                workspace_path = False
            else:
                workspace_path = None
            App = CellProfilerApp(
                0,
                check_for_new_version=(options.pipeline_filename is None),
                show_splashbox=show_splashbox,
                workspace_path=workspace_path)

        #
        # Important to go headless ASAP
        #
        # cellprofiler.preferences can't be imported before we have a chance
        # to initialize the wx app.
        #
        import cellprofiler.preferences as cpprefs
        if not options.show_gui:
            cpprefs.set_headless()
            # What's there to do but run if you're running headless?
            # Might want to change later if there's some headless setup
            options.run_pipeline = True

        if options.plugins_directory is not None:
            cpprefs.set_plugin_directory(options.plugins_directory)
        if options.ij_plugins_directory is not None:
            cpprefs.set_ij_plugin_directory(options.ij_plugins_directory)
        if options.temp_dir is not None:
            cpprefs.set_temporary_directory(options.temp_dir)
        if options.data_file is not None:
            cpprefs.set_data_file(os.path.abspath(options.data_file))
        if options.image_set_file is not None:
            cpprefs.set_image_set_file(options.image_set_file, False)

        from cellprofiler.utilities.version import version_string, version_number
        logging.root.info("Version: %s / %d" %
                          (version_string, version_number))

        if options.run_pipeline and not options.pipeline_filename:
            raise ValueError("You must specify a pipeline filename to run")

        if options.output_directory:
            cpprefs.set_default_output_directory(options.output_directory)

        if options.image_directory:
            cpprefs.set_default_image_directory(options.image_directory)

        if options.show_gui:
            import cellprofiler.gui.cpframe as cpgframe
            if options.pipeline_filename:
                pipeline_path = os.path.expanduser(options.pipeline_filename)
                try:
                    App.frame.pipeline.load(pipeline_path)
                    if options.run_pipeline:
                        App.frame.Command(cpgframe.ID_FILE_ANALYZE_IMAGES)
                except:
                    import wx
                    wx.MessageBox(
                        'CellProfiler was unable to load the pipeline file, "%s"'
                        % options.pipeline_filename,
                        "Error loading pipeline",
                        style=wx.OK | wx.ICON_ERROR)
                    logging.root.error("Unable to load pipeline",
                                       exc_info=True)
            App.MainLoop()
            return

        elif options.run_pipeline:
            run_pipeline_headless(options, args)
    except Exception, e:
        logging.root.fatal("Uncaught exception in CellProfiler.py",
                           exc_info=True)
        raise
from __future__ import division # no more "zero" integer division bugs!:P
import sys
import argparse
import os
import numpy as np # array
import ancillary as anc # not so good...but fast
import random
import logging
import warnings
import h5py
from scipy.stats import norm as scipy_norm

import matplotlib.cm as cm
from matplotlib import use as mpluse
mpluse("Agg")
#mpluse("Qt4Agg")
import matplotlib.pyplot as plt
#plt.rc('font',**{'family':'serif','serif':['Computer Modern Roman']})
#plt.rc('text', usetex=True)
plt.rcParams['text.usetex'] = True
plt.rcParams['font.family'] = 'serif'
import matplotlib.colors as colors
#from matplotlib import rcParams
#rcParams['text.latex.unicode']=True
from matplotlib.ticker import FormatStrFormatter

warnings.simplefilter('ignore', np.RankWarning)

def main():
  # ---
예제 #6
0
if options.run_ilastik:
    #
    # Fake ilastik into thinking it is __main__
    #
    import ilastik
    import imp
    sys.argv.remove("--ilastik")
    il_path = ilastik.__path__
    il_file, il_path, il_description = imp.find_module('ilastikMain', il_path)
    imp.load_module('__main__', il_file, il_path, il_description)
    sys.exit()

# necessary to prevent matplotlib trying to use Tkinter as its backend.
# has to be done before CellProfilerApp is imported
from matplotlib import use as mpluse
mpluse('WXAgg')

if (not hasattr(sys, 'frozen')) and options.fetch_external_dependencies:
    import external_dependencies
    external_dependencies.fetch_external_dependencies(options.overwrite_external_dependencies)

if (not hasattr(sys, 'frozen')) and options.build_extensions:
    import subprocess
    import cellprofiler.cpmath.setup
    import cellprofiler.utilities.setup
    from distutils.dep_util import newer_group
    #
    # Check for dependencies and compile if necessary
    #
    compile_scripts = [(os.path.join('cellprofiler', 'cpmath', 'setup.py'),
                        cellprofiler.cpmath.setup),
예제 #7
0
# -*- coding: utf-8 -*-
from gi.repository import Gtk
import dinic
import networkx as nx
from matplotlib import use as mpluse
mpluse('GTK3Agg')
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar
import matplotlib.pyplot as plt
import thread
from gi.repository import Gdk
f = plt.figure()

class ConsoleLikeTextBuffer:
    def __init__(self):
        self.textbuff = Gtk.TextBuffer()
        self.end_iter = self.textbuff.get_end_iter()
    def get_text_buffer(self):
        return self.textbuff
    def append_line(self, message):
        self.textbuff.insert(self.end_iter, message + "\n")


class ViewableNetworkFlow(dinic.NetworkFlow):
    layout = {}
    dilayout = {}
    def __init__(self):
        super(ViewableNetworkFlow, self).__init__()
        self.console = ConsoleLikeTextBuffer()
    def print_message(self, message):
        self.console.append_line(message)
예제 #8
0
파일: core.py 프로젝트: gact/phenos
#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-

#STANDARD LIBRARY
import os,sys,time,shutil,subprocess
import logging,platform,ConfigParser,traceback
import numpy as np
from itertools import chain
from math import e
from collections import defaultdict, Counter
#OTHER
from matplotlib import use as mpluse
mpluse('PS')
import matplotlib.pyplot as pyplt
import win32com.client


# #############################################################################

filename = os.path.basename(__file__)
authors = ("David B. H. Barton")
version = "2.7"

LOG=logging.getLogger()

#

#UTILITY LAMBDAS ##############################################################

#flattens a nested list, e.g. flatten([[1,2],[3,4]]) returns [1,2,3,4]
flatten=lambda nested: list(chain.from_iterable(nested))
예제 #9
0
Reads data from any log files that are present and sorts by composition of cornstarch.
Plots a few simple checks and then plots shear stresses v strain rates.

Author: Chris Boyle ([email protected]
'''

# System
from glob import glob
from copy import copy
import sys

# 3rd Party
import numpy as np
import scipy as sp
from matplotlib import use as mpluse
mpluse('Agg')  # can't remember this is here... fixes a bug perhaps?
import matplotlib.pyplot as plt

# RPi-R
sys.path.append("./../bin")
import plothelp as ph
from filter import filter as ft
import resx

#############################################################################################################
### Setting up. #############################################################################################
# Before the plot can begin, there are a few things to do first: setting up variables, reading the files etc.

# Change plotter font to serif, I think it looks nicer than sans fonts.
plt.rc('font', family='serif')
예제 #10
0
def main(args):
    '''Run CellProfiler

    args - command-line arguments, e.g. sys.argv
    '''
    if any([arg.startswith('--work-announce') for arg in args]):
        #
        # Go headless ASAP
        #
        import cellprofiler.preferences as cpprefs
        cpprefs.set_headless()
        import cellprofiler.analysis_worker
        cellprofiler.analysis_worker.main()
        sys.exit(0)
        
    options, args = parse_args(args)
    set_log_level(options)
    
    if not hasattr(sys, "frozen") and options.code_statistics:
        print_code_statistics()
        return
    
    if options.print_groups_file is not None:
        print_groups(options.print_groups_file)
        return
    
    if options.batch_commands_file is not None:
        get_batch_commands(options.batch_commands_file)
        return
        
    if options.run_ilastik:
        run_ilastik()
        return
    
    # necessary to prevent matplotlib trying to use Tkinter as its backend.
    # has to be done before CellProfilerApp is imported
    from matplotlib import use as mpluse
    mpluse('WXAgg')
    
    if (not hasattr(sys, 'frozen')) and options.fetch_external_dependencies:
        import external_dependencies
        external_dependencies.fetch_external_dependencies(options.overwrite_external_dependencies)
    
    if (not hasattr(sys, 'frozen')) and options.build_extensions:
        build_extensions()
        if options.build_and_exit:
            return
    
    if options.output_html:
        from cellprofiler.gui.html.manual import generate_html
        webpage_path = options.output_directory if options.output_directory else None
        generate_html(webpage_path)
        return
    if options.print_measurements:
        print_measurements(options)
        return
    
    try:
        if options.show_gui:
            import wx
            wx.Log.EnableLogging(False)
            from cellprofiler.cellprofilerapp import CellProfilerApp
            show_splashbox = (options.pipeline_filename is None and
                              options.workspace_filename is None and
                              (not options.new_workspace) and
                              options.show_splashbox)
            if options.workspace_filename:
                workspace_path = os.path.expanduser(options.workspace_filename)
            elif options.new_workspace:
                workspace_path = False
            else:
                workspace_path = None
            App = CellProfilerApp(
                0, 
                check_for_new_version = (options.pipeline_filename is None),
                show_splashbox = show_splashbox,
                workspace_path = workspace_path)
    
        #
        # Important to go headless ASAP
        #
        # cellprofiler.preferences can't be imported before we have a chance
        # to initialize the wx app.
        #
        import cellprofiler.preferences as cpprefs
        if not options.show_gui:
            cpprefs.set_headless()
            # What's there to do but run if you're running headless?
            # Might want to change later if there's some headless setup 
            options.run_pipeline = True
    
            
        if options.plugins_directory is not None:
            cpprefs.set_plugin_directory(options.plugins_directory)
        if options.ij_plugins_directory is not None:
            cpprefs.set_ij_plugin_directory(options.ij_plugins_directory)
        if options.temp_dir is not None:
            cpprefs.set_temporary_directory(options.temp_dir)
        if options.data_file is not None:
            cpprefs.set_data_file(os.path.abspath(options.data_file))
        if options.image_set_file is not None:
            cpprefs.set_image_set_file(options.image_set_file, False)
            
        from cellprofiler.utilities.version import version_string, version_number
        logging.root.info("Version: %s / %d" % (version_string, version_number))
    
        if options.run_pipeline and not options.pipeline_filename:
            raise ValueError("You must specify a pipeline filename to run")
    
        if options.output_directory:
            cpprefs.set_default_output_directory(options.output_directory)
        
        if options.image_directory:
            cpprefs.set_default_image_directory(options.image_directory)
    
        if options.show_gui:
            import cellprofiler.gui.cpframe as cpgframe
            if options.pipeline_filename:
                pipeline_path = os.path.expanduser(options.pipeline_filename)
                try:
                    App.frame.pipeline.load(pipeline_path)
                    if options.run_pipeline:
                        App.frame.Command(cpgframe.ID_FILE_ANALYZE_IMAGES)
                except:
                    import wx
                    wx.MessageBox(
                        'CellProfiler was unable to load the pipeline file, "%s"' %
                        options.pipeline_filename, "Error loading pipeline",
                        style = wx.OK | wx.ICON_ERROR)
                    logging.root.error("Unable to load pipeline", exc_info=True)
            App.MainLoop()
            return
        
        elif options.run_pipeline:
            run_pipeline_headless(options, args)
    except Exception, e:
        logging.root.fatal("Uncaught exception in CellProfiler.py", exc_info=True)
        raise
예제 #11
0
from matplotlib import use as mpluse
mpluse("TkAgg")
from Laser import *
import matplotlib.pyplot as plt

import math
from math import exp, sqrt, log as ln

# Math helper functions
i15 = 0
q0 = 0


def flagged_trigo(tFunc):
    return (lambda x: (tFunc(x) if i15 else tFunc(math.radians(x))))


def flagged_arctrigo(aFunc):
    return lambda x: (aFunc(x) if i15 else math.degrees(aFunc(x)))


atan2 = lambda y: (math.atan2(y, q0)
                   if i15 else math.degrees(math.atan2(y, q0)))

cos = flagged_trigo(math.cos)
sin = flagged_trigo(math.sin)
tan = flagged_trigo(math.tan)
acos = flagged_arctrigo(math.acos)
asin = flagged_arctrigo(math.asin)
atan = flagged_arctrigo(math.atan)
예제 #12
0
from collections import defaultdict
import numpy as np
from matplotlib import use as mpluse
mpluse('Agg')
import pylab as plt

from IPython import embed

from pyontutils.hierarchies import in_tree

def discretize(data_matrix):
    bins = [0,1,10,100]
    vals = [None,1,2,3]

    for lower, upper, val in zip(bins[:-1],bins[1:], vals[:-1]):
        data_matrix[ (data_matrix >= lower) * (data_matrix < upper) ] = val

    data_matrix[data_matrix >= bins[-1]] = vals[-1]

    return data_matrix

def sCollapseToSrcName(keys, id_name_dict):
    """
        Collapse sources that have the same name.
    """
    key_collections_dict = defaultdict(set)
    new_id_name_dict = {}
    for key in keys:
        if key not in id_name_dict:
            print(key + " is not in this dict")
            continue
예제 #13
0
for example)
'''

# System
import math
from copy import copy

# 3rd Party
import xml.etree.ElementTree as ET
import numpy as np
from numpy import *
from scipy.optimize import curve_fit
try:
    import spidev  # will error if not on rpi
    from matplotlib import use as mpluse
    mpluse(
        'Agg')  # for plotting from commandline (with no xserver or anything)
except:
    pass  # not on rpi, don't need to use (!xserver) as gui backend
import matplotlib.pyplot as plt
import pandas as pd

# RPi-R
from filter import filter


######################################################################################################################## XML FUNCTIONS
def writeout(path="./../etc/data.xml"):
    '''
    writeout(**kwargs)
    
    Writes the contents of a data file.
예제 #14
0
    # Fake ilastik into thinking it is __main__
    #
    import ilastik
    import imp

    sys.argv.remove("--ilastik")
    il_path = ilastik.__path__
    il_file, il_path, il_description = imp.find_module("ilastikMain", il_path)
    imp.load_module("__main__", il_file, il_path, il_description)
    sys.exit()

# necessary to prevent matplotlib trying to use Tkinter as its backend.
# has to be done before CellProfilerApp is imported
from matplotlib import use as mpluse

mpluse("WXAgg")

if (not hasattr(sys, "frozen")) and options.fetch_external_dependencies:
    import external_dependencies

    external_dependencies.fetch_external_dependencies(options.overwrite_external_dependencies)

if (not hasattr(sys, "frozen")) and options.build_extensions:
    import subprocess
    import cellprofiler.cpmath.setup
    import cellprofiler.utilities.setup
    from distutils.dep_util import newer_group

    #
    # Check for dependencies and compile if necessary
    #
예제 #15
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division  # no more "zero" integer division bugs!:P
import sys
import argparse
import os
import numpy as np  # array
import time
#import h5py
#import random
#import constants as cst # local constants module
#from scipy.stats import norm as scipy_norm
import ancillary as anc
from matplotlib import use as mpluse
mpluse("Agg")
#mpluse("Qt4Agg")
import matplotlib.pyplot as plt
#plt.rc('font',**{'family':'serif','serif':['Computer Modern Roman']})
#plt.rc('text', usetex=True)
plt.rcParams['text.usetex'] = True
plt.rcParams['font.family'] = 'serif'
#from matplotlib import rcParams
#rcParams['text.latex.unicode']=True

import logging
import warnings


def main():
    # ---
예제 #16
0
def main(args=None):
    '''Run CellProfiler

    args - command-line arguments, e.g. sys.argv
    '''
    if args is None:
        args = sys.argv
    import cellprofiler.preferences as cpprefs
    cpprefs.set_awt_headless(True)
    exit_code = 0
    switches = ('--work-announce', '--knime-bridge-address')
    if any([any([arg.startswith(switch) for switch in switches])
            for arg in args]):
        #
        # Go headless ASAP
        #
        cpprefs.set_headless()
        for i, arg in enumerate(args):
            if arg == "--ij-plugins-directory" and len(args) > i + 1:
                cpprefs.set_ij_plugin_directory(args[i + 1])
                break
        import cellprofiler.analysis_worker
        cellprofiler.analysis_worker.aw_parse_args()
        cellprofiler.analysis_worker.main()
        sys.exit(exit_code)

    options, args = parse_args(args)
    if options.print_version:
        from cellprofiler.utilities.version import \
            dotted_version, version_string, git_hash, version_number
        print "CellProfiler %s" % dotted_version
        print "Git %s" % git_hash
        print "Version %s" % version_number
        print "Built %s" % version_string.split(" ")[0]
        sys.exit(exit_code)
    #
    # Important to go headless ASAP
    #
    if (not options.show_gui) or options.write_schema_and_exit:
        import cellprofiler.preferences as cpprefs
        cpprefs.set_headless()
        # What's there to do but run if you're running headless?
        # Might want to change later if there's some headless setup
        options.run_pipeline = True

    if options.jvm_heap_size is not None:
        from cellprofiler.preferences import set_jvm_heap_mb
        set_jvm_heap_mb(options.jvm_heap_size, False)
    set_log_level(options)

    if options.print_groups_file is not None:
        print_groups(options.print_groups_file)
        return

    if options.batch_commands_file is not None:
        get_batch_commands(options.batch_commands_file)
        return

    if options.run_ilastik:
        run_ilastik()
        return

    if options.add_message_for_user:
        if len(args) != 3:
            sys.stderr.write("Usage: (for add_message-for-user)\n")
            sys.stderr.write("CellProfiler --add-message-for-user <caption> <message> <pipeline-or-project>\n")
            sys.stderr.write("where:\n")
            sys.stderr.write("    <caption> - the message box caption\n")
            sys.stderr.write("    <message> - the message displayed inside the message box\n")
            sys.stderr.write("    <pipeline-or-project> - the path to the pipeline or project file to modify\n")
            return
        caption = args[0]
        message = args[1]
        path = args[2]

        import h5py
        using_hdf5 = h5py.is_hdf5(path)
        if using_hdf5:
            import cellprofiler.measurements as cpmeas
            m = cpmeas.Measurements(
                    filename=path, mode="r+")
            pipeline_text = m[cpmeas.EXPERIMENT, "Pipeline_Pipeline"]
        else:
            with open(path, "r") as fd:
                pipeline_text = fd.read()
        header, body = pipeline_text.split("\n\n", 1)
        pipeline_text = header + \
                        ("\nMessageForUser:%s|%s\n\n" % (caption, message)) + body
        if using_hdf5:
            m[cpmeas.EXPERIMENT, "Pipeline_Pipeline"] = pipeline_text
            m.close()
        else:
            with open(path, "w") as fd:
                fd.write(pipeline_text)
        print "Message added to %s" % path
        return

    # necessary to prevent matplotlib trying to use Tkinter as its backend.
    # has to be done before CellProfilerApp is imported
    from matplotlib import use as mpluse
    mpluse('WXAgg')

    if options.omero_credentials is not None:
        set_omero_credentials_from_string(options.omero_credentials)
    if options.plugins_directory is not None:
        cpprefs.set_plugin_directory(options.plugins_directory,
                                     globally=False)
    if options.ij_plugins_directory is not None:
        cpprefs.set_ij_plugin_directory(options.ij_plugins_directory,
                                        globally=False)
    if options.temp_dir is not None:
        if not os.path.exists(options.temp_dir):
            os.makedirs(options.temp_dir)
        cpprefs.set_temporary_directory(options.temp_dir, globally=False)
    if not options.allow_schema_write:
        cpprefs.set_allow_schema_write(False)
    #
    # After the crucial preferences are established, we can start the VM
    #
    from cellprofiler.utilities.cpjvm import cp_start_vm
    cp_start_vm()
    #
    # Not so crucial preferences...
    #
    if options.image_set_file is not None:
        cpprefs.set_image_set_file(options.image_set_file)
    try:
        # ---------------------------------------
        #
        # Handle command-line tasks that that need to load the modules to run
        #
        if options.output_html:
            from cellprofiler.gui.html.manual import generate_html
            webpage_path = options.output_directory if options.output_directory else None
            generate_html(webpage_path)
            return
        if options.print_measurements:
            print_measurements(options)
            return
        if not hasattr(sys, "frozen") and options.code_statistics:
            print_code_statistics()
            return
        if options.write_schema_and_exit:
            write_schema(options.pipeline_filename)
            return
        #
        # ------------------------------------------
        if options.show_gui:
            import wx
            wx.Log.EnableLogging(False)
            from cellprofiler.gui.app import App
            from cellprofiler.workspace import is_workspace_file

            if options.pipeline_filename:
                if is_workspace_file(options.pipeline_filename):
                    workspace_path = os.path.expanduser(options.pipeline_filename)
                    pipeline_path = None
                else:
                    pipeline_path = os.path.expanduser(options.pipeline_filename)
                    workspace_path = None
            elif options.new_project:
                workspace_path = False
                pipeline_path = None
            else:
                workspace_path = None
                pipeline_path = None

            app = App(0, workspace_path=workspace_path, pipeline_path=pipeline_path)

        if options.data_file is not None:
            cpprefs.set_data_file(os.path.abspath(options.data_file))

        from cellprofiler.utilities.version import version_string, version_number
        logging.root.info("Version: %s / %d" % (version_string, version_number))

        if options.run_pipeline and not options.pipeline_filename:
            raise ValueError("You must specify a pipeline filename to run")

        if options.output_directory:
            if not os.path.exists(options.output_directory):
                os.makedirs(options.output_directory)
            cpprefs.set_default_output_directory(options.output_directory)

        if options.image_directory:
            cpprefs.set_default_image_directory(options.image_directory)

        if options.show_gui:
            if options.run_pipeline:
                app.frame.pipeline_controller.do_analyze_images()
            app.MainLoop()
            return

        elif options.run_pipeline:
            run_pipeline_headless(options, args)
    except Exception, e:
        logging.root.fatal("Uncaught exception in CellProfiler.py", exc_info=True)
        exit_code = -1
예제 #17
0
파일: zn.py 프로젝트: cbosoft/pi_rheo_proj
from sys import path
from matplotlib import use as mpluse
mpluse('Agg')
import matplotlib.pyplot as plt
path.append("./../bin/")

import motor
import resx
from time import sleep
m = motor.motor()
m.start_poll(name="test.csv", controlled=False)
m.update_setpoint(100)
m.set_dc(25)
print "warming up motor"
sleep(2)
m.start_control()

Ku = 4

m.pidc.tuning = (Ku, 0.0, 0.0)
m.pidc.tuning = (1.8, 2.85, 0.0)

errs_ = list()
times = list()

print "control started\ttuning: {}".format(m.pidc.tuning)
m.update_setpoint(100)

print "waiting"
for i in range(0, 1):
    #print "speed  {:.3f}  gd {:.3f}  lav  {} err {}".format(m.speed, resx.get_strain((m.speed * 2 * 3.14) / 60.0), m.ldc, m.pidc.lerr)
예제 #18
0
if options.run_ilastik:
    #
    # Fake ilastik into thinking it is __main__
    #
    import ilastik
    import imp
    sys.argv.remove("--ilastik")
    il_path = ilastik.__path__
    il_file, il_path, il_description = imp.find_module('ilastikMain', il_path)
    imp.load_module('__main__', il_file, il_path, il_description)
    sys.exit()

# necessary to prevent matplotlib trying to use Tkinter as its backend.
# has to be done before CellProfilerApp is imported
from matplotlib import use as mpluse
mpluse('WXAgg')

if (not hasattr(sys, 'frozen')) and options.fetch_external_dependencies:
    import external_dependencies
    external_dependencies.fetch_external_dependencies(
        options.overwrite_external_dependencies)

if (not hasattr(sys, 'frozen')) and options.build_extensions:
    import subprocess
    import cellprofiler.cpmath.setup
    import cellprofiler.utilities.setup
    from distutils.dep_util import newer_group
    #
    # Check for dependencies and compile if necessary
    #
    compile_scripts = [(os.path.join('cellprofiler', 'cpmath',
예제 #19
0
def main(args=None):
    '''Run CellProfiler

    args - command-line arguments, e.g. sys.argv
    '''
    if args is None:
        args = sys.argv
    import cellprofiler.preferences as cpprefs
    cpprefs.set_awt_headless(True)
    exit_code = 0
    switches = ('--work-announce', '--knime-bridge-address')
    if any(
        [any([arg.startswith(switch) for switch in switches])
         for arg in args]):
        #
        # Go headless ASAP
        #
        cpprefs.set_headless()
        for i, arg in enumerate(args):
            if arg == "--ij-plugins-directory" and len(args) > i + 1:
                cpprefs.set_ij_plugin_directory(args[i + 1])
                break
        import cellprofiler.worker
        cellprofiler.worker.aw_parse_args()
        cellprofiler.worker.main()
        sys.exit(exit_code)

    options, args = parse_args(args)
    if options.print_version:
        from cellprofiler.utilities.version import \
            dotted_version, version_string, git_hash, version_number
        print "CellProfiler %s" % dotted_version
        print "Git %s" % git_hash
        print "Version %s" % version_number
        print "Built %s" % version_string.split(" ")[0]
        sys.exit(exit_code)
    #
    # Important to go headless ASAP
    #
    if (not options.show_gui) or options.write_schema_and_exit:
        import cellprofiler.preferences as cpprefs
        cpprefs.set_headless()
        # What's there to do but run if you're running headless?
        # Might want to change later if there's some headless setup
        options.run_pipeline = True

    if options.jvm_heap_size is not None:
        from cellprofiler.preferences import set_jvm_heap_mb
        set_jvm_heap_mb(options.jvm_heap_size, False)
    set_log_level(options)

    if options.print_groups_file is not None:
        print_groups(options.print_groups_file)
        return

    if options.batch_commands_file is not None:
        get_batch_commands(options.batch_commands_file)
        return

    if options.add_message_for_user:
        if len(args) != 3:
            sys.stderr.write("Usage: (for add_message-for-user)\n")
            sys.stderr.write(
                "CellProfiler --add-message-for-user <caption> <message> <pipeline-or-project>\n"
            )
            sys.stderr.write("where:\n")
            sys.stderr.write("    <caption> - the message box caption\n")
            sys.stderr.write(
                "    <message> - the message displayed inside the message box\n"
            )
            sys.stderr.write(
                "    <pipeline-or-project> - the path to the pipeline or project file to modify\n"
            )
            return
        caption = args[0]
        message = args[1]
        path = args[2]

        import h5py
        using_hdf5 = h5py.is_hdf5(path)
        if using_hdf5:
            import cellprofiler.measurement as cpmeas
            m = cpmeas.Measurements(filename=path, mode="r+")
            pipeline_text = m[cpmeas.EXPERIMENT, "Pipeline_Pipeline"]
        else:
            with open(path, "r") as fd:
                pipeline_text = fd.read()
        header, body = pipeline_text.split("\n\n", 1)
        pipeline_text = header + \
                        ("\nMessageForUser:%s|%s\n\n" % (caption, message)) + body
        if using_hdf5:
            m[cpmeas.EXPERIMENT, "Pipeline_Pipeline"] = pipeline_text
            m.close()
        else:
            with open(path, "w") as fd:
                fd.write(pipeline_text)
        print "Message added to %s" % path
        return

    # necessary to prevent matplotlib trying to use Tkinter as its backend.
    # has to be done before CellProfilerApp is imported
    from matplotlib import use as mpluse
    mpluse('WXAgg')

    if options.omero_credentials is not None:
        set_omero_credentials_from_string(options.omero_credentials)
    if options.plugins_directory is not None:
        cpprefs.set_plugin_directory(options.plugins_directory, globally=False)
    if options.ij_plugins_directory is not None:
        cpprefs.set_ij_plugin_directory(options.ij_plugins_directory,
                                        globally=False)
    if options.temp_dir is not None:
        if not os.path.exists(options.temp_dir):
            os.makedirs(options.temp_dir)
        cpprefs.set_temporary_directory(options.temp_dir, globally=False)
    if not options.allow_schema_write:
        cpprefs.set_allow_schema_write(False)
    #
    # After the crucial preferences are established, we can start the VM
    #
    from cellprofiler.utilities.cpjvm import cp_start_vm
    cp_start_vm()
    #
    # Not so crucial preferences...
    #
    if options.image_set_file is not None:
        cpprefs.set_image_set_file(options.image_set_file)
    try:
        # ---------------------------------------
        #
        # Handle command-line tasks that that need to load the modules to run
        #
        if options.output_html:
            from cellprofiler.gui.html.manual import generate_html
            webpage_path = options.output_directory if options.output_directory else None
            generate_html(webpage_path)
            return
        if options.print_measurements:
            print_measurements(options)
            return
        if not hasattr(sys, "frozen") and options.code_statistics:
            print_code_statistics()
            return
        if options.write_schema_and_exit:
            write_schema(options.pipeline_filename)
            return
        #
        # ------------------------------------------
        if options.show_gui:
            import wx
            wx.Log.EnableLogging(False)
            from cellprofiler.gui.app import App
            from cellprofiler.workspace import is_workspace_file

            if options.pipeline_filename:
                if is_workspace_file(options.pipeline_filename):
                    workspace_path = os.path.expanduser(
                        options.pipeline_filename)
                    pipeline_path = None
                else:
                    pipeline_path = os.path.expanduser(
                        options.pipeline_filename)
                    workspace_path = None
            elif options.new_project:
                workspace_path = False
                pipeline_path = None
            else:
                workspace_path = None
                pipeline_path = None

            app = App(0,
                      workspace_path=workspace_path,
                      pipeline_path=pipeline_path)

        if options.data_file is not None:
            cpprefs.set_data_file(os.path.abspath(options.data_file))

        from cellprofiler.utilities.version import version_string, version_number
        logging.root.info("Version: %s / %d" %
                          (version_string, version_number))

        if options.run_pipeline and not options.pipeline_filename:
            raise ValueError("You must specify a pipeline filename to run")

        if options.output_directory:
            if not os.path.exists(options.output_directory):
                os.makedirs(options.output_directory)
            cpprefs.set_default_output_directory(options.output_directory)

        if options.image_directory:
            cpprefs.set_default_image_directory(options.image_directory)

        if options.show_gui:
            if options.run_pipeline:
                app.frame.pipeline_controller.do_analyze_images()
            app.MainLoop()
            return

        elif options.run_pipeline:
            run_pipeline_headless(options, args)
    except Exception, e:
        logging.root.fatal("Uncaught exception in CellProfiler.py",
                           exc_info=True)
        exit_code = -1
예제 #20
0
 Any live cell with two or three live neighbours lives
 on to the next generation.
 3.
 Any live cell with more than three live neighbours
 dies, as if by over-population.
 4.
 Any dead cell with exactly three live neighbours be-
 comes a live cell, as if by reproduction.
 '''
import random
import sys

import numpy as np

from matplotlib import use as mpluse
mpluse('TkAgg')
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

usage_doc = 'Usage of script: script_nama <size_of_canvas:int>'

choice = [0] * 100 + [1] * 10
random.shuffle(choice)


def create_canvas(size):
    canvas = [[False for i in range(size)] for j in range(size)]
    return canvas


def seed(canvas):