def calculate(self, filtering=False): cxs = self.pre_clean_xs cys = self.pre_clean_ys if not self._check_integrity(cxs, cys): # logger.debug('A integrity check failed') # import traceback # traceback.print_stack() return if not filtering: # prevent infinite recursion fx, fy = self.calculate_filtered_data() else: fx, fy = cxs, cys try: coeffs, cov = optimize.curve_fit( self.fitfunc, fx, fy, p0=self._calculate_initial_guess()) self._coefficients = list(coeffs) self._covariance = cov self._coefficient_errors = list(sqrt(diagonal(cov))) except RuntimeError: from pyface.message_dialog import warning warning(None, 'Exponential failed to converge. Choose a different fit') raise FitError()
def submit(self, info): if not self.model.title: warning(None, 'Please enter a Title for this issue') return self.submit_issue_github() info.ui.dispose()
def get_plugin(pname): klass = None if not pname.endswith('Plugin'): pname = '{}Plugin'.format(pname) # print PACKAGE_DICT.keys() # print pname,pname in PACKAGE_DICT.keys() if pname in PACKAGE_DICT: package = PACKAGE_DICT[pname] klass = get_klass(package, pname) else: logger.warning('****** {} not a valid plugin name******'.format(pname), extra={'threadName_': 'Launcher'}) if klass is not None: plugin = klass() if isinstance(plugin, BasePlugin): check = plugin.check() if check is True: return plugin else: logger.warning('****** {} not available {}******'.format( klass, check), extra={'threadName_': 'Launcher'}) warning(None, 'Failed loading plugin.\n {}'.format(plugin.name)) else: logger.warning( '***** Invalid {} needs to be a subclass of Plugin ******'. format(klass), extra={'threadName_': 'Launcher'})
def _add_decay_constant_fired(self): e = DecayConstantEntry() for a in LAMBDA_K_ATTRS: setattr(e, a, getattr(self, a)) info = e.edit_traits() name = e.name if info.result and name: if name not in self.decay_constant_names: nv = e.totuple() exists = next( (k for k, v in self.decay_constant_entries.iteritems() if nv == v), None) if exists: warning( None, 'Decay constant entry with those values already exists.\nExisting entry named "{}"' .format(exists)) else: self.decay_constant_names.append(name) self.decay_constant_entries[name] = e.totuple() self.decay_constant_name = name else: warning(None, 'Decay constant entry with that name alreay exists')
def git_post(cmd, return_json=True, **kw): usr = os.environ.get('GITHUB_USER') pwd = os.environ.get('GITHUB_PASSWORD') if not pwd: warning(None, 'No password set for "{}". Contact Developer.\n' 'Pychron will quit when this window is closed'.format(usr)) sys.exit() kw['auth'] = (usr, pwd) if globalv.cert_file: kw['verify'] = globalv.cert_file r = requests.post(cmd, **kw) if r.status_code == 401: warning(None, 'Failed to submit issue. Username/Password incorrect.') elif r.status_code == 403: print('asf', r.json()) if r.status_code in (201, 422): ret = True if return_json: ret = r.json() return ret
def check_dependencies(): """ check the dependencies and """ from pyface.api import warning try: mod = __import__('uncertainties', fromlist=['__version__'] ) __version__ = mod.__version__ except ImportError: warning(None, 'Install "{}" package. required version>={} '.format('uncertainties', '2.1')) return vargs = __version__.split('.') maj = vargs[0] if int(maj) < 2: warning(None, 'Update "{}" package. your version={}. required version>={} '.format('uncertainties', __version__, '2.1' )) return return True
def get_plugin(pname): klass = None if not pname.endswith('Plugin'): pname = '{}Plugin'.format(pname) if pname in PACKAGE_DICT: package = PACKAGE_DICT[pname] klass = get_klass(package, pname) else: logger.warning('****** {} not a valid plugin name******'.format(pname), extra={'threadName_': 'Launcher'}) if klass is not None: plugin = klass() if isinstance(plugin, BasePlugin): check = plugin.check() if check is True: return plugin else: logger.warning('****** {} not available {}******'.format(klass, check), extra={'threadName_': 'Launcher'}) warning(None, 'Failed loading plugin.\n {}'.format(plugin.name)) else: logger.warning('***** Invalid {} needs to be a subclass of Plugin ******'.format(klass), extra={'threadName_': 'Launcher'})
def build_globals(debug): try: from pychron.envisage.initialization.initialization_parser import InitializationParser except ImportError, e: from pyface.message_dialog import warning warning(None, str(e))
def _run(self): p = os.path.join(self.root, self.name) if not os.path.exists(p): warning(None, 'Invalid Clovera path {}'.format(self.root)) return # n = 5 # pd = MProgressDialog(max=n, size=(550, 15)) # do_later(pd.open) # do_later(pd.change_message, '{} process started'.format(self.name)) try: p = subprocess.Popen([p], shell=False, bufsize=1024, stdout=subprocess.PIPE ) self._process = p while p.poll() == None: if self.queue: self.queue.put(p.stdout.readline()) time.sleep(1e-6) self.success = True # do_later(pd.change_message, '{} process complete'.format(self.name)) return True except OSError, e: self.warning_dialog('Clovera programs are not executable. Check Default Clovera Directory.\n{}'.format(e)) import traceback traceback.print_exc()
def save(self, ans, db): append = False if not self.name: warning(None, 'Please specify a name for the analysis group') return if not self.project: warning(None, 'Please specify an associated project for the analysis group') return gdb = db.get_analysis_groups_by_name(self.name, self.project) ok = True if gdb: gdb = gdb[-1] if db.confirmation_dialog('"{}" already exists? Would you like to append your selection'.format(gdb.name)): append = True else: ok = False if append: db.append_analysis_group(gdb, ans) elif ok: db.add_analysis_group(ans, self.name, self.project) return True
def _get_runner(self, event): app = event.task.application runner = app.get_service(IPyScriptRunner) if not runner: warning(None, 'No runner available') return runner
def git_post(cmd, return_json=True, **kw): usr = os.environ.get('GITHUB_USER') pwd = os.environ.get('GITHUB_PASSWORD') if not pwd: warning( None, 'No password set for "{}". Contact Developer.\n' 'Pychron will quit when this window is closed'.format(usr)) sys.exit() kw['auth'] = (usr, pwd) if globalv.cert_file: kw['verify'] = globalv.cert_file r = requests.post(cmd, **kw) if r.status_code == 401: warning(None, 'Failed to submit issue. Username/Password incorrect.') elif r.status_code == 403: print('asf', r.json()) if r.status_code in (201, 422): ret = True if return_json: ret = r.json() return ret
def __init__(self, *args, **kw): p = os.path.join(paths.setup_dir, 'initialization.xml') if os.path.isfile(p): super(InitializationParser, self).__init__(p, *args, **kw) else: warning(None, 'No initialization file') sys.exit()
def wx_dropped_on(self, x, y, data, drag_result): """ Handles a Python object being dropped on the window. """ if isinstance(data, (IDockUIProvider, DockControl)): window = self.control dock_info = self._dock_info # See the 'wx_drag_leave' method for an explanation of this code: if dock_info is None: dock_info = self._leave_info dock_info.draw(window) self._dock_info = None try: control = self.handler.dock_control_for(*(self.handler_args + (window, data))) # Safely check to see if the object quacks like a Binding binding = getattr(clipboard, "node", None) if (hasattr(binding, "obj") and (binding.obj is data) and hasattr(binding, "namespace_name")): control.id = "@@%s" % binding.namespace_name dock_info.dock(control, window) return drag_result except: warning( window, "An error occurred while attempting to add an item of " "type '%s' to the window." % data.__class__.__name__, title="Cannot add item to window", ) return wx.DragNone
def _run(self): p = os.path.join(self.root, self.name) if not os.path.exists(p): warning(None, 'Invalid Clovera path {}'.format(self.root)) return # n = 5 # pd = myProgressDialog(max=n, size=(550, 15)) # do_later(pd.open) # do_later(pd.change_message, '{} process started'.format(self.name)) try: p = subprocess.Popen([p], shell=False, bufsize=1024, stdout=subprocess.PIPE) self._process = p while p.poll() == None: if self.queue: self.queue.put(p.stdout.readline()) time.sleep(1e-6) self.success = True # do_later(pd.change_message, '{} process complete'.format(self.name)) return True except OSError, e: self.warning_dialog( 'Clovera programs are not executable. Check Default Clovera Directory.\n{}' .format(e)) import traceback traceback.print_exc()
def start(self): try: import xlwt except ImportError: warning(None, '''"xlwt" package not installed. Install to enable MS Excel export''')
def _handle(*args, **kw): try: return func(*args, **kw) except Exception, e: import traceback traceback.print_exc() warning(None, 'There is a problem in your initialization file {}'.format(e)) sys.exit()
def perform(self, event): if os.path.isfile(paths.last_experiment): with open(paths.last_experiment, 'r') as fp: path = fp.readline() if os.path.isfile(path): self._open_experiment(event, path) else: warning(None, 'No last experiment available')
def start(self): try: import xlwt except ImportError: warning( None, '''"xlwt" package not installed. Install to enable MS Excel export''')
def _add_root_button_fired(self): dlg = DirectoryDialog(default_path=paths.mdd_data_dir) if dlg.open() == OK and dlg.path: name = os.path.basename(dlg.path) if os.path.isfile(os.path.join(dlg.path, '{}.in'.format(name))): self.roots.append(dlg.path) else: warning(None, 'Invalid MDD directory. {}. Directory must contain file ' 'named {}.in'.format(dlg.path, name))
def _load_analyses(self): from pychron.core.csv.csv_parser import CSVColumnParser par = CSVColumnParser(delimiter=',') par.load(self.path) if par.check(('runid', 'age', 'age_err')): return self._get_items_from_file(par) else: warning(None, 'Invalid file format. Minimum columns required are "runid", "age", "age_err"')
def _get_working_repo(self, inform): if not self._repo: try: self._repo = Repo(paths.build_repo) except InvalidGitRepositoryError: if inform: warning(None, 'Invalid Build repository {}.\n' 'Pychron not properly configured for update. \n\n' 'Contact developer'.format(paths.build_repo)) return self._repo
def _get_working_repo(self, inform): if not self._repo: try: self._repo = Repo(self.build_repo) except InvalidGitRepositoryError: if inform: warning(None, 'Invalid Build repository {}.\n' 'Pychron not properly configured for update. \n\n' 'Contact developer'.format(self.build_repo)) return self._repo
def __init__(self, path=None, *args, **kw): if path: self.path = path try: self._parse_file(path) except ParseError as e: from pyface.message_dialog import warning warning(None, str(e)) else: self._root = Element('root')
def _check_refit(self, ai): for k in self._keys: num, dem = k.split('/') i = ai.get_isotope(detector=dem) if i is not None: if not i.ic_factor_reviewed: return True else: from pyface.message_dialog import warning warning(None, 'Data for detector {} is missing from {}'.format(dem, ai.record_id)) raise RefitException()
def init(self): try: self._dev = self._dev_factory() except BaseException, e: print e warning( None, 'Invalid device address. {}. Entering simulation mode'.format( self.address)) self._simulation = True return
def _add_root_button_fired(self): dlg = DirectoryDialog(default_path=paths.mdd_data_dir) if dlg.open() == OK and dlg.path: name = os.path.basename(dlg.path) if os.path.isfile(os.path.join(dlg.path, '{}.in'.format(name))): self.roots.append(dlg.path) else: warning( None, 'Invalid MDD directory. {}. Directory must contain file ' 'named {}.in'.format(dlg.path, name))
def perform(self, event): app = event.task.window.application dvc = app.get_service(DVC_PROTOCOL) if dvc.db.kind != 'mysql': warning(None, 'Your are not using a centralized MySQL database') else: from pychron.dvc.work_offline import WorkOffline wo = WorkOffline(dvc=dvc, application=app) if wo.initialize(): wo.edit_traits()
def interpolate(x, y, ind=None, width=10, func=None): """ modified from peakutils to handle edge peaks Tries to enhance the resolution of the peak detection by using Gaussian fitting, centroid computation or an arbitrary function on the neighborhood of each previously detected peak index. Parameters ---------- x : ndarray Data on the x dimension. y : ndarray Data on the y dimension. ind : ndarray Indexes of the previously detected peaks. If None, indexes() will be called with the default parameters. width : int Number of points (before and after) each peak index to pass to *func* in order to encrease the resolution in *x*. func : function(x,y) Function that will be called to detect an unique peak in the x,y data. Returns ------- ndarray : Array with the adjusted peak positions (in *x*) """ out = [] try: if func is None: from peakutils import gaussian_fit func = gaussian_fit if ind is None: from peakutils import indexes ind = indexes(y) for slice_ in (slice(max(0, i - width), min(i + width, y.shape[0])) for i in ind): try: fit = func(x[slice_], y[slice_]) out.append(fit) except Exception: pass except ImportError: from pyface.message_dialog import warning warning( None, 'PeakUtils required to identify and label peaks.\n\n' 'Please install PeakUtils. From commandline use "pip install peakutils"' ) return array(out)
def perform(self, event): app = event.task.window.application dvc = app.get_service('pychron.dvc.dvc.DVC') if dvc.db.kind != 'mysql': warning(None, 'Your are not using a centralized MySQL database') else: from pychron.dvc.work_offline import WorkOffline wo = WorkOffline(dvc=dvc, application=app) if wo.initialize(): wo.edit_traits()
def _load_analyses(self): from pychron.core.csv.csv_parser import CSVColumnParser par = CSVColumnParser(delimiter=',') par.load(self.path) if par.check(('runid', 'age', 'age_err')): return self._get_items_from_file(par) else: warning( None, 'Invalid file format. Minimum columns required are "runid", "age", "age_err"' )
def fast_find_peaks(ys, xs, **kw): try: from peakutils import indexes except ImportError: from pyface.message_dialog import warning warning(None, 'PeakUtils required to identify and label peaks.\n\n' 'Please install PeakUtils. From commandline use "pip install peakutils"') return [], [] ys, xs = asarray(ys), asarray(xs) indexes = indexes(ys, **kw) peaks_x = interpolate(xs, ys, ind=indexes) return peaks_x, ys[indexes]
def _test_connection_button_fired(self): kw = self._get_connection_dict() self._connected_label = 'Not Connected' self._connected_color = 'red' if kw is not None: c = self._test_connection(kw) if c: self._connected_color = 'green' self._connected_label = 'Connected' else: warning(None, 'Please select a connection to test')
def _check_refit(self, ai): for k in self._keys: num, dem = k.split('/') i = ai.get_isotope(detector=dem) if i is not None: if not i.ic_factor_reviewed: return True else: from pyface.message_dialog import warning warning( None, 'Data for detector {} is missing from {}'.format( dem, ai.record_id)) raise RefitException()
def interpolate(x, y, ind=None, width=10, func=None): """ modified from peakutils to handle edge peaks Tries to enhance the resolution of the peak detection by using Gaussian fitting, centroid computation or an arbitrary function on the neighborhood of each previously detected peak index. Parameters ---------- x : ndarray Data on the x dimension. y : ndarray Data on the y dimension. ind : ndarray Indexes of the previously detected peaks. If None, indexes() will be called with the default parameters. width : int Number of points (before and after) each peak index to pass to *func* in order to encrease the resolution in *x*. func : function(x,y) Function that will be called to detect an unique peak in the x,y data. Returns ------- ndarray : Array with the adjusted peak positions (in *x*) """ out = [] try: if func is None: from peakutils import gaussian_fit func = gaussian_fit if ind is None: from peakutils import indexes ind = indexes(y) for slice_ in (slice(max(0, i - width), min(i + width, y.shape[0])) for i in ind): try: fit = func(x[slice_], y[slice_]) out.append(fit) except Exception: pass except ImportError: from pyface.message_dialog import warning warning(None, 'PeakUtils required to identify and label peaks.\n\n' 'Please install PeakUtils. From commandline use "pip install peakutils"') return array(out)
def load_isotopedb_defaults(db): for name, mass in MOLECULAR_WEIGHTS.iteritems(): db.add_molecular_weight(name, mass) for at in ['blank_air', 'blank_cocktail', 'blank_unknown', 'background', 'air', 'cocktail', 'unknown']: # blank', 'air', 'cocktail', 'background', 'unknown']: db.add_analysis_type(at) for mi in ['obama', 'jan', 'nmgrl map']: db.add_mass_spectrometer(mi) for i, di in enumerate(['blank_air', 'blank_cocktail', 'blank_unknown', 'background', 'air', 'cocktail']): samp = db.add_sample(di) db.add_labnumber(i + 1, sample=samp) for hi, kind, make in [('Fusions CO2', '10.6um co2', 'photon machines'), ('Fusions Diode', '810nm diode', 'photon machines'), ('Fusions UV', '193nm eximer', 'photon machines') ]: db.add_extraction_device(name=hi, kind=kind, make=make ) mdir = os.path.join(paths.setup_dir, 'irradiation_tray_maps') if not os.path.isdir(mdir): warning(None, 'No irradiation_tray_maps directory. add to .../setupfiles') else: for t in os.listdir(mdir): if t.startswith('.'): continue p = os.path.join(mdir, t) if not os.path.isfile(p): continue with open(p, 'r') as f: h = f.readline() nholes, _diam = h.split(',') nholes = int(nholes) holes = [map(float, l.strip().split(',')) for i, l in enumerate(f) if i < nholes] blob = ''.join([struct.pack('>ff', x, y) for x, y in holes]) db.add_irradiation_holder(t, geometry=blob) db.commit()
def close(self, info, is_ok): if is_ok: name = info.object.name.strip() if name == '': warning(info.ui.control, 'No name specified', title='Save Layout Error') return False if name in self.names: return error(message='%s is already defined. Replace?' % name, title='Save Layout Warning', parent=info.ui.control) return True
def make(self, irrad_names): irrad_selector = IrradiationSelector(irradiations=irrad_names) while 1: info = irrad_selector.edit_traits() if info.result: irradiations = irrad_selector.irradiations[1:4] # irradiations = irrad_selector.selected if not irradiations: warning('You must select one or more irradiations') else: self._make(irradiations) break else: break
def build_globals(user, debug): try: from pychron.envisage.initialization.initialization_parser import InitializationParser except ImportError as e: from pyface.message_dialog import warning warning(None, str(e)) ip = InitializationParser() from pychron.globals import globalv globalv.build(ip) globalv.debug = debug globalv.username = user
def _new_fit_series(self, pid, po): ymi, yma = self._plot_unknowns_current(pid, po) args = self._plot_references(pid, po) if args: reg, a, b = args ymi = min(ymi, a) yma = max(yma, b) if reg: a, b = self._plot_interpolated(pid, po, reg) ymi = min(ymi, a) yma = max(yma, b) self.graph.set_y_limits(ymi, yma, pad='0.05', plotid=pid) else: warning(None, 'Invalid Detector choices for these analyses. {}'.format(po.name))
def fast_find_peaks(ys, xs, **kw): try: from peakutils import indexes except ImportError: from pyface.message_dialog import warning warning( None, 'PeakUtils required to identify and label peaks.\n\n' 'Please install PeakUtils. From commandline use "pip install peakutils"' ) return [], [] ys, xs = asarray(ys), asarray(xs) indexes = indexes(ys, **kw) peaks_x = interpolate(xs, ys, ind=indexes) return peaks_x, ys[indexes]
def perform(self, event): from pychron.experiment.conditional.conditionals_edit_view import edit_conditionals task = event.task dnames = None spec = task.application.get_service( 'pychron.spectrometer.base_spectrometer_manager.BaseSpectrometerManager') if spec: dnames = spec.spectrometer.detector_names p = get_path(paths.spectrometer_dir, '.*conditionals', ('.yaml','.yml')) if p: edit_conditionals(p, detectors=dnames, app=task.application) else: warning(None, 'No system conditionals file at {}'.format(p))
def perform(self, event): # from pychron.entry.irradiation_table_writer import IrradiationTableWriter # a = IrradiationTableWriter() # a.make() from pychron.entry.irradiation_xls_writer import IrradiationXLSTableWriter dvc = self.task.window.application.get_service('pychron.dvc.dvc.DVC') if dvc is not None: if dvc.db.connect(): names = dvc.get_irradiation_names() a = IrradiationXLSTableWriter(dvc=dvc) a.make(names) else: from pyface.message_dialog import warning warning(None, 'DVC Plugin is required. Please enable')
def _load_names(self): if self.username and self.password and self.host: if self.host: def func(): self._progress_state = True do_after(50, func) self._names = show_databases(self.host, self.username, self.password, self._schema_identifier) def func(): self._progress_state = True do_after(50, func) else: warning(None, 'Invalid IP address format. "{}" e.g 129.255.12.255'.format(self.host))
def _load_names(self): if self.username and self.password and self.host: if self.host: def func(): self.progress_state = True do_after(50, func) self._names = show_databases(self.host, self.username, self.password) def func(): self.progress_state = True do_after(50, func) else: warning(None, 'Invalid IP address format. "{}" e.g 129.255.12.255'.format(self.host))
def perform(self, event): from pychron.experiment.conditional.conditionals_edit_view import edit_conditionals task = event.task dnames = None spec = task.application.get_service( 'pychron.spectrometer.base_spectrometer_manager.BaseSpectrometerManager' ) if spec: dnames = spec.spectrometer.detector_names p = get_path(paths.spectrometer_dir, '.*conditionals', ('.yaml', '.yml')) if p: edit_conditionals(p, detectors=dnames, app=task.application) else: warning(None, 'No system conditionals file at {}'.format(p))
def __init__(self, *args, **kw): ver = '_proc' # ver = '_exp' #ver = '_exp_uv' #ver= '_spec' # ver='_diode' # ver = '_dash' #ver = '_dash_client' #ver = '' p = os.path.join(paths.setup_dir, 'initialization{}.xml'.format(ver)) if not os.path.isfile(p): p = os.path.join(paths.setup_dir, 'initialization.xml') if not os.path.isfile(p): warning(None, 'No initialization file.\n{} is not a valid file'.format(p)) sys.exit() super(InitializationParser, self).__init__(p, *args, **kw)
def _test_connection_button_fired(self): kw = self._get_connection_dict() self._connected_label = 'Not Connected' self._connected_color = 'red' if kw is not None: klass = self._get_adapter() db = klass(**kw) self._connected_label = '' if self._test_func: db.test_func = self._test_func c = db.connect(warn=False) if c: self._connected_color = 'green' self._connected_label = 'Connected' else: warning(None, 'Please select a connection to test')
def get_db(): conn = dict(host=os.environ.get('ARGONSERVER_HOST'), username='******', # os.environ.get('ARGONSERVER_DB_USER'), password=os.environ.get('ARGONSERVER_DB_PWD'), kind='mysql') paths.build('~/PychronDev') meta_name = 'NMGRLMetaData' dvc = DVC(bind=False, organization='NMGRLData', meta_repo_name=meta_name) paths.meta_root = os.path.join(paths.dvc_dir, dvc.meta_repo_name) dvc.db.trait_set(**conn) if not dvc.initialize(): warning(None, 'Failed to initialize DVC') return dvc.meta_repo.smart_pull() return dvc