text
stringlengths
12
1.05M
repo_name
stringlengths
5
86
path
stringlengths
4
191
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
12
1.05M
keyword
listlengths
1
23
text_hash
stringlengths
64
64
from __future__ import absolute_import from StringIO import StringIO import mock import requests from boto.s3.key import Key EXPECTED_TASK_STATUS_FAILED_RESPONSE = { "s3_urls": {}, "src_url": "", "state": "FAILURE", "status": "{u'exc_message': u'fp is at EOF. Use rewind option or seek() to data start.'" ", u'exc_type': u'AttributeError'}" } EXPECTED_TASK_STATUS_INCOMPLETE_RESPONSE = { "s3_urls": {}, "src_url": "", "state": "STARTED", "status": "no task status at this point", } EXPECTED_TASK_STATUS_SUCCESSFUL_RESPONSE = { "s3_urls": { "us-east-1": "https://archiver-us-east-1.s3.amazonaws.com/mozilla-central-9213957d1.tar.gz", "us-west-2": "https://archiver-us-west-2.s3.amazonaws.com/mozilla-central-9213957d1.tar.gz", }, "src_url": "https://hg.mozilla.org/mozilla-central/archive/9213957d1.tar.gz/testing/mozharness", "state": "SUCCESS", "status": "Task completed! Check 's3_urls' for upload locations." } EXPECTED_TASK_STATUS_PENDING_RESPONSE = { "s3_urls": { "us-east-1": "https://archiver-us-east-1.s3.amazonaws.com/mozilla-central-9213957d1.tar.gz", "us-west-2": "https://archiver-us-west-2.s3.amazonaws.com/mozilla-central-9213957d1.tar.gz", }, "src_url": "https://hg.mozilla.org/mozilla-central/archive/9213957d1.tar.gz/testing/mozharness", "state": "PENDING", "status": "no task status at this point", } def setup_buckets(app, cfg): for region, bucket in cfg['ARCHIVER_S3_BUCKETS'].iteritems(): s3 = app.aws.connect_to('s3', region) s3.create_bucket(bucket) def create_s3_items(app, cfg, key): for region, bucket in cfg['ARCHIVER_S3_BUCKETS'].iteritems(): s3 = app.aws.connect_to('s3', region) b = s3.get_bucket(bucket) k = Key(b) k.key = key k.set_contents_from_string("Help, I'm trapped in an alternate s3 dimension.") def fake_200_response(): response = mock.Mock() response.status_code = 200 response.headers = { 'Content-Type': 'application/x-gzip', 'Content-Disposition': 'attachment; filename=mozilla-central-9213957d166d.tar.gz' } response.raw = StringIO("Debugging is twice as hard as writing the code in the first place. " "Therefore, if you write the code as cleverly as possible, you are, " "by definition, not smart enough to debug it. --Brian W. Kernighan") return response def fake_404_response(): response = mock.Mock() response.status_code = 404 response.raise_for_status.side_effect = requests.exceptions.HTTPError('does not exist yo!') return response def fake_failed_task_status(): task = mock.Mock() task.state = EXPECTED_TASK_STATUS_FAILED_RESPONSE['state'] task.info = EXPECTED_TASK_STATUS_FAILED_RESPONSE['status'] return task def fake_successful_task_status(): task = mock.Mock() task.state = EXPECTED_TASK_STATUS_SUCCESSFUL_RESPONSE['state'] task.info = { 'src_url': EXPECTED_TASK_STATUS_SUCCESSFUL_RESPONSE['src_url'], 's3_urls': EXPECTED_TASK_STATUS_SUCCESSFUL_RESPONSE['s3_urls'], 'status': EXPECTED_TASK_STATUS_SUCCESSFUL_RESPONSE['status'], } return task def fake_expired_task_status(): task = mock.Mock() task.state = EXPECTED_TASK_STATUS_PENDING_RESPONSE['state'] task.info = { 'src_url': EXPECTED_TASK_STATUS_PENDING_RESPONSE['src_url'], 's3_urls': EXPECTED_TASK_STATUS_PENDING_RESPONSE['s3_urls'], 'status': EXPECTED_TASK_STATUS_PENDING_RESPONSE['status'], } return task def fake_incomplete_task_status(): task = mock.Mock() task.state = EXPECTED_TASK_STATUS_INCOMPLETE_RESPONSE['state'] task.status = { 'status': EXPECTED_TASK_STATUS_INCOMPLETE_RESPONSE['status'], } return task
hwine/build-relengapi
relengapi/blueprints/archiver/test_util.py
Python
mpl-2.0
3,879
[ "Brian" ]
a0ed09863c4d5788a4b26c17aaa64059489cd1775ef1014478aa581ee0c3e080
#!/usr/bin/env python # -*- mode: python; coding: utf-8; -*- ##---------------------------------------------------------------------------## ## ## Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer ## Copyright (C) 2003 Mt. Hood Playing Card Co. ## Copyright (C) 2005-2009 Skomoroh ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## 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/>. ## ##---------------------------------------------------------------------------## __all__ = ['SingleGame_StatsDialog', 'AllGames_StatsDialog', 'FullLog_StatsDialog', 'SessionLog_StatsDialog', 'Status_StatsDialog', 'Top_StatsDialog', 'ProgressionDialog', ] # imports import os import time import Tkinter, tkFont # PySol imports from pysollib.mfxutil import kwdefault, KwStruct from pysollib.mfxutil import format_time ##from pysollib.util import * from pysollib.stats import PysolStatsFormatter, ProgressionFormatter from pysollib.settings import TOP_TITLE # Toolkit imports from tkutil import bind, unbind_destroy, loadImage from tkwidget import MfxDialog, MfxMessageDialog from tkwidget import MfxScrolledCanvas # FIXME - this file a quick hack and needs a rewrite # ************************************************************************ # * # ************************************************************************ class SingleGame_StatsDialog(MfxDialog): def __init__(self, parent, title, app, player, gameid, **kw): self.app = app self.selected_game = None kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.top_frame = top_frame self.createBitmaps(top_frame, kw) # self.player = player or _("Demo games") self.top.wm_minsize(200, 200) self.button = kw.default # ##createChart = self.create3DBarChart createChart = self.createPieChart ##createChart = self.createSimpleChart ## if parent.winfo_screenwidth() < 800 or parent.winfo_screenheight() < 600: ## createChart = self.createPieChart ## createChart = self.createSimpleChart # self.font = self.app.getFont("default") self.tk_font = tkFont.Font(self.top, self.font) self.font_metrics = self.tk_font.metrics() self._calc_tabs() # won, lost = app.stats.getStats(player, gameid) createChart(app, won, lost, _("Total")) won, lost = app.stats.getSessionStats(player, gameid) createChart(app, won, lost, _("Current session")) # focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout) # # helpers # def _calc_tabs(self): # font = self.tk_font t0 = 160 t = '' for i in (_("Won:"), _("Lost:"), _("Total:")): if len(i) > len(t): t = i t1 = font.measure(t) ## t1 = max(font.measure(_("Won:")), ## font.measure(_("Lost:")), ## font.measure(_("Total:"))) t1 += 10 ##t2 = font.measure('99999')+10 t2 = 45 ##t3 = font.measure('100%')+10 t3 = 45 tx = (t0, t0+t1+t2, t0+t1+t2+t3) # ls = self.font_metrics['linespace'] ls += 5 ls = max(ls, 20) ty = (ls, 2*ls, 3*ls+15, 3*ls+25) # self.tab_x, self.tab_y = tx, ty def _getPwon(self, won, lost): pwon, plost = 0.0, 0.0 if won + lost > 0: pwon = float(won) / (won + lost) pwon = min(max(pwon, 0.00001), 0.99999) plost = 1.0 - pwon return pwon, plost def _createChartInit(self, text): w, h = self.tab_x[-1]+20, self.tab_y[-1]+20 c = Tkinter.Canvas(self.top_frame, width=w, height=h) c.pack(side='top', fill='both', expand=False, padx=20, pady=10) self.canvas = c ##self.fg = c.cget("insertbackground") self.fg = c.option_get('foreground', '') or c.cget("insertbackground") # c.create_rectangle(2, 7, w, h, fill="", outline="#7f7f7f") l = Tkinter.Label(c, text=text, font=self.font, bd=0, padx=3, pady=1) dy = int(self.font_metrics['ascent']) - 10 dy = dy/2 c.create_window(20, -dy, window=l, anchor="nw") def _createChartTexts(self, tx, ty, won, lost): c, tfont, fg = self.canvas, self.font, self.fg pwon, plost = self._getPwon(won, lost) # x = tx[0] dy = int(self.font_metrics['ascent']) - 10 dy = dy/2 c.create_text(x, ty[0]-dy, text=_("Won:"), anchor="nw", font=tfont, fill=fg) c.create_text(x, ty[1]-dy, text=_("Lost:"), anchor="nw", font=tfont, fill=fg) c.create_text(x, ty[2]-dy, text=_("Total:"), anchor="nw", font=tfont, fill=fg) x = tx[1] - 16 c.create_text(x, ty[0]-dy, text="%d" % won, anchor="ne", font=tfont, fill=fg) c.create_text(x, ty[1]-dy, text="%d" % lost, anchor="ne", font=tfont, fill=fg) c.create_text(x, ty[2]-dy, text="%d" % (won + lost), anchor="ne", font=tfont, fill=fg) y = ty[2] - 11 c.create_line(tx[0], y, x, y, fill=fg) if won + lost > 0: x = tx[2] pw = int(round(100.0 * pwon)) c.create_text(x, ty[0]-dy, text="%d%%" % pw, anchor="ne", font=tfont, fill=fg) c.create_text(x, ty[1]-dy, text="%d%%" % (100-pw), anchor="ne", font=tfont, fill=fg) ## def _createChart3DBar(self, canvas, perc, x, y, p, col): ## if perc < 0.005: ## return ## # translate and scale ## p = list(p[:]) ## for i in (0, 1, 2, 3): ## p[i] = (x + p[i][0], y + p[i][1]) ## j = i + 4 ## dx = int(round(p[j][0] * perc)) ## dy = int(round(p[j][1] * perc)) ## p[j] = (p[i][0] + dx, p[i][1] + dy) ## # draw rects ## def draw_rect(a, b, c, d, col, canvas=canvas, p=p): ## points = (p[a][0], p[a][1], p[b][0], p[b][1], ## p[c][0], p[c][1], p[d][0], p[d][1]) ## canvas.create_polygon(points, fill=col) ## draw_rect(0, 1, 5, 4, col[0]) ## draw_rect(1, 2, 6, 5, col[1]) ## draw_rect(4, 5, 6, 7, col[2]) ## # draw lines ## def draw_line(a, b, canvas=canvas, p=p): ## ##print a, b, p[a], p[b] ## canvas.create_line(p[a][0], p[a][1], p[b][0], p[b][1]) ## draw_line(0, 1) ## draw_line(1, 2) ## draw_line(0, 4) ## draw_line(1, 5) ## draw_line(2, 6) ## ###draw_line(3, 7) ## test ## draw_line(4, 5) ## draw_line(5, 6) ## draw_line(6, 7) ## draw_line(7, 4) # # charts # ## def createSimpleChart(self, app, won, lost, text): ## #c, tfont, fg = self._createChartInit(frame, 300, 100, text) ## self._createChartInit(300, 100, text) ## c, tfont, fg = self.canvas, self.font, self.fg ## # ## tx = (90, 180, 210) ## ty = (21, 41, 75) ## self._createChartTexts(tx, ty, won, lost) ## def create3DBarChart(self, app, won, lost, text): ## image = app.gimages.stats[0] ## iw, ih = image.width(), image.height() ## #c, tfont, fg = self._createChartInit(frame, iw+160, ih, text) ## self._createChartInit(iw+160, ih, text) ## c, tfont, fg = self.canvas, self.font, self.fg ## pwon, plost = self._getPwon(won, lost) ## # ## tx = (iw+20, iw+110, iw+140) ## yy = ih/2 ## + 7 ## ty = (yy+21-46, yy+41-46, yy+75-46) ## # ## c.create_image(0, 7, image=image, anchor="nw") ## # ## p = ((0, 0), (44, 6), (62, -9), (20, -14), ## (-3, -118), (-1, -120), (-1, -114), (-4, -112)) ## col = ("#00ff00", "#008200", "#00c300") ## self._createChart3DBar(c, pwon, 102, 145+7, p, col) ## p = ((0, 0), (49, 6), (61, -10), (15, -15), ## (1, -123), (3, -126), (4, -120), (1, -118)) ## col = ("#ff0000", "#860400", "#c70400") ## self._createChart3DBar(c, plost, 216, 159+7, p, col) ## # ## self._createChartTexts(tx, ty, won, lost) ## c.create_text(tx[0], ty[0]-48, text=self.player, anchor="nw", font=tfont, fill=fg) def createPieChart(self, app, won, lost, text): #c, tfont, fg = self._createChartInit(frame, 300, 100, text) # self._createChartInit(text) c, tfont, fg = self.canvas, self.font, self.fg pwon, plost = self._getPwon(won, lost) # #tx = (160, 250, 280) #ty = (21, 41, 75) # tx, ty = self.tab_x, self.tab_y if won + lost > 0: ##s, ewon, elost = 90.0, -360.0 * pwon, -360.0 * plost s, ewon, elost = 0.0, 360.0 * pwon, 360.0 * plost c.create_arc(20, 25+9, 110, 75+9, fill="#007f00", start=s, extent=ewon) c.create_arc(20, 25+9, 110, 75+9, fill="#7f0000", start=s+ewon, extent=elost) c.create_arc(20, 25, 110, 75, fill="#00ff00", start=s, extent=ewon) c.create_arc(20, 25, 110, 75, fill="#ff0000", start=s+ewon, extent=elost) x, y = tx[0] - 25, ty[0] c.create_rectangle(x, y, x+10, y+10, fill="#00ff00") y = ty[1] c.create_rectangle(x, y, x+10, y+10, fill="#ff0000") else: c.create_oval(20, 25+10, 110, 75+10, fill="#7f7f7f") c.create_oval(20, 25, 110, 75, fill="#f0f0f0") c.create_text(65, 50, text=_("No games"), anchor="center", font=tfont, fill="#bfbfbf") # self._createChartTexts(tx, ty, won, lost) # # # def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), (_("&All games..."), 102), (TOP_TITLE+"...", 105), (_("&Reset..."), 302)), default=0, image=self.app.gimages.logos[5], padx=10, pady=10, ) return MfxDialog.initKw(self, kw) # ************************************************************************ # * # ************************************************************************ class CanvasFormatter(PysolStatsFormatter): def __init__(self, app, canvas, parent_window, font, w, h): self.app = app self.canvas = canvas self.parent_window = parent_window ##self.fg = canvas.cget("insertbackground") self.fg = canvas.option_get('foreground', '') or canvas.cget("insertbackground") self.font = font self.w = w self.h = h #self.x = self.y = 0 self.gameid = None self.gamenumber = None self.canvas.config(yscrollincrement=h) self._tabs = None def _addItem(self, id): self.canvas.dialog.nodes[id] = (self.gameid, self.gamenumber) def _calc_tabs(self, arg): tw = 15*self.w ##tw = 160 self._tabs = [tw] font = tkFont.Font(self.canvas, self.font) for t in arg[1:]: tw = font.measure(t)+20 self._tabs.append(tw) self._tabs.append(10) def pstats(self, y, args, gameid=None): x = 1 t1, t2, t3, t4, t5, t6, t7 = args self.gameid = gameid if gameid is None: # header self.gameid = 'header' for var, text, anchor, tab in ( ('name', t1, 'nw', self._tabs[0]+self._tabs[1]), ('played', t2, 'ne', self._tabs[2]), ('won', t3, 'ne', self._tabs[3]), ('lost', t4, 'ne', self._tabs[4]), ('time', t5, 'ne', self._tabs[5]), ('moves', t6, 'ne', self._tabs[6]), ('percent', t7, 'ne', self._tabs[7]), ): self.gamenumber = None if gameid is None: # header self.gamenumber=var id = self.canvas.create_text(x, y, text=text, anchor=anchor, font=self.font, fill=self.fg) self._addItem(id) x += tab self.pstats_perc(x, y, t7) def pstats_perc(self, x, y, t): if not (t and "0" <= t[0] <= "9"): return perc = int(round(float(str(t)))) if perc < 1: return rx, ry, rw, rh = x, y+1, 2 + 8*10, self.h-5 if 1: w = int(round(rw*perc/100.0)) if 1 and w < 1: return if w > 0: w = max(3, w) w = min(rw - 2, w) id = self.canvas.create_rectangle(rx, ry, rx+w, ry+rh, width=1, fill="#00ff00", outline="#000000") if w < rw: id = self.canvas.create_rectangle(rx+w, ry, rx+rw, ry+rh, width=1, fill="#ff0000", outline="#000000") return ##fill = "#ffffff" ##fill = self.canvas["bg"] fill = None id = self.canvas.create_rectangle(rx, ry, rx+rw, ry+rh, width=1, fill=fill, outline="#808080") if 1: rx, rw = rx + 1, rw - 1 ry, rh = ry + 1, rh - 1 w = int(round(rw*perc/100.0)) if w > 0: id = self.canvas.create_rectangle(rx, ry, rx+w, ry+rh, width=0, fill="#00ff00", outline="") if w < rw: id = self.canvas.create_rectangle(rx+w, ry, rx+rw, ry+rh, width=0, fill="#ff0000", outline="") return p = 1.0 ix = rx + 2 for i in (1, 11, 21, 31, 41, 51, 61, 71, 81, 91): if perc < i: break ##c = "#ff8040" r, g, b = 255, 128*p, 64*p c = "#%02x%02x%02x" % (int(r), int(g), int(b)) id = self.canvas.create_rectangle(ix, ry+2, ix+6, ry+rh-2, width=0, fill=c, outline=c) ix = ix + 8 p = max(0.0, p - 0.1) def writeStats(self, player, sort_by='name'): header = self.getStatHeader() y = 0 if self._tabs is None: self._calc_tabs(header) self.pstats(y, header) # y += 2*self.h for result in self.getStatResults(player, sort_by): gameid = result.pop() self.pstats(y, result, gameid) y += self.h # y += self.h total, played, won, lost, time_, moves, perc = self.getStatSummary() s = _("Total (%d out of %d games)") % (played, total) self.pstats(y, (s, won+lost, won, lost, time_, moves, perc)) def writeLog(self, player, prev_games): y = 0 header = self.getLogHeader() t1, t2, t3, t4 = header s = "%-25s %-20s %-17s %s" % header id = self.canvas.create_text(1, y, text=s, anchor="nw", font=self.font, fill=self.fg) self._addItem(id) y += 2*self.h if not player or not prev_games: return 0 for result in self.getLogResults(player, prev_games): s = "%-25s %-20s %-17s %s" % tuple(result[:4]) id = self.canvas.create_text(1, y, text=s, anchor="nw", font=self.font, fill=self.fg) y += self.h return 1 def writeFullLog(self, player): prev_games = self.app.stats.prev_games.get(player) return self.writeLog(player, prev_games) def writeSessionLog(self, player): prev_games = self.app.stats.session_games.get(player) return self.writeLog(player, prev_games) # ************************************************************************ # * # ************************************************************************ class AllGames_StatsDialogScrolledCanvas(MfxScrolledCanvas): pass class AllGames_StatsDialog(MfxDialog): YVIEW = 0 FONT_TYPE = "default" def __init__(self, parent, title, app, player, **kw): lines = 25 #if parent and parent.winfo_screenheight() < 600: # lines = 20 # self.font = app.getFont(self.FONT_TYPE) font = tkFont.Font(parent, self.font) self.font_metrics = font.metrics() self.CHAR_H = self.font_metrics['linespace'] self.CHAR_W = font.measure('M') self.app = app # self.player = player self.title = title self.sort_by = 'name' self.selected_game = None # kwdefault(kw, width=self.CHAR_W*64, height=lines*self.CHAR_H) kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) # self.top.wm_minsize(200, 200) self.button = kw.default # self.sc = AllGames_StatsDialogScrolledCanvas(top_frame, width=kw.width, height=kw.height) self.sc.pack(fill='both', expand=True, padx=kw.padx, pady=kw.pady) # self.nodes = {} self.canvas = self.sc.canvas self.canvas.dialog = self bind(self.canvas, "<1>", self.singleClick) self.fillCanvas(player, title) bbox = self.canvas.bbox("all") ##print bbox ##self.canvas.config(scrollregion=bbox) dx, dy = 4, 0 self.canvas.config(scrollregion=(-dx,-dy,bbox[2]+dx,bbox[3]+dy)) self.canvas.xview_moveto(-dx) self.canvas.yview_moveto(self.YVIEW) # focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout) def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), (_("&Save to file"), 202), (_("&Reset all..."), 301),), default=0, resizable=True, padx=10, pady=10, #width=900, ) return MfxDialog.initKw(self, kw) def destroy(self): self.app = None self.canvas.dialog = None self.nodes = {} self.sc.destroy() MfxDialog.destroy(self) def rearrange(self, sort_by): if self.sort_by == sort_by: return self.sort_by = sort_by self.fillCanvas(self.player, self.title) def singleClick(self, event=None): id = self.canvas.find_withtag('current') if not id: return ##print 'singleClick:', id, self.nodes.get(id[0]) gameid, gamenumber = self.nodes.get(id[0], (None, None)) if gameid == 'header': if self.sort_by == gamenumber: return self.sort_by = gamenumber self.fillCanvas(self.player, self.title) return ## FIXME / TODO return if gameid and gamenumber: print gameid, gamenumber elif gameid: print gameid # # # def fillCanvas(self, player, header): self.canvas.delete('all') self.nodes = {} writer = CanvasFormatter(self.app, self.canvas, self, self.font, self.CHAR_W, self.CHAR_H) writer.writeStats(player, self.sort_by) # ************************************************************************ # * # ************************************************************************ class FullLog_StatsDialog(AllGames_StatsDialog): YVIEW = 1 FONT_TYPE = "fixed" def fillCanvas(self, player, header): writer = CanvasFormatter(self.app, self.canvas, self, self.font, self.CHAR_W, self.CHAR_H) writer.writeFullLog(player) def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), (_("Session &log..."), 104), (_("&Save to file"), 203)), default=0, width=76*self.CHAR_W, ) return AllGames_StatsDialog.initKw(self, kw) class SessionLog_StatsDialog(FullLog_StatsDialog): def fillCanvas(self, player, header): a = PysolStatsFormatter() writer = CanvasFormatter(self.app, self.canvas, self, self.font, self.CHAR_W, self.CHAR_H) writer.writeSessionLog(player) def initKw(self, kw): kw = KwStruct(kw, strings=(_("&OK"), (_("&Full log..."), 103), (_("&Save to file"), 204)), default=0, ) return FullLog_StatsDialog.initKw(self, kw) # ************************************************************************ # * # ************************************************************************ class Status_StatsDialog(MfxMessageDialog): def __init__(self, parent, game): stats, gstats = game.stats, game.gstats w1 = w2 = "" n = 0 for s in game.s.foundations: n = n + len(s.cards) w1 = (_("Highlight piles: ") + str(stats.highlight_piles) + "\n" + _("Highlight cards: ") + str(stats.highlight_cards) + "\n" + _("Highlight same rank: ") + str(stats.highlight_samerank) + "\n") if game.s.talon: if game.gameinfo.redeals != 0: w2 = w2 + _("\nRedeals: ") + str(game.s.talon.round - 1) w2 = w2 + _("\nCards in Talon: ") + str(len(game.s.talon.cards)) if game.s.waste and game.s.waste not in game.s.foundations: w2 = w2 + _("\nCards in Waste: ") + str(len(game.s.waste.cards)) if game.s.foundations: w2 = w2 + _("\nCards in Foundations: ") + str(n) # date = time.strftime("%Y-%m-%d %H:%M", time.localtime(game.gstats.start_time)) MfxMessageDialog.__init__(self, parent, title=_("Game status"), text=game.getTitleName() + "\n" + game.getGameNumber(format=1) + "\n" + _("Playing time: ") + game.getTime() + "\n" + _("Started at: ") + date + "\n\n"+ _("Moves: ") + str(game.moves.index) + "\n" + _("Undo moves: ") + str(stats.undo_moves) + "\n" + _("Bookmark moves: ") + str(gstats.goto_bookmark_moves) + "\n" + _("Demo moves: ") + str(stats.demo_moves) + "\n" + _("Total player moves: ") + str(stats.player_moves) + "\n" + _("Total moves in this game: ") + str(stats.total_moves) + "\n" + _("Hints: ") + str(stats.hints) + "\n" + "\n" + w1 + w2, strings=(_("&OK"), (_("&Statistics..."), 101), (TOP_TITLE+"...", 105), ), image=game.app.gimages.logos[3], image_side="left", image_padx=20, padx=20, ) # ************************************************************************ # * # ************************************************************************ class _TopDialog(MfxDialog): def __init__(self, parent, title, top, **kw): kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) cnf = {'master': top_frame, 'highlightthickness': 1, 'highlightbackground': 'black', } frame = Tkinter.Frame(**cnf) frame.pack(expand=True, fill='both', padx=10, pady=10) frame.columnconfigure(0, weight=1) cnf['master'] = frame cnf['text'] = _('N') l = Tkinter.Label(**cnf) l.grid(row=0, column=0, sticky='ew') cnf['text'] = _('Game number') l = Tkinter.Label(**cnf) l.grid(row=0, column=1, sticky='ew') cnf['text'] = _('Started at') l = Tkinter.Label(**cnf) l.grid(row=0, column=2, sticky='ew') cnf['text'] = _('Result') l = Tkinter.Label(**cnf) l.grid(row=0, column=3, sticky='ew') row = 1 for i in top: # N cnf['text'] = str(row) l = Tkinter.Label(**cnf) l.grid(row=row, column=0, sticky='ew') # Game number cnf['text'] = '#'+str(i.game_number) l = Tkinter.Label(**cnf) l.grid(row=row, column=1, sticky='ew') # Start time t = time.strftime('%Y-%m-%d %H:%M', time.localtime(i.game_start_time)) cnf['text'] = t l = Tkinter.Label(**cnf) l.grid(row=row, column=2, sticky='ew') # Result if isinstance(i.value, float): # time s = format_time(i.value) else: # moves s = str(i.value) cnf['text'] = s l = Tkinter.Label(**cnf) l.grid(row=row, column=3, sticky='ew') row += 1 focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout) def initKw(self, kw): kw = KwStruct(kw, strings=(_('&OK'),), default=0, separator=True) return MfxDialog.initKw(self, kw) class Top_StatsDialog(MfxDialog): def __init__(self, parent, title, app, player, gameid, **kw): self.app = app kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) frame = Tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=10, pady=10) frame.columnconfigure(0, weight=1) if (player in app.stats.games_stats and gameid in app.stats.games_stats[player] and app.stats.games_stats[player][gameid].time_result.top): Tkinter.Label(frame, text=_('Minimum')).grid(row=0, column=1) Tkinter.Label(frame, text=_('Maximum')).grid(row=0, column=2) Tkinter.Label(frame, text=_('Average')).grid(row=0, column=3) ##Tkinter.Label(frame, text=_('Total')).grid(row=0, column=4) s = app.stats.games_stats[player][gameid] row = 1 ll = [ (_('Playing time:'), format_time(s.time_result.min), format_time(s.time_result.max), format_time(s.time_result.average), format_time(s.time_result.total), s.time_result.top, ), (_('Moves:'), s.moves_result.min, s.moves_result.max, round(s.moves_result.average, 2), s.moves_result.total, s.moves_result.top, ), (_('Total moves:'), s.total_moves_result.min, s.total_moves_result.max, round(s.total_moves_result.average, 2), s.total_moves_result.total, s.total_moves_result.top, ), ] ## if s.score_result.min: ## ll.append(('Score:', ## s.score_result.min, ## s.score_result.max, ## round(s.score_result.average, 2), ## s.score_result.top, ## )) ## if s.score_casino_result.min: ## ll.append(('Casino Score:', ## s.score_casino_result.min, ## s.score_casino_result.max, ## round(s.score_casino_result.average, 2), )) for l, min, max, avr, tot, top in ll: Tkinter.Label(frame, text=l).grid(row=row, column=0) Tkinter.Label(frame, text=str(min)).grid(row=row, column=1) Tkinter.Label(frame, text=str(max)).grid(row=row, column=2) Tkinter.Label(frame, text=str(avr)).grid(row=row, column=3) ##Tkinter.Label(frame, text=str(tot)).grid(row=row, column=4) b = Tkinter.Button(frame, text=TOP_TITLE+' ...', width=10, command=lambda top=top: self.showTop(top)) b.grid(row=row, column=5) row += 1 else: Tkinter.Label(frame, text=_('No TOP for this game')).pack() focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout) def showTop(self, top): #print top d = _TopDialog(self.top, TOP_TITLE, top) def initKw(self, kw): kw = KwStruct(kw, strings=(_('&OK'),), default=0, image=self.app.gimages.logos[4], separator=True, ) return MfxDialog.initKw(self, kw) # ************************************************************************ # * # ************************************************************************ class ProgressionDialog(MfxDialog): def __init__(self, parent, title, app, player, gameid, **kw): font_name = app.getFont('default') font = tkFont.Font(parent, font_name) tkfont = tkFont.Font(parent, font) font_metrics = font.metrics() measure = tkfont.measure self.text_height = font_metrics['linespace'] self.text_width = measure('XX.XX.XX') self.items = [] self.formatter = ProgressionFormatter(app, player, gameid) kw = self.initKw(kw) MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) frame = Tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) # constants self.canvas_width, self.canvas_height = 600, 250 if parent.winfo_screenwidth() < 800 or \ parent.winfo_screenheight() < 600: self.canvas_width, self.canvas_height = 400, 200 self.xmargin, self.ymargin = 10, 10 self.graph_dx, self.graph_dy = 10, 10 self.played_color = '#ff7ee9' self.won_color = '#00dc28' self.percent_color = 'blue' # create canvas self.canvas = canvas = Tkinter.Canvas(frame, bg='#dfe8ff', highlightthickness=1, highlightbackground='black', width=self.canvas_width, height=self.canvas_height) canvas.pack(side='left', padx=5) # dir = os.path.join('images', 'stats') try: fn = app.dataloader.findImage('progression', dir) self.bg_image = loadImage(fn) canvas.create_image(0, 0, image=self.bg_image, anchor='nw') except: pass # tw = max(measure(_('Games/day')), measure(_('Games/week')), measure(_('% won'))) self.left_margin = self.xmargin+tw/2 self.right_margin = self.xmargin+tw/2 self.top_margin = 15+self.text_height self.bottom_margin = 15+self.text_height+10+self.text_height # x0, y0 = self.left_margin, self.canvas_height-self.bottom_margin x1, y1 = self.canvas_width-self.right_margin, self.top_margin canvas.create_rectangle(x0, y0, x1, y1, fill='white') # horizontal axis canvas.create_line(x0, y0, x1, y0, width=3) # left vertical axis canvas.create_line(x0, y0, x0, y1, width=3) t = _('Games/day') self.games_text_id = canvas.create_text(x0-4, y1-4, anchor='s', text=t) # right vertical axis canvas.create_line(x1, y0, x1, y1, width=3) canvas.create_text(x1+4, y1-4, anchor='s', text=_('% won')) # caption d = self.text_height x, y = self.xmargin, self.canvas_height-self.ymargin id = canvas.create_rectangle(x, y, x+d, y-d, outline='black', fill=self.played_color) x += d+5 canvas.create_text(x, y, anchor='sw', text=_('Played')) x += measure(_('Played'))+20 id = canvas.create_rectangle(x, y, x+d, y-d, outline='black', fill=self.won_color) x += d+5 canvas.create_text(x, y, anchor='sw', text=_('Won')) x += measure(_('Won'))+20 id = canvas.create_rectangle(x, y, x+d, y-d, outline='black', fill=self.percent_color) x += d+5 canvas.create_text(x, y, anchor='sw', text=_('% won')) # right frame right_frame = Tkinter.Frame(frame) right_frame.pack(side='left', fill='x', padx=5) self.all_games_variable = var = Tkinter.StringVar() var.set('all') b = Tkinter.Radiobutton(right_frame, text=_('All games'), variable=var, value='all', command=self.updateGraph, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) b = Tkinter.Radiobutton(right_frame, text=_('Current game'), variable=var, value='current', command=self.updateGraph, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) label_frame = Tkinter.LabelFrame(right_frame, text=_('Statistics for')) label_frame.pack(side='top', fill='x', pady=10) self.variable = var = Tkinter.StringVar() var.set('week') for v, t in ( ('week', _('Last 7 days')), ('month', _('Last month')), ('year', _('Last year')), ('all', _('All time')), ): b = Tkinter.Radiobutton(label_frame, text=t, variable=var, value=v, command=self.updateGraph, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) label_frame = Tkinter.LabelFrame(right_frame, text=_('Show graphs')) label_frame.pack(side='top', fill='x') self.played_graph_var = Tkinter.BooleanVar() self.played_graph_var.set(True) b = Tkinter.Checkbutton(label_frame, text=_('Played'), command=self.updateGraph, variable=self.played_graph_var, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) self.won_graph_var = Tkinter.BooleanVar() self.won_graph_var.set(True) b = Tkinter.Checkbutton(label_frame, text=_('Won'), command=self.updateGraph, variable=self.won_graph_var, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) self.percent_graph_var = Tkinter.BooleanVar() self.percent_graph_var.set(True) b = Tkinter.Checkbutton(label_frame, text=_('% won'), command=self.updateGraph, variable=self.percent_graph_var, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) self.updateGraph() focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout) def initKw(self, kw): kw = KwStruct(kw, strings=(_('&OK'),), default=0, separator=True) return MfxDialog.initKw(self, kw) def updateGraph(self, *args): interval = self.variable.get() canvas = self.canvas if self.items: canvas.delete(*self.items) self.items = [] all_games = (self.all_games_variable.get() == 'all') result = self.formatter.getResults(interval, all_games) if interval in ('week', 'month'): t = _('Games/day') else: t = _('Games/week') canvas.itemconfig(self.games_text_id, text=t) graph_width = self.canvas_width-self.left_margin-self.right_margin graph_height = self.canvas_height-self.top_margin-self.bottom_margin dx = (graph_width-2*self.graph_dx)/(len(result)-1) graph_dx = (graph_width-(len(result)-1)*dx)/2 dy = (graph_height-self.graph_dy)/5 x0, y0 = self.left_margin, self.canvas_height-self.bottom_margin x1, y1 = self.canvas_width-self.right_margin, self.top_margin td = self.text_height/2 # vertical scale x = x0+graph_dx xx = -100 for res in result: if res[0] is not None and x > xx+self.text_width+4: ##id = canvas.create_line(x, y0, x, y0-5, width=3) ##self.items.append(id) id = canvas.create_line(x, y0, x, y1, stipple='gray50') self.items.append(id) id = canvas.create_text(x, y0+td, anchor='n', text=res[0]) self.items.append(id) xx = x else: id = canvas.create_line(x, y0, x, y0-3, width=1) self.items.append(id) x += dx # horizontal scale max_games = max([i[1] for i in result]) games_delta = max_games/5+1 percent = 0 games = 0 for y in range(y0, y1, -dy): if y != y0: id = canvas.create_line(x0, y, x1, y, stipple='gray50') self.items.append(id) id = canvas.create_text(x0-td, y, anchor='e', text=str(games)) self.items.append(id) id = canvas.create_text(x1+td, y, anchor='w', text=str(percent)) self.items.append(id) games += games_delta percent += 20 # draw result games_resolution = float(dy)/games_delta percent_resolution = float(dy)/20 played_coords = [] won_coords = [] percent_coords = [] x = x0+graph_dx for res in result: played, won = res[1], res[2] y = y0 - int(games_resolution*played) played_coords += [x,y] y = y0 - int(games_resolution*won) won_coords += [x,y] if played > 0: percent = int(100.*won/played) else: percent = 0 y = y0 - int(percent_resolution*percent) percent_coords += [x,y] x += dx if self.played_graph_var.get(): id = canvas.create_line(fill=self.played_color, width=3, *played_coords) self.items.append(id) if self.won_graph_var.get(): id = canvas.create_line(fill=self.won_color, width=3, *won_coords) self.items.append(id) if self.percent_graph_var.get(): id = canvas.create_line(fill=self.percent_color, width=3, *percent_coords) self.items.append(id)
TrevorLowing/PyGames
pysollib/tk/tkstats.py
Python
gpl-2.0
40,892
[ "CASINO" ]
d3c77c77d0d1e468ef81e779e12ad106c149cc53b34850308e26040c8e2557fe
# vim: set expandtab ts=4 sw=4 filetype=python fileencoding=utf8: import logging import textwrap import psycopg2.extras log = logging.getLogger(__name__) fighters_and_moves = dict({ "Liu Kang": [ ("Fire blast", 20), ("Flying kick", 30), ], 'Scorpion': [ ("Harpoon", 30), ("Teleport punch", 30), ], 'Sub Zero': [ ("Ice ball", 10), ("Foot slide", 20), ] }) def create_tables(pgconn): cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" create table fighters ( fighter_id serial primary key, title text not null unique ) """)) cursor.execute(textwrap.dedent(""" create table special_moves ( special_move_id serial primary key, fighter_id integer references fighters (fighter_id), title text not null, unique(fighter_id, title), damage integer not null ) """)) def insert_data(pgconn): global fighters_and_moves cursor = pgconn.cursor() for fighter, special_moves in fighters_and_moves.items(): # I discovered the "returning" keyword a few years ago and it # has vastly simplified a lot of my database code. cursor.execute(textwrap.dedent(""" insert into fighters (title) values (%(fighter)s) returning fighter_id """), { 'fighter': fighter, }) fighter_id = cursor.fetchone().fighter_id log.info("Stored fighter {0} with fighter ID {1}.".format( fighter, fighter_id)) for title, damage in special_moves: cursor.execute(textwrap.dedent(""" insert into special_moves (fighter_id, title, damage) values ( %(fighter_id)s, %(title)s, %(damage)s ) returning special_move_id """), { 'fighter_id': fighter_id, 'title': title, 'damage': damage }) special_move_id = cursor.fetchone().special_move_id log.info( "Stored special move {0} with special move " "ID {1}.".format( title, special_move_id)) def do_ugly_report(pgconn): cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" select f.title, sm.title as move_name, sm.damage from fighters f join special_moves sm on f.fighter_id = sm.fighter_id order by f.title, sm.title """)) print("+" * 60) print("UGLY REPORT") print("+" * 60) print("") print("{0:20} {1:20} {2:20}".format( "Fighter", "Move", "Damage")) print("-"*20 + " " + "-"*20 + " " + "-"*18 + " ") for row in cursor: # the < symbol means "left-justify", which seems to be the # default for strings, but not for integers. print("{0:20} {1:20} {2:<20}".format(*row)) print("") def do_pretty_report_with_array_agg_1(pgconn): """ Use array_agg to roll up the just the titles of the special moves. The titles will come back as a list of strings. """ cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" select f.title, array_agg(sm.title order by sm.title) as special_moves from fighters f join special_moves sm on f.fighter_id = sm.fighter_id group by f.fighter_id order by f.title """)) print("+" * 60) print("PRETTY REPORT 1") print("+" * 60) print("") for row in cursor: print("{0}".format(row.title)) log.debug("In array_agg_1, type(row.special_moves) is {0}".format( type(row.special_moves))) for move in row.special_moves: print(" {0}".format(move)) print("") def do_pretty_report_with_array_agg_2(pgconn): """ Try to use array_agg to roll up more than one columns from the special moves table. But beware! This doesn't work right! Because psycopg2 has no understanding of how to convert the thing made with the row(...) function, it just returns it as a string. """ cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" select f.title, array_agg(row(sm.title, sm.damage) order by sm.title) as special_moves from fighters f join special_moves sm on f.fighter_id = sm.fighter_id group by f.fighter_id order by f.title """)) print("+" * 60) print("PRETTY REPORT 2") print("+" * 60) print("") for row in cursor: print("{0}".format(row.title)) log.debug("In array_agg_2, type(row.special_moves) is {0}".format( type(row.special_moves))) print(" {0}".format(row.special_moves)) print("") def register_type(pgconn): # Tell psycopg2 that when it gets an instance of a special moves # type, it should make a named tuple instance for the special moves # table. psycopg2.extras.register_composite('special_moves', pgconn) def do_pretty_report_with_array_agg_3(pgconn): """ Note this weird syntax in the SQL:: row( sm.special_move_id, sm.fighter_id, sm.title, sm.damage)::special_moves That :: operator casts whatever is on the left to a different type. Every table in postgresql is also a user-defined type. In this case, I'm saying "treat these four values in this row as a special_moves type instance. Here are much simpler / less scary examples:: >>> cursor.execute("select '2014-08-01' as x") >>> type(cursor.fetchone().x) <type 'str'> >>> cursor.execute("select '2014-08-01'::date as x") >>> type(cursor.fetchone().x) <type 'datetime.date'> """ cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" select f.title, array_agg(row( sm.special_move_id, sm.fighter_id, sm.title, sm.damage)::special_moves) as special_moves from fighters f join special_moves sm on f.fighter_id = sm.fighter_id group by f.fighter_id order by f.title """)) print("+" * 60) print("PRETTY REPORT 3") print("+" * 60) print("") for row in cursor: print("{0}".format(row.title)) log.debug("In array_agg_3, type(row.special_moves) is {0}".format( type(row.special_moves))) for sm in row.special_moves: log.debug("type(sm) is {0}.".format(type(sm))) print(" {0:20} {1:<20}".format(sm.title, sm.damage)) print("") class Fighter(object): def __init__(self, fighter_id, title): self.fighter_id = fighter_id self.title = title def __str__(self): return "{0}: {1} (fighter ID: {2})".format( self.__class__.__name__, self.title, self.fighter_id) class FighterFactory(psycopg2.extras.CompositeCaster): def make(self, values): d = dict(zip(self.attnames, values)) return Fighter(**d) class SpecialMove(object): def __init__(self, special_move_id, fighter_id, title, damage): self.special_move_id = special_move_id self.fighter_id = fighter_id self.title = title self.damage = damage def __str__(self): return "{0}: {1} (special move ID: {2})".format( self.__class__.__name__, self.title, self.special_move_id) class SpecialMoveFactory(psycopg2.extras.CompositeCaster): def make(self, values): d = dict(zip(self.attnames, values)) return SpecialMove(**d) def register_home_made_types(pgconn): # Register our own home-made FighterFactory to instantiate instances # of our own Fighter class. psycopg2.extras.register_composite( 'fighters', pgconn, factory=FighterFactory) # Same thing, but different tables. psycopg2.extras.register_composite( 'special_moves', pgconn, factory=SpecialMoveFactory) def cast_to_our_own_classes(pgconn): """ In this one, I use this syntax:: (f.*)::fighters instead of something like:: row(f.fighter_id, f.title)::fighters They do the exact same thing. """ cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" select (f.*)::fighters as fighter from fighters f order by f.title """)) log.debug("cast to our own Fighter class") for row in cursor: log.debug(row.fighter) def do_pretty_report_with_array_agg_4(pgconn): """ Get a single row back for each fighter, with two columns in each row. The first column should hold an instance of our homemade Fighter class. The second column should hold an array of instances of our customized SpecialMove class. """ cursor = pgconn.cursor() cursor.execute(textwrap.dedent(""" select (f.*)::fighters as fighter, array_agg((sm.*)::special_moves order by sm.title) as special_moves from fighters f join special_moves sm on f.fighter_id = sm.fighter_id group by f.fighter_id order by f.title """)) print("+" * 60) print("PRETTY REPORT 4") print("+" * 60) print("") for row in cursor: log.debug("type(row.fighter): {0}".format(type(row.fighter))) # This uses the Fighter.__str__ method print(row.fighter) log.debug("type(row.special_moves): {0}".format(type(row.special_moves))) for sm in row.special_moves: log.debug("type(sm): {0}".format(type(sm))) print(sm)
216software/psycopg2-special-moves
ericlib.py
Python
bsd-2-clause
10,053
[ "BLAST" ]
d8950c0cd5bc57b639d9fae4d51b937d7a365f672049b68d88615e0badd9c018
# -c print "BEGIN-LOG" import pymol import cmd # need to do this for all supported file types because the load routines diverge... def x(st): print st cmd.set("raise_exceptions",0) valu = eval(st) print valu if cmd.is_error(valu): cmd.set("raise_exceptions",1) try: print eval(st) except pymol.CmdException: print "CmdException raised." except cmd.QuietException: print "QuietException raised." map(x,[ 'cmd.load("dat/pept.pdb")' , 'cmd.load("dat/nonexistent.pdb")' , 'cmd.load("dat/small01.mol")' , 'cmd.load("dat/nonexistent.mol")' , 'cmd.load("dat/ligs3d.sdf")' , 'cmd.load("dat/nonexistent.sdf")', 'cmd.load("dat/small03.mol2")' , 'cmd.load("dat/nonexistent.mol2")' , 'cmd.load("dat/pept.r3d")' , 'cmd.load("dat/nonexistent.r3d")' , 'cmd.load("dat/pept.pkl")' , 'cmd.load("dat/nonexistent.pkl")' , 'cmd.get_names()' , 'cmd.delete("all")' , 'cmd.get_names()' , 'cmd.get_model("nonexistent")' , 'cmd.space("cmyk")', 'cmd.space("unknown")', 'cmd.space("rgb")', 'cmd.space()', ]) cmd.delete("all") cmd.load("dat/pept.pdb") mdl = cmd.get_model("pept") print mdl.__class__ print len(mdl.atom) mdl = cmd.get_model("none") print mdl.__class__ print len(mdl.atom) map( x, [ 'cmd.get_model("nonexistent")', 'cmd.create("test","none",quiet=0)', 'cmd.create("test2","nonexistent")', 'cmd.create("test3","?allowed",quiet=0)', 'cmd.fragment("arg")', 'cmd.fragment("nonexistent")', ]) cmd.delete("all") cmd.load("dat/pept.pdb") map( x, [ 'cmd.distance("none","none","none")', 'cmd.distance("none","invalid1","none")', 'cmd.distance("none","none","invalid2")', 'cmd.distance("none","invalid1","invalid2")', 'cmd.index("none")', 'cmd.index("first pept")', 'cmd.index("invalid")', 'cmd.identify("none")', 'cmd.identify("first pept")', 'cmd.identify("invalid")', 'cmd.identify("none",mode=1)', 'cmd.identify("first pept",mode=1)', 'cmd.identify("invalid",mode=1)', 'cmd.count_atoms("none")', 'cmd.count_atoms()', 'cmd.count_atoms("pept")', 'cmd.count_atoms("invalid")', 'cmd.count_frames()', 'cmd.count_states()', 'cmd.count_states("all")', 'cmd.count_states("none")', 'cmd.count_states("invalid")', 'cmd.get_area()', 'cmd.get_area("resi 1")', 'cmd.get_area("none")', 'cmd.get_area("invalid")', 'cmd.get_chains()', 'cmd.get_chains("pept")', 'cmd.get_chains("resi 1")', 'cmd.get_chains("none")', 'cmd.get_chains("invalid")', 'cmd.zoom()', 'cmd.zoom("pept")', 'cmd.zoom("none")', 'cmd.zoom("invalid")', 'cmd.center()', 'cmd.center("pept")', 'cmd.center("none")', 'cmd.center("invalid")', ]) print "END-LOG" TODO=""" #-------------------------------------------------------------------- from querying import \ angle, \ dist, \ dihedral, \ distance, \ export_dots, \ find_pairs, \ get_angle, \ get_area, \ get_chains, \ get_color_index, \ get_color_indices, \ get_object_color_index, \ get_object_list, \ get_color_tuple, \ get_atom_coords, \ get_dihedral, \ get_distance, \ get_extent, \ get_movie_locked, \ get_names_of_type, \ get_object_matrix, \ get_phipsi, \ get_position, \ get_povray, \ get_renderer, \ get_symmetry, \ get_title, \ get_type, \ id_atom, \ overlap, \ phi_psi #-------------------------------------------------------------------- from selecting import \ deselect, \ indicate, \ select, \ select_list, \ pop #-------------------------------------------------------------------- from exporting import \ png, \ export_coords, \ get_pdbstr, \ get_session, \ multisave, \ save #-------------------------------------------------------------------- import editing from editing import \ alter, \ alter_list, \ alter_state, \ attach, \ bond, \ cycle_valence, \ deprotect, \ dss, \ edit, \ fix_chemistry, \ flag, \ fuse, \ h_add, \ h_fill, \ invert, \ iterate, \ iterate_state, \ map_set_border, \ map_double, \ matrix_transfer, \ matrix_reset, \ protect, \ push_undo, \ redo, \ remove, \ remove_picked, \ rename, \ replace, \ rotate, \ sculpt_purge, \ sculpt_deactivate, \ sculpt_activate, \ sculpt_iterate, \ set_dihedral, \ set_name, \ set_geometry, \ set_object_ttt, \ set_symmetry, \ set_title, \ smooth, \ sort, \ split_states, \ torsion, \ transform_object, \ transform_selection,\ translate, \ translate_atom, \ unbond, \ undo, \ unpick, \ update #-------------------------------------------------------------------- from externing import \ cd, \ ls, \ paste, \ pwd, \ system #-------------------------------------------------------------------- from wizarding import \ get_wizard, \ get_wizard_stack, \ refresh_wizard, \ replace_wizard, \ set_wizard, \ set_wizard_stack, \ dirty_wizard, \ wizard #-------------------------------------------------------------------- from fitting import \ align, \ fit, \ rms, \ rms_cur, \ intra_fit, \ intra_rms, \ intra_rms_cur, \ pair_fit #-------------------------------------------------------------------- from preset import \ simple, \ technical, \ pretty, \ publication #-------------------------------------------------------------------- import moving from moving import \ madd, \ mset, \ mclear, \ mdo, \ mappend, \ mmatrix, \ mdump, \ accept, \ decline, \ mpng, \ mview, \ forward, \ backward, \ rewind, \ middle, \ ending, \ mplay, \ mtoggle, \ mstop, \ mpng, \ mray, \ frame, \ get_movie_playing, \ get_state, \ get_frame #-------------------------------------------------------------------- import viewing from viewing import \ as, \ bg_color, \ bg_colour, \ cartoon, \ clip, \ color, \ colour, \ del_colorection, \ dirty, \ disable, \ enable, \ full_screen, \ get_colorection, \ get_view, \ get_vis, \ get_scene_dict, \ hide, \ label, \ load_png, \ meter_reset, \ move, \ orient, \ origin, \ center, \ ray, \ rebuild, \ recolor, \ recolour, \ refresh, \ reset, \ rock, \ scene, \ set_color, \ set_colour, \ set_colorection, \ set_colorection_name,\ set_vis, \ set_view, \ show, \ spectrum, \ stereo, \ toggle, \ turn, \ view, \ viewport, \ window, \ zoom #-------------------------------------------------------------------- import setting from setting import \ set, \ get, \ unset, \ get_setting_legacy, \ get_setting_tuple, \ get_setting_updates, \ get_setting_text #-------------------------------------------------------------------- import helping from helping import \ show_help, \ help, \ commands #-------------------------------------------------------------------- from experimenting import \ check, \ dump, \ expfit, \ get_bond_print, \ fast_minimize, \ import_coords, \ load_coords, \ mem, \ minimize, \ spheroid, \ test from importing import \ finish_object, \ load_brick, \ load_callback, \ load_cgo, \ load_embedded, \ load_map, \ load_model, \ load_object, \ load_traj, \ loadable, \ read_mmodstr, \ read_molstr, \ read_pdbstr, \ read_xplorstr, \ set_session, \ #-------------------------------------------------------------------- import creating from creating import \ copy, \ isodot, \ isolevel, \ isomesh, \ isosurface, \ slice_new, \ symexp, \ map_new, \ ramp_new #-------------------------------------------------------------------- from commanding import \ cls, \ do, \ log, \ log_close, \ log_open, \ quit, \ resume, \ splash, \ reinitialize, \ sync #-------------------------------------------------------------------- import controlling from controlling import \ button, \ config_mouse, \ mouse, \ mask, \ order, \ set_key, \ unmask, \ edit_mode """
gratefulfrog/lib
python/pymol/pymol_path/test/inp/C2000returns.py
Python
gpl-2.0
12,632
[ "PyMOL" ]
0129cae12b90b96ad0989a4723f54890f7bab1725372e57412dcd5f3e32e2c63
"""Classes for use with the XYZ format Provides a Xyz class with reading and writing functions """ import copy as cp from ase.atoms import Atoms class Xyz(object): """Stores data of an xyz file. """ def __init__(self, filename=None, comment=None, frames=None): """Standard constructor, all parameters default to None.""" self.filename = filename self.comment = comment self.frames = frames @classmethod def from_xyz(cls, xyz): """Creates Xyz from Xyz object using deep copy""" tmp = cp.deepcopy(xyz) return tmp @classmethod def from_file(cls, fname, index=None): """Creates Xyz from .xyz file""" tmp = Xyz() tmp.read(fname, index) return tmp def read(self, fileobj, index=None): """Reads a trajectory from an xyz file. This function returns a list of ase.atoms.Atoms objects. The original ase.io.xyz.read_xyz function was only capable of returning a single Atoms object. """ if isinstance(fileobj, str): fileobj = open(fileobj) lines = fileobj.readlines() L1 = lines[0].split() if len(L1) == 1: del lines[:2] natoms = int(L1[0]) else: natoms = len(lines) frames = [] while len(lines) >= natoms: positions = [] symbols = [] for line in lines[:natoms]: symbol, x, y, z = line.split()[:4] symbol = symbol.lower().capitalize() symbols.append(symbol) positions.append([float(x), float(y), float(z)]) frames.append(Atoms(symbols=symbols, positions=positions)) del lines[:natoms + 2] if index is None: self.frames = frames else: self.frames = [frames[index]] @classmethod def read_atoms(cls, fileobj, index=None): """Reads a trajectory from an xyz file. Does not return an xyz instance but simply the list of atoms. """ tmp = Xyz.from_file(fileobj, index) if len(tmp.frames) == 1: return tmp.frames[0] else: return tmp.frames def string(self): """Construct and return string for .xyz file""" s = '' s += ' {n}\n'.format(n=len(self.frames)) s += self.comment + '\n' for atom in self.frames: s += '{s:4} {x:<16.10} {y:<16.10} {z:<16.10}\n' \ .format(s=atom.s, x=atom.x, y=atom.y, z=atom.z) return s def write(fname=None): """Write content of object to .xyz file""" if fname is not None: self.fname = fname f=open(self.fname, 'w') f.write(self.string()) f.close()
cpignedoli/asetk
asetk/format/xyz.py
Python
mit
2,839
[ "ASE" ]
c97c5d9e7823345aaab49c03142dcc4c6a27ff301233fbcba2f3c54f028ed605
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import logging from uuid import uuid4 from datetime import datetime, timedelta from ujson import dumps from colorama import Fore, Style from octopus import TornadoOctopus from octopus.limiter.redis.per_domain import Limiter from retools.lock import Lock, LockTimeout from sqlalchemy.orm import scoped_session from holmes import __version__ from holmes.reviewer import Reviewer from holmes.utils import load_classes, count_url_levels, get_domain_from_url from holmes.models import Request, Key, DomainsViolationsPrefs from holmes.cli import BaseCLI class BaseWorker(BaseCLI): def _load_validators(self): return load_classes(default=self.config.VALIDATORS) def _load_facters(self): return load_classes(default=self.config.FACTERS) def get_otto_limiter(self): domains = self.cache.get_domain_limiters() limiter = None if domains: limiter = Limiter( *domains, redis=self.redis, expiration_in_seconds=self.config.LIMITER_LOCKS_EXPIRATION ) limiter.subscribe_to_lock_miss(self.handle_limiter_miss) return limiter def update_otto_limiter(self): domains = self.cache.get_domain_limiters() if hasattr(self.otto, 'limiter') and self.otto.limiter is not None: self.otto.limiter.update_domain_definitions(*domains) def start_otto(self): self.info('Starting Octopus with %d concurrent threads.' % self.options.concurrency) self.otto = TornadoOctopus( concurrency=self.options.concurrency, cache=self.options.cache, connect_timeout_in_seconds=self.config.CONNECT_TIMEOUT_IN_SECONDS, request_timeout_in_seconds=self.config.REQUEST_TIMEOUT_IN_SECONDS, limiter=self.get_otto_limiter() ) self.otto.start() def handle_error(self, exc_type, exc_value, tb): try: if not self.db.connection().invalidated: self.db.rollback() except Exception: err = sys.exc_info()[1] logging.error("Cannot rollback: %s" % str(err)) self.otto.url_queue = [] self.db.close_all() self.db.remove() self.db = scoped_session(self.sqlalchemy_db_maker) for handler in self.error_handlers: handler.handle_exception( exc_type, exc_value, tb, extra={ 'worker-uuid': self.uuid, 'holmes-version': __version__ } ) def async_get(self, url, handler, method='GET', **kw): url, response = self.cache.get_request(url) kw['user_agent'] = self.config.HOLMES_USER_AGENT if not response: kw['proxy_host'] = self.config.HTTP_PROXY_HOST kw['proxy_port'] = self.config.HTTP_PROXY_PORT self.debug('Enqueueing %s for %s...' % (method, url)) self.otto.enqueue(url, self.handle_response(url, handler), method, **kw) else: handler(url, response) def handle_response(self, url, handler): def handle(url, response): self.cache.set_request( url, response.status_code, response.headers, response.cookies, response.text, response.effective_url, response.error, response.request_time, self.config.REQUEST_CACHE_EXPIRATION_IN_SECONDS ) handler(url, response) return handle def handle_limiter_miss(self, url): pass def publish(self, data): self.redis_pub_sub.publish('events', data) class HolmesWorker(BaseWorker): def initialize(self): self.uuid = uuid4().hex self.working_url = None self.domain_name = None self.last_ping = None authnz_wrapper_class = self.load_authnz_wrapper() if authnz_wrapper_class: self.authnz_wrapper = authnz_wrapper_class(self.config) else: self.authnz_wrapper = None self.facters = self._load_facters() self.validators = self._load_validators() self.error_handlers = [handler(self.config) for handler in self.load_error_handlers()] self.connect_sqlalchemy() self.search_provider = self.load_search_provider()( config=self.config, db=self.db, authnz_wrapper=self.authnz_wrapper ) self.connect_to_redis() self.start_otto() self.fact_definitions = {} self.violation_definitions = {} self.default_violations_values = {} for facter in self.facters: self.fact_definitions.update(facter.get_fact_definitions()) Key.insert_keys(self.db, self.fact_definitions) for validator in self.validators: self.violation_definitions.update(validator.get_violation_definitions()) self.default_violations_values.update( validator.get_default_violations_values(self.config) ) Key.insert_keys( self.db, self.violation_definitions, self.default_violations_values ) self.configure_material_girl() DomainsViolationsPrefs.insert_default_violations_values_for_all_domains( self.db, self.default_violations_values, self.violation_definitions, self.cache ) self.load_all_domains_violations_prefs() def load_all_domains_violations_prefs(self): from holmes.models import Domain for domain in Domain.get_all_domains(self.db): self.cache.get_domain_violations_prefs(domain.name) def config_parser(self, parser): parser.add_argument( '--concurrency', '-t', type=int, default=10, help='Number of threads (or async http requests) to use for Octopus (doing GETs concurrently)' ) parser.add_argument( '--cache', default=False, action='store_true', help='Whether http requests should be cached by Octopus.' ) def get_description(self): uuid = str(getattr(self, 'uuid', '')) return "%s%sholmes-worker-%s%s" % ( Fore.BLUE, Style.BRIGHT, uuid, Style.RESET_ALL, ) def do_work(self): self.debug('Started doing work...') self.update_otto_limiter() job = self._load_next_job() if job is None: self.info('No jobs could be found! Returning...') self._ping_api() return if not self._start_job(job): self.info('Could not start job for url "%s". Maybe other worker doing it?' % job['url']) lock = job.get('lock', None) self._release_lock(lock) return self.info('Starting new job for %s...' % job['url']) self._start_reviewer(job=job) lock = job.get('lock', None) self._complete_job(lock) self.db.commit() def _start_reviewer(self, job): if job: if count_url_levels(job['url']) > self.config.MAX_URL_LEVELS: self.info('Max URL levels! Details: %s' % job['url']) return self.debug('Starting Review for [%s]' % job['url']) reviewer = Reviewer( api_url=self.config.HOLMES_API_URL, page_uuid=job['page'], page_url=job['url'], page_score=0, config=self.config, validators=self.validators, facters=self.facters, search_provider=self.search_provider, async_get=self.async_get, wait=self.otto.wait, wait_timeout=0, # max time to wait for all requests to finish db=self.db, cache=self.cache, publish=self.publish, girl=self.girl, fact_definitions=self.fact_definitions, violation_definitions=self.violation_definitions ) reviewer.review() def _ping_api(self): self.debug('Pinging that this worker is still alive...') self.last_ping = datetime.utcnow() self.publish(dumps({ 'type': 'worker-status', 'workerId': str(self.uuid), 'dt': self.last_ping, 'url': self.working_url, 'domainName': self.domain_name, })) def handle_limiter_miss(self, url): self.working_url = url if self.last_ping < datetime.utcnow() - timedelta(seconds=1): self._ping_api() def _load_next_job(self): return self.cache.get_next_job(self.config.REVIEW_EXPIRATION_IN_SECONDS, self.config.WORKERS_LOOK_AHEAD_PAGES) def _start_job(self, job): try: lock = Lock(job['url'], redis=self.redis, timeout=1) lock.acquire() self.working_url = job['url'] if self.working_url: self.domain_name, domain_url = get_domain_from_url(self.working_url) self._ping_api() job['lock'] = lock return True except LockTimeout: job['lock'] = None return False def _complete_job(self, lock): self.working_url = None self.domain_name = None self._ping_api() self._release_lock(lock) Request.delete_old_requests(self.db, self.config) def _release_lock(self, lock): if lock is not None: lock.release() def main(): worker = HolmesWorker(sys.argv[1:]) worker.run() if __name__ == '__main__': main()
holmes-app/holmes-api
holmes/worker.py
Python
mit
9,785
[ "Octopus" ]
373fca7a8b272d3a5e9cb5c846bd71ead3c6c3963546b30c10bcf02ae90a0f62
#!/usr/bin/env python2 # vim:fileencoding=utf-8 # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import (unicode_literals, division, absolute_import, print_function) from collections import OrderedDict from functools import partial from PyQt5.Qt import ( QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QListWidget, QIcon, QSize, QComboBox, QLineEdit, QListWidgetItem, QStyledItemDelegate, QStaticText, Qt, QStyle, QToolButton, QInputDialog, QMenu ) from calibre.ebooks.metadata.tag_mapper import map_tags, compile_pat from calibre.gui2 import error_dialog, elided_text, Application, question_dialog from calibre.gui2.widgets2 import Dialog from calibre.utils.config import JSONConfig tag_maps = JSONConfig('tag-map-rules') class RuleEdit(QWidget): ACTION_MAP = OrderedDict(( ('remove', _('Remove')), ('replace', _('Replace')), ('keep', _('Keep')), ('capitalize', _('Capitalize')), ('lower', _('Lower-case')), ('upper', _('Upper-case')), )) MATCH_TYPE_MAP = OrderedDict(( ('one_of', _('is one of')), ('not_one_of', _('is not one of')), ('matches', _('matches pattern')), ('not_matches', _('does not match pattern')) )) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.h = h = QHBoxLayout() self.la = la = QLabel(_( 'Create the rule below, the rule can be used to remove or replace tags')) la.setWordWrap(True) l.addWidget(la) l.addLayout(h) self.action = a = QComboBox(self) h.addWidget(a) for action, text in self.ACTION_MAP.iteritems(): a.addItem(text, action) a.currentIndexChanged.connect(self.update_state) self.la1 = la = QLabel('\xa0' + _('the tag, if it') + '\xa0') h.addWidget(la) self.match_type = q = QComboBox(self) h.addWidget(q) for action, text in self.MATCH_TYPE_MAP.iteritems(): q.addItem(text, action) q.currentIndexChanged.connect(self.update_state) self.la2 = la = QLabel(':\xa0') h.addWidget(la) self.query = q = QLineEdit(self) h.addWidget(q) self.h2 = h = QHBoxLayout() l.addLayout(h) self.la3 = la = QLabel(_('with the tag:') + '\xa0') h.addWidget(la) self.replace = r = QLineEdit(self) h.addWidget(r) l.addStretch(10) self.update_state() def sizeHint(self): a = QWidget.sizeHint(self) a.setHeight(a.height() + 75) a.setWidth(a.width() + 100) return a def update_state(self): replace = self.action.currentData() == 'replace' self.la3.setVisible(replace), self.replace.setVisible(replace) tt = _('A comma separated list of tags') if 'matches' in self.match_type.currentData(): tt = _('A regular expression') self.query.setToolTip(tt) @property def rule(self): return { 'action': self.action.currentData(), 'match_type': self.match_type.currentData(), 'query': self.query.text().strip(), 'replace': self.replace.text().strip(), } @rule.setter def rule(self, rule): def sc(name): c = getattr(self, name) idx = c.findData(unicode(rule.get(name, ''))) if idx < 0: idx = 0 c.setCurrentIndex(idx) sc('action'), sc('match_type') self.query.setText(unicode(rule.get('query', '')).strip()) self.replace.setText(unicode(rule.get('replace', '')).strip()) def validate(self): rule = self.rule if not rule['query']: error_dialog(self, _('Query required'), _( 'You must provide a value for the tag to match'), show=True) return False if 'matches' in rule['match_type']: try: compile_pat(rule['query']) except Exception: error_dialog(self, _('Query invalid'), _( '%s is not a valid regular expression') % rule['query'], show=True) return False return True class RuleEditDialog(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Edit rule'), 'edit-tag-mapper-rule', parent=None) def setup_ui(self): self.l = l = QVBoxLayout(self) self.edit_widget = w = RuleEdit(self) l.addWidget(w) l.addWidget(self.bb) def accept(self): if self.edit_widget.validate(): Dialog.accept(self) DATA_ROLE = Qt.UserRole RENDER_ROLE = DATA_ROLE + 1 class RuleItem(QListWidgetItem): @staticmethod def text_from_rule(rule, parent): query = elided_text(rule['query'], font=parent.font(), width=200, pos='right') text = _( '<b>{action}</b> the tag, if it <i>{match_type}</i>: <b>{query}</b>').format( action=RuleEdit.ACTION_MAP[rule['action']], match_type=RuleEdit.MATCH_TYPE_MAP[rule['match_type']], query=query) if rule['action'] == 'replace': text += '<br>' + _('with the tag:') + ' <b>%s</b>' % rule['replace'] return text def __init__(self, rule, parent): QListWidgetItem.__init__(self, '', parent) st = self.text_from_rule(rule, parent) self.setData(RENDER_ROLE, st) self.setData(DATA_ROLE, rule) class Delegate(QStyledItemDelegate): MARGIN = 16 def sizeHint(self, option, index): st = QStaticText(index.data(RENDER_ROLE)) st.prepare(font=self.parent().font()) width = max(option.rect.width(), self.parent().width() - 50) if width and width != st.textWidth(): st.setTextWidth(width) br = st.size() return QSize(br.width(), br.height() + self.MARGIN) def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) pal = option.palette color = pal.color(pal.HighlightedText if option.state & QStyle.State_Selected else pal.Text).name() text = '<div style="color:%s">%s</div>' % (color, index.data(RENDER_ROLE)) st = QStaticText(text) st.setTextWidth(option.rect.width()) painter.drawStaticText(option.rect.left() + self.MARGIN // 2, option.rect.top() + self.MARGIN // 2, st) class Rules(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.msg_label = la = QLabel( '<p>' + _('You can specify rules to filter/transform tags here. Click the "Add Rule" button' ' below to get started. The rules will be processed in order for every tag until either a' ' "remove" or a "keep" rule matches.') + '<p>' + _( 'You can <b>change an existing rule</b> by double clicking it') ) la.setWordWrap(True) l.addWidget(la) self.h = h = QHBoxLayout() l.addLayout(h) self.add_button = b = QPushButton(QIcon(I('plus.png')), _('&Add rule'), self) b.clicked.connect(self.add_rule) h.addWidget(b) self.remove_button = b = QPushButton(QIcon(I('minus.png')), _('&Remove rule(s)'), self) b.clicked.connect(self.remove_rules) h.addWidget(b) self.h3 = h = QHBoxLayout() l.addLayout(h) self.rule_list = r = QListWidget(self) self.delegate = Delegate(self) r.setSelectionMode(r.ExtendedSelection) r.setItemDelegate(self.delegate) r.doubleClicked.connect(self.edit_rule) h.addWidget(r) r.setDragEnabled(True) r.viewport().setAcceptDrops(True) r.setDropIndicatorShown(True) r.setDragDropMode(r.InternalMove) r.setDefaultDropAction(Qt.MoveAction) self.l2 = l = QVBoxLayout() h.addLayout(l) self.up_button = b = QToolButton(self) b.setIcon(QIcon(I('arrow-up.png'))), b.setToolTip(_('Move current rule up')) b.clicked.connect(self.move_up) l.addWidget(b) self.down_button = b = QToolButton(self) b.setIcon(QIcon(I('arrow-down.png'))), b.setToolTip(_('Move current rule down')) b.clicked.connect(self.move_down) l.addStretch(10), l.addWidget(b) def sizeHint(self): return QSize(800, 600) def add_rule(self): d = RuleEditDialog(self) if d.exec_() == d.Accepted: i = RuleItem(d.edit_widget.rule, self.rule_list) self.rule_list.scrollToItem(i) def edit_rule(self): i = self.rule_list.currentItem() if i is not None: d = RuleEditDialog(self) d.edit_widget.rule = i.data(Qt.UserRole) if d.exec_() == d.Accepted: rule = d.edit_widget.rule i.setData(DATA_ROLE, rule) i.setData(RENDER_ROLE, RuleItem.text_from_rule(rule, self.rule_list)) def remove_rules(self): for item in self.rule_list.selectedItems(): self.rule_list.takeItem(self.rule_list.row(item)) def move_up(self): i = self.rule_list.currentItem() if i is not None: row = self.rule_list.row(i) if row > 0: self.rule_list.takeItem(row) self.rule_list.insertItem(row - 1, i) self.rule_list.setCurrentItem(i) def move_down(self): i = self.rule_list.currentItem() if i is not None: row = self.rule_list.row(i) if row < self.rule_list.count() - 1: self.rule_list.takeItem(row) self.rule_list.insertItem(row + 1, i) self.rule_list.setCurrentItem(i) @property def rules(self): ans = [] for r in xrange(self.rule_list.count()): ans.append(self.rule_list.item(r).data(DATA_ROLE)) return ans @rules.setter def rules(self, rules): self.rule_list.clear() for rule in rules: if 'action' in rule and 'match_type' in rule and 'query' in rule: RuleItem(rule, self.rule_list) class Tester(Dialog): def __init__(self, rules, parent=None): self.rules = rules Dialog.__init__(self, _('Test tag mapper rules'), 'test-tag-mapper-rules', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.bb.setStandardButtons(self.bb.Close) self.la = la = QLabel(_( 'Enter a comma separated list of &tags to test:')) l.addWidget(la) self.tags = t = QLineEdit(self) la.setBuddy(t) t.setPlaceholderText(_('Enter tags and click the Test button')) self.h = h = QHBoxLayout() l.addLayout(h) h.addWidget(t) self.test_button = b = QPushButton(_('&Test'), self) b.clicked.connect(self.do_test) h.addWidget(b) self.result = la = QLabel(self) la.setWordWrap(True) la.setText('<p>&nbsp;<br>&nbsp;</p>') l.addWidget(la) l.addWidget(self.bb) def do_test(self): tags = [x.strip() for x in self.tags.text().split(',')] tags = map_tags(tags, self.rules) self.result.setText(_('<b>Resulting tags:</b> %s') % ', '.join(tags)) class RulesDialog(Dialog): def __init__(self, parent=None): self.loaded_ruleset = None Dialog.__init__(self, _('Edit tag mapper rules'), 'edit-tag-mapper-rules', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.edit_widget = w = Rules(self) l.addWidget(w) l.addWidget(self.bb) self.save_button = b = self.bb.addButton(_('&Save'), self.bb.ActionRole) b.setToolTip(_('Save this ruleset for later re-use')) b.clicked.connect(self.save_ruleset) self.load_button = b = self.bb.addButton(_('&Load'), self.bb.ActionRole) b.setToolTip(_('Load a previously saved ruleset')) self.load_menu = QMenu(self) b.setMenu(self.load_menu) self.build_load_menu() self.test_button = b = self.bb.addButton(_('&Test rules'), self.bb.ActionRole) b.clicked.connect(self.test_rules) @property def rules(self): return self.edit_widget.rules @rules.setter def rules(self, rules): self.edit_widget.rules = rules def save_ruleset(self): if not self.rules: error_dialog(self, _('No rules'), _( 'Cannot save as no rules have been created'), show=True) return text, ok = QInputDialog.getText(self, _('Save ruleset as'), _( 'Enter a name for this ruleset:'), text=self.loaded_ruleset or '') if ok and text: if self.loaded_ruleset and text == self.loaded_ruleset: if not question_dialog(self, _('Are you sure?'), _( 'A ruleset with the name "%s" already exists, do you want to replace it?') % text): return self.loaded_ruleset = text rules = self.rules if rules: tag_maps[text] = self.rules elif text in tag_maps: del tag_maps[text] self.build_load_menu() def build_load_menu(self): self.load_menu.clear() if len(tag_maps): for name, rules in tag_maps.iteritems(): self.load_menu.addAction(name).triggered.connect(partial(self.load_ruleset, name)) self.load_menu.addSeparator() m = self.load_menu.addMenu(_('Delete saved rulesets')) for name, rules in tag_maps.iteritems(): m.addAction(name).triggered.connect(partial(self.delete_ruleset, name)) else: self.load_menu.addAction(_('No saved rulesets available')) def load_ruleset(self, name): self.rules = tag_maps[name] self.loaded_ruleset = name def delete_ruleset(self, name): del tag_maps[name] self.build_load_menu() def test_rules(self): Tester(self.rules, self).exec_() if __name__ == '__main__': app = Application([]) d = RulesDialog() d.rules = [ {'action':'remove', 'query':'moose', 'match_type':'one_of', 'replace':''}, {'action':'replace', 'query':'moose', 'match_type':'one_of', 'replace':'xxxx'}, ] d.exec_() from pprint import pprint pprint(d.rules) del d, app
hazrpg/calibre
src/calibre/gui2/tag_mapper.py
Python
gpl-3.0
14,651
[ "MOOSE" ]
7ff9a1cf23a4c839eba388a823885a0f08470685401dbb3a1f4c268fb8e1cf1a
""" ******************************************************* * * psyFunction - GENERATE GENERAL FORMULATION OF PSYCHOMETRIC FUNCTION * * License: Apache 2.0 * Written by: Michael Slugocki * Created on: April 18, 2018 * Last updated: August 30, 2018 * ******************************************************* """ ################################################################# # IMPORT MODULES ################################################################# import numpy as np from scipy.special import erf ################################################################# # DEFINE PSYCHOMETRIC FUNCTIONS ################################################################# # Cumulative Gaussian def _norm(x, xShift, sd): return ((erf((x-xShift)/(np.sqrt(2)*sd))+1)*0.5) # Logistic def _logistic(x, alpha, beta): return 1 / (1 + np.exp(-beta*(x - alpha))) # Weibull def _weibull(x, alpha, beta): return 1 - np.exp(-(x/alpha)**beta) # Gumbel def _gumbel(x, alpha, beta): return 1 - np.exp(-10**(beta*(x-alpha))) # Quick def _quick(x, alpha, beta): return 1 - 2**(-(x/alpha)**beta) # Log-Quick def _quicklog(x, alpha, beta): return 1 - 2**(-10**(beta*(x - alpha))) # Hyperbolic Secant def _hyperbolic_secant(x, alpha, beta): return (2/np.pi)*np.arctan(np.exp((np.pi/2)*beta*(x - alpha))) ################################################################# # DEFINE GENERIC FORMULATION OP PSYCHOMETRIC FUNCTIONS ################################################################# # Note: Although laballed as scale and slope, these parameters # can jointly determine such characteristics depending upon # the PF function chosen (e.g., Weibull). def psyfunction(x, scale, slope, gamma, lambda_, sigmoid_type): with np.errstate(divide='ignore',invalid='ignore', over ='ignore'): if sigmoid_type == 'norm': return gamma + (1 - lambda_ - gamma) * _norm(x, scale, slope) elif sigmoid_type == 'logistic': return gamma + (1 - lambda_ - gamma) * _logistic(x, scale, slope) elif sigmoid_type == 'weibull': return gamma + (1 - lambda_ - gamma) * _weibull(x, scale, slope) elif sigmoid_type == 'gumbel': return gamma + (1 - lambda_ - gamma) * _gumbel(x, scale, slope) elif sigmoid_type == 'quick': return gamma + (1 - lambda_ - gamma) * _quick(x, scale, slope) elif sigmoid_type == 'log-quick': return gamma + (1 - lambda_ - gamma) * _quicklog(x, scale, slope) elif sigmoid_type == 'hyperbolic': return gamma + (1 - lambda_ - gamma) * _hyperbolic_secant(x, scale, slope)
SlugocM/bayesfit
bayesfit/psyFunction.py
Python
apache-2.0
2,658
[ "Gaussian" ]
e81cc5196fcca36d97cce717aac8017d773256776c86f3bc3b8f733e8e9af32e
import mdp # import numeric module (scipy, Numeric or numarray) numx, numx_rand, numx_linalg = mdp.numx, mdp.numx_rand, mdp.numx_linalg numx_description = mdp.numx_description import random import itertools def timediff(data): """Returns the array of the time differences of data.""" # this is the fastest way we found so far return data[1:]-data[:-1] def refcast(array, dtype): """ Cast the array to dtype only if necessary, otherwise return a reference. """ dtype = mdp.numx.dtype(dtype) if array.dtype == dtype: return array return array.astype(dtype) def scast(scalar, dtype): """Convert a scalar in a 0D array of the given dtype.""" return numx.array(scalar, dtype=dtype) def rotate(mat, angle, columns=(0, 1), units='radians'): """ Rotate in-place data matrix (NxM) in the plane defined by the columns=[i,j] when observation are stored on rows. Observations are rotated counterclockwise. This corresponds to the following matrix-multiplication for each data-point (unchanged elements omitted): [ cos(angle) -sin(angle) [ x_i ] sin(angle) cos(angle) ] * [ x_j ] If M=2, columns=[0,1]. """ if units is 'degrees': angle = angle/180.*numx.pi cos_ = numx.cos(angle) sin_ = numx.sin(angle) [i, j] = columns col_i = mat[:, i] + 0. col_j = mat[:, j] mat[:, i] = cos_*col_i - sin_*col_j mat[:, j] = sin_*col_i + cos_*col_j def permute(x, indices=(0, 0), rows=0, cols=1): """Swap two columns and (or) two rows of 'x', whose indices are specified in indices=[i,j]. Note: permutations are done in-place. You'll lose your original matrix""" ## the nicer option: ## x[i,:],x[j,:] = x[j,:],x[i,:] ## does not work because array-slices are references. ## The following would work: ## x[i,:],x[j,:] = x[j,:].tolist(),x[i,:].tolist() ## because list-slices are copies, but you get 2 ## copies instead of the one you need with our method. ## This would also work: ## tmp = x[i,:].copy() ## x[i,:],x[j,:] = x[j,:],tmp ## but it is slower (for larger matrices) than the one we use. [i, j] = indices if rows: x[i, :], x[j, :] = x[j, :], x[i, :] + 0 if cols: x[:, i], x[:, j] = x[:, j], x[:, i] + 0 def hermitian(x): """Compute the Hermitian, i.e. conjugate transpose, of x.""" return x.T.conj() def symrand(dim_or_eigv, dtype="d"): """Return a random symmetric (Hermitian) matrix. If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues uniformly distributed on (-1,1). If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose eigenvalues are 'a'. """ if isinstance(dim_or_eigv, int): dim = dim_or_eigv d = (numx_rand.random(dim)*2) - 1 elif isinstance(dim_or_eigv, numx.ndarray) and len(dim_or_eigv.shape) == 1: dim = dim_or_eigv.shape[0] d = dim_or_eigv else: raise mdp.MDPException("input type not supported.") v = random_rot(dim) #h = mdp.utils.mult(mdp.utils.mult(hermitian(v), mdp.numx.diag(d)), v) h = mdp.utils.mult(mult_diag(d, hermitian(v), left=False), v) # to avoid roundoff errors, symmetrize the matrix (again) h = 0.5*(h.T+h) if dtype in ('D', 'F', 'G'): h2 = symrand(dim_or_eigv) h = h + 1j*(numx.triu(h2)-numx.tril(h2)) return refcast(h, dtype) def random_rot(dim, dtype='d'): """Return a random rotation matrix, drawn from the Haar distribution (the only uniform distribution on SO(n)). The algorithm is described in the paper Stewart, G.W., "The efficient generation of random orthogonal matrices with an application to condition estimators", SIAM Journal on Numerical Analysis, 17(3), pp. 403-409, 1980. For more information see http://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization""" H = mdp.numx.eye(dim, dtype=dtype) D = mdp.numx.ones((dim,), dtype=dtype) for n in range(1, dim): x = mdp.numx_rand.normal(size=(dim-n+1,)).astype(dtype) D[n-1] = mdp.numx.sign(x[0]) x[0] -= D[n-1]*mdp.numx.sqrt((x*x).sum()) # Householder transformation Hx = ( mdp.numx.eye(dim-n+1, dtype=dtype) - 2.*mdp.numx.outer(x, x)/(x*x).sum() ) mat = mdp.numx.eye(dim, dtype=dtype) mat[n-1:, n-1:] = Hx H = mdp.utils.mult(H, mat) # Fix the last sign such that the determinant is 1 D[-1] = (-1)**(1-dim%2)*D.prod() # Equivalent to mult(numx.diag(D), H) but faster H = (D*H.T).T return H def norm2(v): """Compute the 2-norm for 1D arrays. norm2(v) = sqrt(sum(v_i^2))""" return numx.sqrt((v*v).sum()) def cov2(x, y): """Compute the covariance between 2D matrices x and y. Complies with the old scipy.cov function: different variables are on different columns.""" mnx = x.mean(axis=0) mny = y.mean(axis=0) tlen = x.shape[0] return mdp.utils.mult(x.T, y)/(tlen-1) - numx.outer(mnx, mny) def cov_maxima(cov): """Extract the maxima of a covariance matrix.""" dim = cov.shape[0] maxs = [] if dim >= 1: cov=abs(cov) glob_max_idx = (cov.argmax()//dim, cov.argmax()%dim) maxs.append(cov[glob_max_idx[0], glob_max_idx[1]]) cov_reduce = cov.copy() cov_reduce = cov_reduce[numx.arange(dim) != glob_max_idx[0], :] cov_reduce = cov_reduce[:, numx.arange(dim) != glob_max_idx[1]] maxs.extend(cov_maxima(cov_reduce)) return maxs else: return [] def mult_diag(d, mtx, left=True): """Multiply a full matrix by a diagonal matrix. This function should always be faster than dot. Input: d -- 1D (N,) array (contains the diagonal elements) mtx -- 2D (N,N) array Output: mult_diag(d, mts, left=True) == dot(diag(d), mtx) mult_diag(d, mts, left=False) == dot(mtx, diag(d)) """ if left: return (d*mtx.T).T else: return d*mtx def comb(N, k): """Return number of combinations of k objects from a set of N objects without repetitions, a.k.a. the binomial coefficient of N and k.""" ret = 1 for mlt in xrange(N, N-k, -1): ret *= mlt for dv in xrange(1, k+1): ret //= dv return ret # WARNING numpy.linalg.eigh does not support float sizes larger than 64 bits, # and complex numbers of size larger than 128 bits. # Also float16 is not supported either. # This is not a problem for MDP, as long as scipy.linalg.eigh is available. def get_dtypes(typecodes_key, _safe=True): """Return the list of dtypes corresponding to the set of typecodes defined in numpy.typecodes[typecodes_key]. E.g., get_dtypes('Float') = [dtype('f'), dtype('d'), dtype('g')]. If _safe is True (default), we remove large floating point types if the numerical backend does not support them. """ types = [] for c in numx.typecodes[typecodes_key]: try: type_ = numx.dtype(c) if (_safe and not mdp.config.has_symeig == 'scipy.linalg.eigh' and type_ in _UNSAFE_DTYPES): continue types.append(type_) except TypeError: pass return types _UNSAFE_DTYPES = [numx.typeDict[d] for d in ['float16', 'float96', 'float128', 'complex192', 'complex256'] if d in numx.typeDict] def nongeneral_svd(A, range=None, **kwargs): """SVD routine for simple eigenvalue problem, API is compatible with symeig.""" Z2, w, Z = mdp.utils.svd(A) # sort eigenvalues and corresponding eigenvectors idx = w.argsort() w = w.take(idx) Z = Z.take(idx, axis=0).T if range is not None: lo, hi = range Z = Z[:, lo-1:hi] w = w[lo-1:hi] return w, Z def sqrtm(A): """This is a symmetric definite positive matrix sqrt function""" d, V = mdp.utils.symeig(A) return mdp.utils.mult(V, mult_diag(numx.sqrt(d), V.T)) # replication functions def lrep(x, n): """Replicate x n-times on a new first dimension""" shp = [1] shp.extend(x.shape) return x.reshape(shp).repeat(n, axis=0) def rrep(x, n): """Replicate x n-times on a new last dimension""" shp = x.shape + (1,) return x.reshape(shp).repeat(n, axis=-1) def irep(x, n, dim): """Replicate x n-times on a new dimension dim-th dimension""" x_shape = x.shape shp = x_shape[:dim] + (1,) + x_shape[dim:] return x.reshape(shp).repeat(n, axis=dim) # /replication functions try: # product exists only in itertools >= 2.6 from itertools import product except ImportError: def product(*args, **kwds): """Cartesian product of input iterables. """ # taken from python docs 2.6 # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) def orthogonal_permutations(a_dict): """ Takes a dictionary with lists as keys and returns all permutations of these list elements in new dicts. This function is useful, when a method with several arguments shall be tested and all of the arguments can take several values. The order is not defined, therefore the elements should be orthogonal to each other. >>> for i in orthogonal_permutations({'a': [1,2,3], 'b': [4,5]}): print i {'a': 1, 'b': 4} {'a': 1, 'b': 5} {'a': 2, 'b': 4} {'a': 2, 'b': 5} {'a': 3, 'b': 4} {'a': 3, 'b': 5} """ pool = dict(a_dict) args = [] for func, all_args in pool.items(): # check the size of the list in the second item of the tuple args_with_fun = [(func, arg) for arg in all_args] args.append(args_with_fun) for i in product(*args): yield dict(i) def izip_stretched(*iterables): """Same as izip, except that for convenience non-iterables are repeated ad infinitum. This is useful when trying to zip input data with respective labels and allows for having a single label for all data, as well as for havning a list of labels for each data vector. Note that this will take strings as an iterable (of course), so strings acting as a single value need to be wrapped in a repeat statement of their own. Thus, >>> for zipped in izip_stretched([1, 2, 3], -1): print zipped (1, -1) (2, -1) (3, -1) is equivalent to >>> for zipped in izip([1, 2, 3], [-1] * 3): print zipped (1, -1) (2, -1) (3, -1) """ def iter_or_repeat(val): try: return iter(val) except TypeError: return itertools.repeat(val) iterables= map(iter_or_repeat, iterables) while iterables: # need to care about python < 2.6 yield tuple([it.next() for it in iterables]) def weighted_choice(a_dict, normalize=True): """Returns a key from a dictionary based on the weight that the value suggests. If 'normalize' is False, it is assumed the weights sum up to unity. Otherwise, the algorithm will take care of normalising. Example: >>> d = {'a': 0.1, 'b': 0.5, 'c': 0.4} >>> weighted_choice(d) # draws 'b':'c':'a' with 5:4:1 probability TODO: It might be good to either shuffle the order or explicitely specify it, before walking through the items, to minimise possible degeneration. """ if normalize: d = a_dict.copy() s = sum(d.values()) for key, val in d.items(): d[key] = d[key] / s else: d = a_dict rand_num = random.random() total_rand = 0 for key, val in d.items(): total_rand += val if total_rand > rand_num: return key return None def bool_to_sign(an_array): """Return -1 for each False; +1 for each True""" return numx.sign(an_array - 0.5) def sign_to_bool(an_array, zero=True): """Return False for each negative value, else True. The value for 0 is specified with 'zero'. """ if zero: return numx.array(an_array) >= 0 else: return numx.array(an_array) > 0 def gabor(size, alpha, phi, freq, sgm, x0=None, res=1, ampl=1.): """Return a 2D array containing a Gabor wavelet. Input arguments: size -- (height, width) (pixels) alpha -- orientation (rad) phi -- phase (rad) freq -- frequency (cycles/deg) sgm -- (sigma_x, sigma_y) standard deviation along the axis of the gaussian ellipse (pixel) x0 -- (x,y) coordinates of the center of the wavelet (pixel) Default: None, meaning the center of the array res -- spatial resolution (deg/pixel) Default: 1, so that 'freq' is measured in cycles/pixel ampl -- constant multiplying the result Default: 1. """ # init w, h = size if x0 is None: x0 = (w//2, h//2) y0, x0 = x0 # some useful quantities freq *= res sinalpha = numx.sin(alpha) cosalpha = numx.cos(alpha) v0, u0 = freq*cosalpha, freq*sinalpha # coordinates #x = numx.mgrid[-x0:w-x0, -y0:h-y0] x = numx.meshgrid(numx.arange(w)-x0, numx.arange(h)-y0) x = (x[0].T, x[1].T) xr = x[0]*cosalpha - x[1]*sinalpha yr = x[0]*sinalpha + x[1]*cosalpha # gabor im = ampl*numx.exp(-0.5*(xr*xr/(sgm[0]*sgm[0]) + yr*yr/(sgm[1]*sgm[1]))) \ *numx.cos(-2.*numx.pi*(u0*x[0]+v0*x[1]) - phi) return im def residuals(app_x, y_noisy, exp_funcs, x_orig, k=0.0): """Function used internally by invert_exp_funcs2 to approximate inverses in ConstantExpansionNode. """ app_x = app_x.reshape((1,len(app_x))) app_exp_x = numx.concatenate([func(app_x) for func in exp_funcs],axis=1) div_y = numx.sqrt(len(y_noisy)) div_x = numx.sqrt(len(x_orig)) return numx.append( (1-k)*(y_noisy-app_exp_x[0]) / div_y, k * (x_orig - app_x[0])/div_x ) def invert_exp_funcs2(exp_x_noisy, dim_x, exp_funcs, use_hint=False, k=0.0): """Approximates a preimage app_x of exp_x_noisy. Returns an array app_x, such that each row of exp_x_noisy is close to each row of exp_funcs(app_x). use_hint: determines the starting point for the approximation of the preimage. There are three possibilities. if it equals False: starting point is generated with a normal distribution if it equals True: starting point is the first dim_x elements of exp_x_noisy otherwise: use the parameter use_hint itself as the first approximation k: weighting factor in [0, 1] to balance between approximation error and closeness to the starting point. For instance: objective function is to minimize: (1-k) * |exp_funcs(app_x) - exp_x_noisy|/output_dim + k * |app_x - starting point|/input_dim Note: this function requires scipy. """ if numx_description != 'scipy': raise NotImplementedError('This function requires scipy.') else: import scipy.optimize num_samples = exp_x_noisy.shape[0] if isinstance(use_hint, numx.ndarray): app_x = use_hint.copy() elif use_hint == True: app_x = exp_x_noisy[:,0:dim_x].copy() else: app_x = numx.random.normal(size=(num_samples,dim_x)) for row in range(num_samples): plsq = scipy.optimize.leastsq(residuals, app_x[row], args=(exp_x_noisy[row], exp_funcs, app_x[row], k), maxfev=50*dim_x) app_x[row] = plsq[0] app_exp_x = numx.concatenate([func(app_x) for func in exp_funcs],axis=1) return app_x, app_exp_x
ME-ICA/me-ica
meica.libs/mdp/utils/routines.py
Python
lgpl-2.1
15,909
[ "Gaussian" ]
f56a30a30a1f89c6ae76b9ca3c3450dcfd9a9a322c117eab38b69422fd148680
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from pyscf import lib from pyscf import gto, scf try: from pyscf.geomopt import berny_solver except ImportError: berny_solver = False mol = gto.M(atom=''' O 0. 0. 0. H 0. -0.757 0.587 H 0. 0.757 0.587 ''', symmetry=True, verbose=0) def tearDownModule(): global mol del mol @unittest.skipIf(not berny_solver, "pyberny library not found.") class KnownValues(unittest.TestCase): def test_as_pyscf_method(self): gs = scf.RHF(mol).nuc_grad_method().as_scanner() f = lambda mol: gs(mol) m = berny_solver.as_pyscf_method(mol, f) mol1 = berny_solver.optimize(m) self.assertAlmostEqual(lib.fp(mol1.atom_coords()), 2.20003359484436, 4) self.assertEqual(mol1.symmetry, 'C2v') def test_optimize(self): conv_params = { 'gradientmax': 0.1e-3, 'gradientrms': 0.1e-3, } mf = scf.RHF(mol) mol_eq = mf.Gradients().optimizer(solver='berny').kernel(params=conv_params) self.assertAlmostEqual(lib.fp(mol_eq.atom_coords()), 2.19943732625887, 4) if __name__ == "__main__": print("Tests for berny_solver") unittest.main()
gkc1000/pyscf
pyscf/geomopt/test/test_berny_solver.py
Python
apache-2.0
1,843
[ "PySCF" ]
e8f3866d7fb23f7890567c5e522d635a6ab2410452847cc195b897e34f53632d
# This Python file uses the following encoding: utf-8 # Create your views here. from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.template.loader import get_template from django.template import Context from django.utils.safestring import SafeString from django.utils.html import strip_tags from django.utils.timezone import * from django.utils.encoding import smart_str, smart_text #from dateutil.relativedelta import relativedelta from django.shortcuts import render_to_response, render, get_object_or_404 from django.conf import settings from django import forms from multiquest.forms import * from multiquest.models import * from multiquest.utilities import * from multiquest.utilities_db import * from datetime import datetime import pickle from django.db.models import Q from django.core.mail import send_mail, EmailMessage from django.core.context_processors import csrf from reportlab.pdfgen import canvas import os from django.contrib.auth import authenticate from django.contrib.auth.views import login, logout from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group, User, Permission from django.contrib.auth.decorators import login_required from operator import itemgetter, attrgetter # used for sorting & selecting from a list import csv import unicodedata allResultsDict = 'questionnaireResults' allResultsList = 'questionnaireResultsList' respondentIDDict = 'respondentIDInfo' allYesButton = 'set flag when all responses are "Yes"' anyYesButton = 'set flag when some (perhaps all) responses are "Yes"' allNoButton = 'set flag when all responses are "No"' anyNoButton = 'set flag when some (perhaps all) responses are "No"' anySelectedButton = 'set flag when at least one choice is selected' noneSelectedButton = 'set flag when no choices are selected' multipleChoiceTypes = [ 'MultipleChoiceField', 'MultipleChoiceRequiredField', 'SingleChoiceField', ] autoDebugFlag = 'debugSessionFlag' class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() testCondChoices = { allYesButton : 'allYesButton', anyYesButton : 'anyYesButton', allNoButton : 'allNoButton', anyNoButton : 'anyNoButton', anySelectedButton : 'anySelectedButton', noneSelectedButton : 'noneSelectedButton', } SessionAnalysisFlags = 'SessionAnalysisFlags' analSaveButton = 'Save the condition for setting the flag to the database' url_base = settings.WSGI_URL_PREFIX + 'multiquest/' workingPageURL_base = url_base + 'working_pages/' registrationURL_base = url_base + 'registration/' workingPageTemplateRoot = 'working_pages/' questionnaireSelectionPage = workingPageURL_base + 'setSessionProjectQuestionnaireDefault/' from django.forms.formsets import formset_factory def testing(request): errmsg = '' ArticleFormSet = formset_factory(ArticleForm, extra=4) formset = ArticleFormSet(initial=[ {'title': u'Django is now open source', 'pub_date': timezone.now(),} ]) theForm = formset resultMessage = '' localContext = { 'errmsg' : errmsg, 'theForm' : theForm, 'resultMessage' : resultMessage, } return # def userLogin(request): # not used. # """ User View for login. # Args: # "request" input # Returns: # return_value: html. # Raises: # None. # """ # DebugOut('userLogin: enter') # errMsg=[] # # # check for prior login # # allU = getAllUsers() # # for aUser in allU: # # if aUser.is_authenticated(): # # errMsg.append('Current login: %s now logged out' %aUser.username) # # logout(request) # username = request.POST.get('username','') # password = request.POST.get('password','') # theUser = authenticate(username=username, password=password) # # login(request, theUser) # theProject = getAssociatedProjectForUser(theUser) # if theProject == None: # # redirect to project selection # redirectURL = registrationURL_base + 'selectProjectDefault/' # DebugOut('userLogin: redirect to %s' %redirectURL) # return HttpResponseRedirect(redirectURL) # else: # # redirect to user landing # redirectURL = registrationURL_base + 'userLanding/' # DebugOut('userLogin: redirect to %s' %redirectURL) # return HttpResponseRedirect(redirectURL) # # DebugOut('userLogin: exit') # return render(request, "registration/login.html", { # 'errMsg' : errMsg, # }) def userLogout(request): """ User View for logout. Args: "request" input Returns: return_value: html. Raises: None. """ logout(request) # Redirect to a success page. return render(request, "registration/logout.html", {}) def createNewAccount(request): """ User interface for creation of a User object. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('createNewAccount: enter') if request.method == 'POST': regForm = RegistrationForm(request.POST) if regForm.is_valid(): if request.user.is_authenticated(): # if someone is already logged in! logout(request) new_user = regForm.save() new_user = authenticate(username=request.POST['username'], password=request.POST['password1']) try: studentGroupObj = Group.objects.get(name='Student') except Group.DoesNotExist: # so create it studentGroupObj = Group.objects.create(name='Student') new_user.groups.add(studentGroupObj) login(request, new_user) redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('createNewAccount: redirect to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: regForm = RegistrationForm() DebugOut('createNewAccount: exit') currentContext = { 'regForm': regForm, } currentContext.update(csrf(request)) return render(request, "registration/createNewAccount.html", currentContext) @login_required() def selectProjectDefault(request): """ Allow the selection of a Project as a default to fill the UserProject table. Args http request Database Sets an association between User and Project in UserProject Session data Sets Project default. Uses temporary 'FselectProjectDefault' """ DebugOut('selectProjectDefault: enter') # allProjectInfo record structure # [ Project short tag, name, email, projectAddress, contactPhone, internetLocation, # record number in the Project table ] errMsg = [] theUser = request.user if request.method == 'POST': # Default project selected. # retrieve table from Session data if 'SelectProject' in request.POST: allProjectInfo = displayProjectsWithinScope() # display project information for selection [dummyText, listRecNum] = request.POST['SelectProject'].split(" ") #decode the response # format is "Select" "record number in display list" recNum = int(listRecNum) - 1 # start with zero theProjectIDinDB = allProjectInfo[recNum][-1] # is the record number for the project try: theProject = Project.objects.get(id=theProjectIDinDB) setSessionProject(request, theProject) # set Session data default associateUserToProject(theProject, theUser) projectTag = theProject.shortTag # remove Questionnaire default since it is invalid if 'theQuestionnaire' in request.session: del request.session['theQuestionnaire'] errMsg.append('Project "%s" selected.' %projectTag) redirectURL = registrationURL_base + 'userLanding/' return HttpResponseRedirect(redirectURL) except Project.DoesNotExist: errMsg.append('System error (syserrmsg): Project does not exist') elif 'returnToHome' in request.POST: theProjectTesting = getAssociatedProjectForUser(theUser) if theProjectTesting == None: # no default for the user! errMsg.append('Please select a Project.') else: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) allProjectInfo = displayProjectsWithinScope() # display project information for selection theCurrentDefaultProject = getSessionProject(request) if not theCurrentDefaultProject: # not in session data # fall back to user default theCurrentDefaultProject = getAssociatedProjectForUser(theUser) # If no project, Don't redirect!! This page allows a new user to select currentContext = { 'theUser' : theUser, 'allProjectInfo' : allProjectInfo, 'theCurrentDefaultProject' : theCurrentDefaultProject, 'errMsg' : errMsg, } DebugOut('selectProjectDefault: exit') return render(request,'registration/selectProjectDefault.html', currentContext) def associateUserToProject(theProject, theUser): """ Adds or updates a record in UserProject connecting User and Project. Allow only one Project associate per user. Database Sets and association between User and Project in UserProject. The combination of theProject + theUser must be unique Session data Untouched. """ # check if already existing record. allSAObjs = UserProject.objects.filter( userID=theUser, ) if len(allSAObjs)>1: # delete the extra records and replace with a new one UserProject.objects.filter( userID=theUser, ).delete() UserProject.objects.create( userID=theUser, projectID=theProject ) elif len(allSAObjs)==1: # update the existing record. Don't bother checking if the Project has changed. theSArec = allSAObjs[0] theSArec.projectID=theProject theSArec.save() elif len(allSAObjs)==0: # No records exist for this User, so create one UserProject.objects.create( userID=theUser, projectID=theProject ) return True def getAssociatedProjectForUser(theUser): """ Adds or updates a record in UserProject connecting User and Project. Allow only one Project associate per user. Database Reads UserProject. The combination of theProject + theUser must be unique Session data Untouched. """ try: allSAObjs = UserProject.objects.filter( userID=theUser, ) if len(allSAObjs)>=1: # Should not be greater than 1! So select 1st one in the list. theUSObj = allSAObjs[0] if len(allSAObjs)>1: DebugOut('getAssociatedProjectForUser: syserrmsg: Found more than one project in UserProject table for user: %s'%theUser.username) theProject = theUSObj.projectID elif len(allSAObjs)==0: theProject=None except: theProject=None return theProject @login_required() def uploadDownloadQuestionnaire(request): """Dumps a csv-type file of the default Questionnaire. This is a one line or more descriptive summary. Blah Blah Blah. Args: argument_one: This is of some type a and does x. arg....:... Returns: http response Raises: none. """ DebugOut('uploadDownloadQuestionnaire: enter') errMsg = '' #Standards: “Handling Session values of Project and Questionnaire” for Groups [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) theUser = request.user if not theProject: theProject = getAssociatedProjectForUser(theUser) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) workingQuestionnaireTag = theQuestionnaire.shortTag if not theProject: # select a project. DebugOut('The Project has not been selected') errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) theProjectTag = theProject.shortTag DebugOut('Project: %s, Questionnaire: %s' %(theProject.shortTag, theQuestionnaire.shortTag)) if request.method == 'POST': if 'dumpQuestionnaireSpecification' in request.POST: redirectURL = url_base + 'working_pages/dumpQuestionnaireSpecification/' return HttpResponseRedirect(redirectURL) elif 'uploadQuestionnaireSpecification' in request.POST: DebugOut('in uploadQuestionnaireSpecification') redirectURL = url_base + 'working_pages/uploadQuestionnaireSpecification/' return HttpResponseRedirect(redirectURL) elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) currentContext = { 'theProject' : theProject, 'theUser' : theUser, 'theQuestionnaire' : theQuestionnaire, 'errMsg' : errMsg, } DebugOut('uploadDownloadQuestionnaire: exit') return render(request,'working_pages/uploadDownloadQuestionnaire.html', currentContext) @login_required() def uploadQuestionnaireSpecification(request): """Loads a csv-type file of a Questionnaire specification. The text-editable file is a serialization of the database. Args: http request Returns: http response Raises: none. """ DebugOut('uploadQuestionnaireSpecification: Enter') errMsg = [] DebugOut('User is: %s'%request.user) if request.method == 'POST': DebugOut('in UploadQuestionnaire') DebugOut('request.POST: %s'%request.POST) theForm = UploadFileForm(request.POST, request.FILES) if 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) if theForm.is_valid(): # handle_uploaded_file(request.FILES['theFile']) errMsg.append('This feature is under development.') urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': errMsg, 'wsgiPrefix':urlPrefix}) else: DebugOut('Form errors %s'%theForm.errors) else: DebugOut('Not a POST') theForm = UploadFileForm() DebugOut('uploadQuestionnaireSpecification: Exit') return render(request,'working_pages/uploadQuestionnaireSpecification.html', {'theForm': theForm}) @login_required() def handle_uploaded_file(thePost): DebugOut('handle_uploaded_file: enter') return @login_required() def dumpQuestionnaireSpecification(request): """Dumps a csv-type file of the default Questionnaire. This is a one line or more descriptive summary. Blah Blah Blah. Args: argument_one: This is of some type a and does x. arg....:... Returns: http response Raises: none. """ DebugOut('dumpQuestionnaireSpecification: Enter') errMsg = [] [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') now = str(timezone.now()) questionnaireSpecFileName = "Questionnaire specification %s_%s.txt"%(theProject.shortTag, theQuestionnaire.shortTag) contentDispo = 'attachment; filename=' + '"' + questionnaireSpecFileName + '"' response['Content-Disposition'] = contentDispo response.write('ProjectSeparator'+os.linesep) # Dump Project record # make project pointer into a queryset which adheres to dumpQuerySet requirements projectQS = Project.objects.filter(id=theProject.id) nRecs = dumpQuerySet(response, projectQS) DebugOut('Project nRecs: %s'%nRecs) # dump questionnaire record questionnaireQS = Questionnaire.objects.filter(id=theQuestionnaire.id) nRecs = dumpQuerySet(response, questionnaireQS) DebugOut('Questionnaire nRecs: %s'%nRecs) # dump Pages pageQS = getAllPageObjsForQuestionnaire(theQuestionnaire) nRecs = dumpQuerySet(response, pageQS) DebugOut('Page nRecs: %s'%nRecs) # dump Questions questQS = getAllQuestionObjsForQuestionnaire(theQuestionnaire) nRecs = dumpQuerySet(response, questQS) DebugOut('Question nRecs: %s'%nRecs) # dump ProjectQuestionnaire pqQS = ProjectQuestionnaire.objects.filter( projectID=theProject, questionnaireID=theQuestionnaire, ) nRecs = dumpQuerySet(response, pqQS) DebugOut('ProjectQuestionnaire nRecs: %s'%nRecs) # Dump PageQuestion table # build an "or" query to include all pages # initialize query queryOR = Q(pageID=pageQS[0]) for anID in pageQS[1:]: queryOR = queryOR | Q(pageID=anID) PageQuestionQS = PageQuestion.objects.filter(queryOR) nRecs = dumpQuerySet(response, PageQuestionQS) DebugOut('PageQuestion nRecs: %s'%nRecs) # Dump ResponseChoice table # build an "or" query to include all pages # initialize query queryOR = Q(questionID=questQS[0]) for anID in questQS[1:]: queryOR = queryOR | Q(questionID=anID) ResponseChoiceQS = ResponseChoice.objects.filter(queryOR) nRecs = dumpQuerySet(response, ResponseChoiceQS) DebugOut('ResponseChoice nRecs: %s'%nRecs) # Dump ProjectAttributes table ProjectAttributesQS = ProjectAttributes.objects.filter(projectID=theProject) nRecs = dumpQuerySet(response, ProjectAttributesQS) DebugOut('ProjectAttributes nRecs: %s'%nRecs) # Dump QuestionnaireAttributes table QuestionnaireAttributesQS = QuestionnaireAttributes.objects.filter(questionnaireID=theQuestionnaire) nRecs = dumpQuerySet(response, QuestionnaireAttributesQS) DebugOut('QuestionnaireAttributes nRecs: %s'%nRecs) # Dump PageAnalysis table PageAnalysisQS = PageAnalysis.objects.filter(questionnaireID=theQuestionnaire) nRecs = dumpQuerySet(response, PageAnalysisQS) DebugOut('PageAnalysis nRecs: %s'%nRecs) # Dump PageAttribute table PageAttributesQS = PageAttributes.objects.all() nRecs = dumpQuerySet(response, PageAttributesQS) DebugOut('PageAttribute nRecs: %s'%nRecs) DebugOut('dumpQuestionnaireSpecification: Exit') return response @login_required() def userLanding(request): """ Next page after login. Set various defaults associated with the user. Check for preexisting Project association. If not associated, redirect to selection. Database Session data Untouched. """ DebugOut('userLanding: enter') errMsg = [] theUser = request.user DebugOut('the user is: %s' %theUser) theProject = getSessionProject(request) if not theProject: # if not already set in session data, then use User default theProject = getAssociatedProjectForUser(theUser) # retrieve default project for User if theProject == None: # redirect to project selection redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) else: # set default project in session data setSessionProject(request, theProject) # remove Questionnaire default since it may be invalid if 'theQuestionnaire' in request.session: del request.session['theQuestionnaire'] theQuestionnaire = getSessionQuestionnaire(request) # May be None if request.method == 'POST': if 'differentProject' in request.POST: redirectURL = registrationURL_base + 'selectProjectDefault/' return HttpResponseRedirect(redirectURL) elif 'editProject' in request.POST: redirectURL = url_base + 'registration/editProjectRecord/' return HttpResponseRedirect(redirectURL) elif 'displayRunQuestionnaire' in request.POST: redirectURL = url_base + 'working_pages/selectProjectsQuestionnairesToExecute/' return HttpResponseRedirect(redirectURL) elif 'duplicateQuestionnaireView' in request.POST: redirectURL = url_base + 'working_pages/duplicateQuestionnaireView/' return HttpResponseRedirect(redirectURL) elif 'runTheQuestionnaire' in request.POST: removeResponsesFromSessionData(request) questionnaireEnvironmentPrep( request, theProject, theQuestionnaire) urltogo = questionnaireToGo(request, theProject, theQuestionnaire) return HttpResponseRedirect(urltogo) elif 'selectQuestionnaireDefault' in request.POST: redirectURL = url_base + 'registration/selectQuestionnaireDefault/' return HttpResponseRedirect(redirectURL) elif 'createPageTransition' in request.POST: redirectURL = url_base + 'working_pages/setPageToPageTransitionCalculated/' return HttpResponseRedirect(redirectURL) elif 'editDefaultPageTransitions' in request.POST: redirectURL = url_base + 'working_pages/editDefaultPageTransitions/' return HttpResponseRedirect(redirectURL) elif 'dumpSubmissionDataForProject' in request.POST: redirectURL = url_base + 'working_pages/dumpSubmissionDataForProject/' return HttpResponseRedirect(redirectURL) elif 'createProjectWithSamples' in request.POST: redirectURL = url_base + 'working_pages/createProjectWithSamples/' return HttpResponseRedirect(redirectURL) elif 'uploadDownloadQuestionnaire' in request.POST: redirectURL = url_base + 'working_pages/uploadDownloadQuestionnaire/' return HttpResponseRedirect(redirectURL) elif 'dumpSubmissionDataForProject' in request.POST: redirectURL = url_base + 'working_pages/dumpSubmissionDataForProject/' return HttpResponseRedirect(redirectURL) elif 'responseViewer' in request.POST: redirectURL = url_base + 'working_pages/responseViewer/' return HttpResponseRedirect(redirectURL) elif 'responseDelete' in request.POST: redirectURL = url_base + 'working_pages/responseDelete/' return HttpResponseRedirect(redirectURL) elif 'editQuestionnaireInfo' in request.POST: redirectURL = url_base + 'working_pages/editQuestionnaire/' return HttpResponseRedirect(redirectURL) elif 'bulkPageEdit' in request.POST: redirectURL = url_base + 'working_pages/bulkPageEdit/' return HttpResponseRedirect(redirectURL) elif 'editQuestionNames' in request.POST: redirectURL = url_base + 'working_pages/editQuestionNames/' return HttpResponseRedirect(redirectURL) elif 'bulkQuestionEdit' in request.POST: redirectURL = url_base + 'working_pages/bulkQuestionEdit/' return HttpResponseRedirect(redirectURL) elif 'deleteQuestionnaireView' in request.POST: redirectURL = url_base + 'working_pages/deleteQuestionnaireView/' return HttpResponseRedirect(redirectURL) elif 'savecsvDecoder' in request.POST: redirectURL = url_base + 'working_pages/savecsvDecoder/' return HttpResponseRedirect(redirectURL) elif 'logout' in request.POST: redirectURL = url_base + 'registration/logout/' return HttpResponseRedirect(redirectURL) #http://10.0.1.73:8000/multiquest/working_pages/savecsvDecoder/ currentContext = { 'theProject' : theProject, 'theUser' : theUser, 'theQuestionnaire' : theQuestionnaire, 'errMsg' : errMsg, } DebugOut('userLanding: exit') return render(request,'registration/userLanding.html', currentContext) @login_required() def createProjectWithSamples(request): """ Create a new Questionnaire object in the current Project. Database Create a new record in the Questionnaire table. Create sample Questionnaires. Session data Untouched. """ DebugOut('createProjectWithSamples: enter') errMsg = [] theProject = getSessionProject(request) if not theProject: # not in session data # fall back to user default theUser = request.user theProject = getAssociatedProjectForUser(theUser) if not theProject: # Redirect if still no project redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # find the sample questionnaire projectTagforSample = 'test_project' questionnaireTagforSample = 'TestQuest' # "Get" this Questionnaire questionnaireTagforTarget = 'SampleQ' # and "Put" it into the current project under this name sampleQuestionnaire = getQuestionnaireObjFromTags( projectTagforSample, questionnaireTagforSample) existingQuestionnaireTags = getQuestionnaireTagsForProject(theProject) # Capture request to go home if request.method == 'POST': if 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('createProjectWithSamples: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) if not sampleQuestionnaire: errMsg.append('syserrmsg: Sample questionnaire name %s does not exist for copying!'%questionnaireTagforSample) currentContext = { 'questionnaireTagforTarget' : questionnaireTagforTarget, 'existingQuestionnaireTags' : existingQuestionnaireTags, 'theProject' : theProject, 'errMsg' : errMsg, } DebugOut('createProjectWithSamples: exit') return render(request,'working_pages/createProjectWithSamples.html', currentContext) DebugOut('The Sample questionnaire name is: %s'%sampleQuestionnaire.shortTag) if request.method == 'POST': if 'CreateSampleQuestionnaire' in request.POST: DebugOut('In CreateSampleQuestionnaire') # Before creation check to see if the name conflicts DebugOut('Start name: %s'%questionnaireTagforTarget) maxLength = 30 # maximum length of a Questionnaire shortTag. theNewName = makeUniqueTag( existingQuestionnaireTags, questionnaireTagforTarget, maxLength) DebugOut('Updated name: %s'%theNewName) newQuestionnaire = duplicateQuestionnaire( theProject, sampleQuestionnaire, theNewName) # update the list with the new Questionnaire existingQuestionnaireTags = getQuestionnaireTagsForProject(theProject) DebugOut('The new Sample questionnaire name is: %s'%newQuestionnaire.shortTag) currentContext = { 'questionnaireTagforTarget' : questionnaireTagforTarget, 'existingQuestionnaireTags' : existingQuestionnaireTags, 'theProject' : theProject, 'errMsg' : errMsg, } DebugOut('createProjectWithSamples: exit') return render(request,'working_pages/createProjectWithSamples.html', currentContext) @login_required() def editProjectRecord(request): """ Edit the current default Project record Database Create a new record in the Project table. Create sample Questionnaires. Session data Untouched. """ DebugOut('editProjectRecord: enter') errMsg = [] theUser = request.user theProject = getAssociatedProjectForUser(theUser) if request.method == 'POST': theForm = ProjectForm(request.POST) if 'submitButton' in request.POST: # accept the Project edits if request.POST['submitButton'] == 'accept Project Edits': if theForm.is_valid(): # Save the edited Project record. DebugOut('after is_valid') cleanedData = theForm.cleaned_data DebugOut('cleanedData %s' %cleanedData) theForm = ProjectForm(cleanedData) # want to UPDATE the Project record updateProjectRecord(theProject,cleanedData) # theForm.save() # error: creates a new record rather than updates elif 'returnToHome' in request.POST: # return to Home Page redirectURL = registrationURL_base + 'userLanding/' return HttpResponseRedirect(redirectURL) else: theForm = ProjectForm(instance=theProject) currentContext = { 'theProject' : theProject, 'theForm' : theForm, 'errMsg' : errMsg, } DebugOut('editProjectRecord: exit') return render(request,'registration/editProjectRecord.html', currentContext) # **** How to do this without calling out each field! def updateProjectRecord(theProject,cleanedData): # Alas, how to get rid of this!! """ Edit the current default Project record using the data dictionary input. Args theProject cleanedData: dictionary Database Update the input record in the Project table. Create sample Questionnaires. Session data Untouched. """ if 'shortTag' in cleanedData: theProject.shortTag=cleanedData['shortTag'] if 'abbrev' in cleanedData: theProject.abbrev=cleanedData['abbrev'] if 'name' in cleanedData: theProject.name=cleanedData['name'] if 'projectAddress' in cleanedData: theProject.projectAddress=cleanedData['projectAddress'] if 'email' in cleanedData: theProject.email=cleanedData['email'] if 'contactPhone' in cleanedData: theProject.contactPhone=cleanedData['contactPhone'] if 'internetLocation' in cleanedData: theProject.internetLocation=cleanedData['internetLocation'] theProject.save() return theProject def listRegistration(request): """ List information about the registered users. """ DebugOut('listRegistration: enter') errMsg = [] # Initialize error messages allG=Group.objects.all() colList = [ 'Project', 'User Name', 'Last Name', 'First Name', 'Email', 'Last Login', 'Date Joined', 'Group Name', ] allMemberInfo = [] for aGroup in allG: allMembs=User.objects.filter( groups=aGroup) # Lists the members of a group for aMem in allMembs: username = aMem.username last_name = aMem.last_name first_name = aMem.first_name email = aMem.email last_login = aMem.last_login date_joined = aMem.date_joined groupName = aGroup.name try: projectTag = UserProject.objects.get(userID=aMem).projectID.shortTag except: projectTag = '' allMemberInfo.append([ projectTag, username, last_name, first_name, email, last_login, date_joined, groupName, ]) if len(allMemberInfo)==0: errMsg.append('No members to be listed') DebugOut('listRegistration: exit') return render(request, workingPageTemplateRoot + 'tablelisting.html', {'pageTitle' : 'List the Groups and their members', 'allValues' : allMemberInfo, 'colList' : colList, 'bannerText' : 'List the Groups and their members', 'bannerText1' : '', 'back_to' : settings.WSGI_URL_PREFIX + 'multiquest/intro/', 'back_toPrompt' : 'Return to the Introduction Page', 'errMsg' : errMsg, }) def intro(request): DebugOut('intro: enter') [currentProject, currentQuestionnaire] = getSessionQuestionnaireProject(request) if request.method == 'POST': DebugOut('In "post"') if currentProject: projectName = currentProject.shortTag else: projectName = '' if currentQuestionnaire: questionnaireName = currentQuestionnaire.shortTag else: questionnaireName = '' introContext = {'current_date' : timezone.now(), 'thishost' : request.get_host(), 'back_to' : 'multiquest/intro/', 'projectName' : projectName, 'questionnaireName' : questionnaireName, 'imageloc' : settings.MEDIA_URL, 'workingPageTemplateRoot' : workingPageTemplateRoot, 'workingPageURL_base' : workingPageURL_base, 'registrationURL_base' : registrationURL_base, 'urlprefix' : settings.WSGI_URL_PREFIX, 'debug' : settings.DEBUG} DebugOut('intro: exit') return render(request, workingPageTemplateRoot + 'intro.html', introContext) def selectPages(request): """Select pages to include in a Questionnaire from a list. This function displays a list Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('selectPages: enter') [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] return render(request, 'system_error.html', { 'syserrmsg': errMsg}) # list the columns colList = ['Page Tag','Description (not displayed)','Explanation','Prologue','Epilogue','Language','Page Type', 'Questionnaire member'] allValuesUnsorted = [] # table rows pageObjs = getAllPageObjsInQuestionnaires() for aPage in pageObjs: theQaires = getAllQuestionnairesReferencingAPage( aPage ) theQTags = [aQ.shortTag for aQ in theQaires] tagListStr = ', '.join(theQTags) rowValues = [ aPage.shortTag, aPage.description, aPage.explanation, aPage.prologue, aPage.epilogue, aPage.language, aPage.pageType, tagListStr, ] allValuesUnsorted.append(rowValues) allValues = sorted( allValuesUnsorted, key=itemgetter(0,7)) DebugOut('selectPages: exit') return render(request, workingPageTemplateRoot + 'selectPages.html', {'allValues' : allValues}) def listPages(request): """View a listing of pages. This function displays a list Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('listPages: enter') errMsg = [] # Initialize error messages try: pageListing = Page.objects.all().order_by('shortTag') except: errMsg.append('List Pages: query to database failed.') if errMsg != []: DebugOut(str(errMsg)) return render(request, 'system_error.html', { 'syserrmsg': errMsg}) allPages = getAllPageObjsInQuestionnaires() # All Pages referenced [allValues, colList, pageRecordDict1 ] = displayAllPageInfo(allPages) if errMsg == []: errMsg = '' missingPages = getAllPageObjsNotReferenced() # All Pages referenced [allValues2, colList, pageRecordDict2 ] = displayAllPageInfo(missingPages) DebugOut('listPages: exit') return render(request, workingPageTemplateRoot + 'tablelisting.html', {'pageTitle' : 'List the available Pages', 'allValues' : allValues, 'colList' : colList, 'allValues2' : allValues2, 'colList2' : colList, 'imageloc' : settings.MEDIA_URL, 'bannerText' : 'List the available Pages', 'bannerText1' : '', 'bannerText2' : 'Page list NOT in any Questionnaire', 'back_to' : settings.WSGI_URL_PREFIX + 'multiquest/intro/', 'back_toPrompt' : 'Return to the Introduction Page', 'errMsg' : errMsg, }) def listQuestions(request): errMsg = [] # Initialize error messages workingPageTemplateRoot = 'working_pages/' tableListing = getAllQuestionObjsEditable() numberOfQuestions = tableListing.count() if errMsg != []: DebugOut(str(errMsg)) return render(request, 'system_error.html', { 'syserrmsg': errMsg}) colList = ['Question Text','Question Tag','Response Type','Explanation (viewed by respondent)','Description (not viewed by respondent)',"Page Tag('s)"] dbNames = ['questionText','questionTag','responseType','explanation','description','shortTag' ] allValues = [] for questionObj in tableListing: rowValues = [] for item in dbNames: if item == 'shortTag': allPQs = PageQuestion.objects.filter(questionID=questionObj) allTags = [aPQ.pageID.shortTag for aPQ in allPQs] # list comprehension tagListStr = ', '.join(allTags) rowValues.append(tagListStr) else: rowValues.append(unicode(getattr(questionObj, item)).encode('utf-8')) allValues.append(rowValues) if errMsg == []: errMsg = '' return render(request, workingPageTemplateRoot + 'tablelisting.html', {'pageTitle' : 'List the available Questions', 'allValues' : allValues, 'colList' : colList, 'allValues2' : '', 'colList2' : '', 'imageloc' : settings.MEDIA_URL, 'bannerText' : 'List the available Questions', 'bannerText1' : 'Number of questions: %s' %numberOfQuestions, 'bannerText2' : '', 'back_to' : settings.WSGI_URL_PREFIX + 'multiquest/intro/', 'back_toPrompt' : 'Return to the Introduction Page', 'errMsg' : errMsg, }) def verifyQuestionnaireProjectDB(request, whichProject, whichQuest): """Checks input Project tag and Questionnaire tag against the database if both exist in the database, then return the corresponding objects errMsg = False Does not set Session Data, does not write to the database Purpose: help with translating a url and mapping the page tag to a page record Args: request: request sent from client browser whichProject: Project Tag: character string whichQuest: Questionnaire Tag: character string Returns: Project and Questionnaire objects from Session Data Raises: None. """ errMsg = [] try: theProject = getProjectObj(whichProject) except: errMess = 'syserrmsg: url "%s/" does not match any project in the database' %(whichProject) errMsg.append(errMess) try: theQuestionnaire = getQuestionnaireObjFromTags(whichProject, whichQuest) except: errMess = 'syserrmsg: url "%s/" does not match any questionnaire in the database' %(whichQuest) errMsg.append(errMess) if errMsg == []: errMsg = False return [theProject, theQuestionnaire, errMsg] def verifyQuestionnaireProject(request, whichProject, whichQuest): """Checks input Project tag and Questionnaire tag against the session data. If both exist in the database, then return the corresponding objects errMsg = False Does not set Session Data, does not write to the database Purpose: help with translating a url and mapping the page tag to a page record Args: request: request sent from client browser whichProject: Project Tag: character string whichQuest: Questionnaire Tag: character string Returns: Project and Questionnaire objects from Session Data Raises: None. """ # checks input Project tag and Questionnaire tag against session data # if both exist in the session data, then return the corresponding objects errMsg = False # Session data is read, but not altered. errMessOut = [] if not whichProject: errMess = 'Debug: Project tag is missing from url.' DebugOut(errMess) errMessOut.append(errMess) if not whichQuest: errMess = 'syserrmsg: Questionnaire tag is missing from url.' DebugOut(errMess) errMessOut.append(errMess) if errMessOut != []: return [None, None, errMessOut] if request: [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) # retrieve from session data else: errMess = 'No session data' DebugOut(errMess) errMessOut.append(errMess) return [None, None, errMessOut] if not theProject: errMess = 'Debug: current Project is not specified for this Session.' DebugOut(errMess) errMessOut.append(errMess) if not theQuestionnaire: errMess = 'syserrmsg: current Questionnaire is not specified for this Session.' DebugOut(errMess) errMessOut.append(errMess) if errMessOut != []: return [theProject, theQuestionnaire, errMessOut] # Verify that whichProject matches session data if theProject.shortTag != whichProject: errMess = 'syserrmsg: url "%s/" does not match current project "%s/"' %(whichProject, theProject.shortTag) DebugOut(errMess) errMessOut.append(errMess) # Verify that whichQuest matches session data if theQuestionnaire.shortTag != whichQuest: errMess = 'syserrmsg: url "%s/" does not match current questionnaire "%s"/' %(whichQuest, theQuestionnaire.shortTag) DebugOut(errMess) errMessOut.append(errMess) if errMessOut != []: return [theProject, theQuestionnaire, errMessOut] return [theProject, theQuestionnaire, errMessOut] def getSessionQuestionnaireProject(request): """Retrieve a Project and Questionnaire object from session data. Use database query to update the object. Args: "request" input Returns: return_value: html. Raises: None. """ if 'theProject' in request.session: projRecNo = request.session['theProject'] try: # update the object by querying the database theProject = Project.objects.get(id= projRecNo) except Project.DoesNotExist: theProject = None else: theProject = None if 'theQuestionnaire' in request.session: questRecNo = request.session['theQuestionnaire'] try: theQuestionnaire = Questionnaire.objects.get(id= questRecNo) except Questionnaire.DoesNotExist: theQuestionnaire = None else: theQuestionnaire = None return [theProject, theQuestionnaire ] def displayQuestionnairesAndProjectsRetrieve(allQuestionnaireInfo, listRecNum): """Return the Project and Questionnaire objects, given the record number of the list row selection as displayed to the user. Display list is formatted in function displayQuestionnairesAndProjects. Project may not always exist. Args: listRecNum, integer (first row is a text "1") of row in list displayed to the user. Returns: ProjectObj, QuestionnaireObj: objects referenced in the list row. """ DebugOut('displayQuestionnairesAndProjectsRetrieve enter') DebugOut('listRecNum %s' %listRecNum) recNum = int(listRecNum) - 1 # start with zero theProjectIDinDB = allQuestionnaireInfo[recNum][-2] # is the record number for the project theQuestIDinDB = allQuestionnaireInfo[recNum][-1] # is the record number for the questionnaire DebugOut('theProjectIDinDB %s' %theProjectIDinDB) theQuestionnaire = Questionnaire.objects.get(id=theQuestIDinDB) DebugOut('theQuestionnaire %s' %theQuestionnaire) if theProjectIDinDB: # project may not exist theProject = Project.objects.get(id=theProjectIDinDB) else: theProject = Project.objects.none() DebugOut('displayQuestionnairesAndProjectsRetrieve exit') return [theProject, theQuestionnaire] def displayProjectsWithinScope(): """Prepare a list for display of all Projects within scope """ DebugOut('displayProjectsWithinScope: enter') allProjectObjs = getAllProjectsWithinScope() allProjectInfo = [] for aProject in allProjectObjs: allProjectInfo.append([ aProject.shortTag, aProject.name, aProject.email, aProject.projectAddress, aProject.contactPhone, aProject.internetLocation, aProject.id, ]) # record structure # [ Project short tag, name, email, projectAddress, contactPhone, internetLocation, # record number in the Project table ] DebugOut('displayProjectsWithinScope: exit') return allProjectInfo # list def displayQuestionnairesAndProjects(limitScope, limitProjectView, thisProject): """Prepare a list for display of all active questionnaires and the corresponding project. Args: limitScope: True if ProjectAttributes is to be consulted for permission to display. limitProjectView: True if list contains only the Questionnaires from thisProject thisProject: "None" displays all projects permitted, otherwise only the specific project is displayed. """ DebugOut('displayQuestionnairesAndProjects: enter') if not limitScope: # unlimited scope. Display all allProjects = getAllProjects() else: # limited scope, Display Projects permitted by ProjectAttributes allProjects = getAllProjectsWithinScope() # further reduce the scope. if limitProjectView: # limit Questionnaires only in thisProject allProjects = Project.objects.filter(id=thisProject.id) allQuestionnaireInfo = [] for aProject in allProjects: allQuestionnaires = getQuestionnaireObjsForProject(aProject) for aQuest in allQuestionnaires: # get info about the Questionnaire questionnaireStatus = getQuestionnaireStatusValue(aProject, aQuest) #DebugOut('Status for questionnaire %s is %s.' %(aQuest.shortTag,questionnaireStatus)) spTag = aProject.shortTag spRec = aProject.id allQuestionnaireInfo.append([ aQuest.shortTag, # 0 aQuest.pageTitle, # 1 aQuest.description, # 2 aQuest.version, # 3 aQuest.versionDate, # 4 aQuest.lastUpdate, # 5 questionnaireStatus, # 6 aQuest.language, # 7 spTag, # 8 spRec, # 9 aQuest.id # 10 ]) # record structure # [ questionnaire short tag, Page Title, Description, Version, Version Date, # Last Update, Enabled/Disabled, Language, Project, record number in Questionnaire DebugOut('displayQuestionnairesAndProjects: exit') return allQuestionnaireInfo # list @login_required() def deleteQuestionnaireView(request): """Delete a Questionnaire. This function displays a list of Questionnaires and Projects for the user to select for deletion. If a Submission exists which points to this record, no deletion actually occurs. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('deleteQuestionnaireView: enter') limitScope = True # limit view of Projects to those permitted by PorjectAttributes # find if default project has been set in the database theUser = request.user theUserDefaultProject = getAssociatedProjectForUser(theUser) limitProjectView = getSessionLimitViewProjectSetting(request) currentProjectDefault = theUserDefaultProject if limitProjectView: # limit the view to the current project if not currentProjectDefault: # Project default not actually set in database DebugOut('Current project not defined.') limitProjectView = False # Current project not defined, so do not limit scope else: DebugOut('currentProjectDefault: %s' %currentProjectDefault.shortTag) limitProjectView = True # redundant else: DebugOut('limitProjectView: is false, therefore send flag to displayQuestionnairesAndProjects') currentProjectDefault = theUserDefaultProject errMsg = [] if request.method == 'POST': DebugOut('after POST') if 'SelectQuestionnaire' in request.POST: # Default questionnaire selected. It may be different than current working questionnaire allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, currentProjectDefault) # this is the list the user is looking at [dummyText, listRecNum] = request.POST['SelectQuestionnaire'].split(" ") # format is "Select" "record number in display list" [theProject, theQuestionnaire] = displayQuestionnairesAndProjectsRetrieve(allQuestionnaireInfo, listRecNum) workingQuestionnaireTag = theQuestionnaire.shortTag DebugOut('new default questionnaire selected %s' %workingQuestionnaireTag) setSessionQuestionnaireProject(request, theProject, theQuestionnaire) request.session['delete_QandS'] = [theProject.id, theQuestionnaire.id] # force a second stage for deletion. questName = theQuestionnaire.pageTitle firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageInQuestTag = firstPageObj.shortTag else: firstPageInQuestTag = '' barTitle=theQuestionnaire.barTitle language=theQuestionnaire.language elif 'DeleteQuestionnaire' in request.POST: # delete questionnaire DebugOut('after DeleteQuestionnaire') # retrieve previous selection, if any if 'delete_QandS' in request.session: # then set [theProjectid, theQuestionnaireid] = request.session['delete_QandS'] theProject = Project.objects.get(id=theProjectid) theQuestionnaire = Questionnaire.objects.get(id=theQuestionnaireid) [deleteSuccess, errMsg] = deleteQuestionnaireInDB(theQuestionnaire) # Performs delete with additional logic del request.session['delete_QandS'] # No defaults # Must select a questionnaire! workingQuestionnaireTag = '' # no longer exists questName = '' firstPageInQuestTag = '' barTitle = '' language = '' allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, currentProjectDefault) # display new list elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, currentProjectDefault) # this is the list the user is looking at if 'delete_QandS' in request.session: # then set [theProjectid, theQuestionnaireid] = request.session['delete_QandS'] theProject = Project.objects.get(id=theProjectid) theQuestionnaire = Questionnaire.objects.get(id=theQuestionnaireid) # verify that the questionnaire exists in the database. workingQuestionnaireTag = theQuestionnaire.shortTag questName = theQuestionnaire.pageTitle firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageInQuestTag = firstPageObj.shortTag else: firstPageInQuestTag = '' barTitle=theQuestionnaire.barTitle language=theQuestionnaire.language else: workingQuestionnaireTag = '' # no longer exists questName = '' firstPageInQuestTag = '' barTitle = '' language = '' currentContext = { 'workingQuestionnaireTag' : workingQuestionnaireTag, 'allQuestionnaireInfo' : allQuestionnaireInfo, 'allowToggleEnable' : False, 'questName' : questName, 'firstPageInQuestTag' : firstPageInQuestTag, 'barTitle' : barTitle, 'language' : language, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, 'errMsg' : errMsg, } currentContext.update(csrf(request)) DebugOut('deleteQuestionnaireView: exit') return render(request, workingPageTemplateRoot + 'deleteQuestionnaireView.html', currentContext) def duplicateQuestionnaireView(request): """Select a Questionnaire from a list for duplication. Only Questionnaires in the default Project are listed. """ # retrieve from session data. DebugOut('duplicateQuestionnaireView: enter') limitScope = True # limit view of Projects to those permitted by ProjectAttributes limitProjectView = True # limit view of Questionnaires to those belonging to the current project # find if default project has been set in the database [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) theUser = request.user if not theProject: theProject = getAssociatedProjectForUser(theUser) if not theProject: # select a project. DebugOut('The Project has not been selected') errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) theProjectTag = theProject.shortTag # prepare a list for display of all questionnaires for the project errMsg = [] if request.method == 'POST': allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, theProject) if 'SelectQuestionnaire' in request.POST: DebugOut('SelectQuestionnaire button') [dummyText, recNum] = request.POST['SelectQuestionnaire'].split(" ") # format is "Select" "record number" recNum = int(recNum) - 1 # start with zero workingQuestionnaireTag = allQuestionnaireInfo[recNum][0] # see function workingQuestionnaireRecInDB = allQuestionnaireInfo[recNum][-1] # last element is the record number for the questionnaire duplicateThisQuestionnaire = Questionnaire.objects.get(id=workingQuestionnaireRecInDB) errMsg.append('Selected Questionnaire: %s' %workingQuestionnaireTag) # Before creation generate a unique name DebugOut('Start name: %s'%workingQuestionnaireTag) maxLength = 30 # maximum length of a Questionnaire shortTag. existingQuestionnaireTags = getQuestionnaireTagsForProject(theProject) theNewName = makeUniqueTag( existingQuestionnaireTags, workingQuestionnaireTag, maxLength) DebugOut('Updated name: %s'%theNewName) newQuestionnaire = duplicateQuestionnaire( theProject, duplicateThisQuestionnaire, theNewName) # update the list with the new Questionnaire allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, theProject) if newQuestionnaire: DebugOut('The duplicated Questionnaire name is: %s'%newQuestionnaire.shortTag) elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView,theProject) newQuestionnaire = None # no questionnaire duplicated debugOn = settings.DEBUG currentContext = { 'allQuestionnaireInfo' : allQuestionnaireInfo, 'newQuestionnaire' : newQuestionnaire, 'allowToggleEnable' : False, 'theUser' : theUser, 'limitProjectView' : True, 'theProject' : theProject, 'debugOn' : debugOn, 'url_base' : url_base, 'errMsg' : errMsg, } DebugOut('duplicateQuestionnaireView: exit') return render(request, workingPageTemplateRoot + 'duplicateQuestionnaireView.html', currentContext) def selectProjectsQuestionnairesToExecute(request): """Select a Questionnaire and Project from a list for default reference when editing. # might be obselete *** This function displays a list Args: "request" input Returns: return_value: html. Raises: None. """ # retrieve from session data. DebugOut('selectProjectsQuestionnairesToExecute: enter') limitScope = True # limit view of Projects to those permitted by ProjectAttributes # find if default project has been set in the database theUser = request.user theUserDefaultProject = getAssociatedProjectForUser(theUser) limitProjectView = getSessionLimitViewProjectSetting(request) #limit questionnaire list to default project currentProjectDefault = theUserDefaultProject if limitProjectView: # limit the view to the current project if not currentProjectDefault: # Project default not actually set in database DebugOut('Current project not defined.') limitProjectView = False # Current project not defined, so do not limit scope else: DebugOut('currentProjectDefault: %s' %currentProjectDefault.shortTag) limitProjectView = True # redundant else: DebugOut('limitProjectView: is false, therefore send flag to displayQuestionnairesAndProjects') currentProjectDefault = theUserDefaultProject # prepare a list for display of all active questionnaires and the project errMsg = [] if request.method == 'POST': # prepare a list for display of all active questionnaires and the project allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, currentProjectDefault) if 'SelectQuestionnaire' in request.POST: DebugOut('SelectQuestionnaire button') [dummyText, recNum] = request.POST['SelectQuestionnaire'].split(" ") # format is "Select" "record number" recNum = int(recNum) - 1 # start with zero workingQuestionnaireTag = allQuestionnaireInfo[recNum][0] # see function workingProjectTag = allQuestionnaireInfo[recNum][8] # see function if not workingProjectTag: # if project is not specified errMsg.append('Please add a project to "%s" before executing the questionnaire.' %workingQuestionnaireTag) workingProjectRec = allQuestionnaireInfo[recNum][9] # see function theProject = Project.objects.get(id=workingProjectRec) workingProjectTag = theProject.shortTag # should be the same! theRecInDB = allQuestionnaireInfo[recNum][-1] # last element is the record number for the questionnaire theQuestionnaire = Questionnaire.objects.get(id=theRecInDB) if getQuestionnaireStatusValue(theProject,theQuestionnaire) != 'enabled': errMsg.append('Please enable "%s" before executing the questionnaire.' %workingQuestionnaireTag) enabledFlag = False else: enabledFlag = True if workingProjectTag and enabledFlag: # two conditions required for executing the questionnaire # set defaults in session data # prepare Session Data environment for running the questionnaire removeResponsesFromSessionData(request) DebugOut('Removed Response data from Session Data') questionnaireEnvironmentPrep( request, theProject, theQuestionnaire) urltogo = questionnaireToGo(request, theProject, theQuestionnaire) return HttpResponseRedirect(urltogo) # next screen url elif 'ToggleDisable' in request.POST: # toggle the enable/disable flag for the selected questionnaire toggleSelectText = request.POST['ToggleDisable'] [toggleValue,theRecText]=toggleSelectText.split("_") theRecInList = int(theRecText)-1 theRecInDB = allQuestionnaireInfo[theRecInList][-1] # last element is the record number theQuestionnaire = Questionnaire.objects.get(id=theRecInDB) if toggleValue == 'enabled': setEnabledFlag = 'disabled' elif toggleValue == 'disabled': setEnabledFlag = 'enabled' else: # error none of the above, so enable setEnabledFlag = 'enabled' theProject = getProjectObjForQuestionnaire( theQuestionnaire) setQuestionnaireStatusValue(theProject, theQuestionnaire, setEnabledFlag) currentProjectDefault = theProject allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, currentProjectDefault) # refresh elif 'limitProjectViewSelection' in request.POST: DebugOut('In limitProjectViewSelection') limitProjectView = getSessionLimitViewProjectSetting(request) # toggle if limitProjectView: limitProjectView = False else: limitProjectView = True setSessionLimitViewProjectSetting(request, limitProjectView) # save the new value allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, currentProjectDefault) # refresh elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView,currentProjectDefault) thisHost = request.get_host() debugOn = settings.DEBUG currentContext = { 'allQuestionnaireInfo' : allQuestionnaireInfo, 'allowToggleEnable' : True, 'theUser' : theUser, 'limitProjectView' : limitProjectView, 'currentProjectDefault' : currentProjectDefault, 'debugOn' : debugOn, 'thisHost' : thisHost, 'url_base' : url_base, 'errMsg' : errMsg, } currentContext.update(csrf(request)) DebugOut('selectProjectsQuestionnairesToExecute: exit') return render(request, workingPageTemplateRoot + 'selectProjectsQuestionnairesToExecute.html', currentContext) def simplyExecuteTheQuestionnaire(request): """Run the default questionnaire. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('simplyExecuteTheQuestionnaire: enter') limitScope = True # limit view of Projects to those permitted by PorjectAttributes # prepare a list for display of all active questionnaires and the project [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] return render(request, 'system_error.html', { 'syserrmsg': errMsg}) workingQuestionnaireTag = theQuestionnaire.shortTag if theProject: workingProjectTag = theProject.shortTag else: workingProjectTag = '' errMsg = [] limitProjectView = False # does not matter since list is not displayed if request.method == 'POST': DebugOut('after POST') # prepare a list for display of all active questionnaires and the project allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, None) if 'runQuestionnaire' in request.POST: if not workingProjectTag: # if project is not specified errMsg.append('Please add a project to "%s" before executing the questionnaire.' %workingQuestionnaireTag) if getQuestionnaireStatusValue(theProject,theQuestionnaire) != 'enabled': errMsg.append('Please enable "%s" before executing the questionnaire.' %workingQuestionnaireTag) enabledFlag = False else: enabledFlag = True if workingProjectTag and enabledFlag: # two conditions required for executing the questionnaire # set defaults in session data # prepare Session Data environment for running the questionnaire removeResponsesFromSessionData(request) DebugOut('Removed previous Response data from Session Data') urltogo = questionnaireToGo(request, theProject, theQuestionnaire) DebugOut('Run Questionnaire %s' %workingQuestionnaireTag) return HttpResponseRedirect(urltogo) # next screen url elif 'ToggleDisable' in request.POST: # toggle the enable/disable flag for the selected questionnaire toggleValue = request.POST['ToggleDisable'] if toggleValue == 'enabled': setEnabledFlag = 'disabled' elif toggleValue == 'disabled': setEnabledFlag = 'enabled' else: # error none of the above, so enable setEnabledFlag = 'enabled' setQuestionnaireStatusValue(theProject, theQuestionnaire, setEnabledFlag) # Display questionnaire information pageTitle = theQuestionnaire.pageTitle pageSubTitle = theQuestionnaire.pageSubTitle description = theQuestionnaire.description footerText = theQuestionnaire.footerText version = theQuestionnaire.version versionDate = theQuestionnaire.versionDate lastUpdate = theQuestionnaire.lastUpdate questEnabled = getQuestionnaireStatusValue(theProject,theQuestionnaire) language = theQuestionnaire.language firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageTag = firstPageObj.shortTag else: firstPageTag = '' thisHost = request.get_host() currentContext = { 'workingQuestionnaireTag' : workingQuestionnaireTag, 'workingProjectTag' : workingProjectTag, 'allowToggleEnable' : True, 'thisHost' : thisHost, 'pageTitle' : pageTitle, 'pageSubTitle' : pageSubTitle, 'description' : description, 'footerText' : footerText, 'version' : version, 'versionDate' : str(versionDate), 'lastUpdate' : str(lastUpdate), 'questEnabled' : questEnabled, 'language' : language, 'firstPageTag' : firstPageTag, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, 'errMsg' : errMsg, } currentContext.update(csrf(request)) DebugOut('simplyExecuteTheQuestionnaire: exit') return render(request, workingPageTemplateRoot + 'simplyExecuteTheQuestionnaire.html', currentContext) def restartSession(request,whichProject,whichQuestionnaire): """ Allow urls of the type /project/questionnaire to get to the start page of the questionnaire. """ DebugOut('restartSession: called when clicking Back to splash') DebugOut('whichProject %s, whichQuestionnaire %s' %(whichProject,whichQuestionnaire)) # Standard verification w.r.t. project and questionnaire [theProject, theQuestionnaire, errMess] = verifyQuestionnaireProject(request, whichProject, whichQuestionnaire) if errMess != []: DebugOut('test %s' %str(errMess)) # last ditch effort. theProject = getProjectObj( whichProject) # query the database theQuestionnaire = getQuestionnaireObjFromTags(whichProject, whichQuestionnaire) if not theProject or not theQuestionnaire: return selectProjectsQuestionnairesToExecute(request) # set up environment removeResponsesFromSessionData(request) # remove detritus DebugOut('Removed Response data from Session Data') urltogo = questionnaireToGo(request, theProject, theQuestionnaire) DebugOut('restartSession: exit. Calling start page') return HttpResponseRedirect(urltogo) # next screen url @login_required() def selectQuestionnaireDefault(request): """Select a Questionnaire within scope of the Project as Session Data default. """ DebugOut('selectQuestionnaireDefault: enter') errMsg = [] # select a default Questionnaire and Project tag to start. [workingProject, workingQuestionnaire] = getSessionQuestionnaireProject(request) if not workingProject: # select a project. errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) allQuestionnaires = getQuestionnaireObjsForProject(workingProject) if request.method == 'POST': # Default project selected. if 'SelectQuestionnaire' in request.POST: [dummyText, listRecNum] = request.POST['SelectQuestionnaire'].split(" ") #decode the response # format is "Select" "record number in display list" recNum = int(listRecNum) - 1 # start with zero theQuestionnaire = allQuestionnaires[recNum] setSessionQuestionnaire(request, theQuestionnaire) redirectURL = registrationURL_base + 'userLanding/' return HttpResponseRedirect(redirectURL) elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) currentContext = { 'allQuestionnaires' : allQuestionnaires, 'workingProject' : workingProject, 'url_base' : url_base, 'errMsg' : errMsg, } currentContext.update(csrf(request)) DebugOut('selectQuestionnaireDefault: exit') return render(request, 'registration/selectQuestionnaireDefault.html', currentContext) def setSessionProjectQuestionnaireDefault(request): """Select a Questionnaire and Project as Session Data default. This function displays a list of Questionnaires and Projects for the user to select as a default. "Default" means that the identities of the Questionnaire and Project are saved in Session Data for later retrieval during the life of the Session. Args: "request" input Returns: return_value: html. Session Data: Sets session data with function setSessionQuestionnaireProject. Raises: None. """ DebugOut('setSessionProjectQuestionnaireDefault: enter') limitScope = True # limit view of Projects to those permitted by PorjectAttributes limitProjectView = False # do not limit scope to current default project errMsg = [] if request.method == 'POST': DebugOut('after POST') if 'SelectQuestionnaire' in request.POST: DebugOut('after SelectQuestionnaire') # Default questionnaire selected. It may be different than current working questionnaire allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, None) # generate the list for the user to view [dummyText, listRecNum] = request.POST['SelectQuestionnaire'].split(" ") #decode the response # format is "Select" "record number in display list" [theProject, theQuestionnaire] = displayQuestionnairesAndProjectsRetrieve(allQuestionnaireInfo, listRecNum) workingQuestionnaireTag = theQuestionnaire.shortTag setSessionQuestionnaire(request, theQuestionnaire) errMsg.append('The default Questionnaire selected: %s' %workingQuestionnaireTag) if theProject: workingProjectTag = theProject.shortTag errMsg.append('The default Project selected: %s' %workingProjectTag) setSessionProject(request, theProject) else: workingProjectTag = '' errMsg.append('A Project has not been assigned to this questionnaire.') removeResponsesFromSessionData(request) # remove previous questionnaire responses # prepare environment pageBaseURL = questionnaireEnvironmentPrep( request, theProject, theQuestionnaire) DebugOut('questionnaireEnvironmentPrep called') questName = theQuestionnaire.pageTitle firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageInQuestTag = firstPageObj.shortTag else: firstPageInQuestTag = '' barTitle=theQuestionnaire.barTitle language=theQuestionnaire.language elif 'returnToHome' in request.POST: # return to Home Page redirectURL = registrationURL_base + 'userLanding/' return HttpResponseRedirect(redirectURL) else: # not a POST allQuestionnaireInfo = displayQuestionnairesAndProjects(limitScope, limitProjectView, None) # this is the list the user is looking at [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) if theProject: workingProjectTag = theProject.shortTag else: workingProjectTag = '' if theQuestionnaire: # then set project and questionnaire objects workingQuestionnaireTag = theQuestionnaire.shortTag questName = theQuestionnaire.pageTitle firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageInQuestTag = firstPageObj.shortTag else: firstPageInQuestTag = '' barTitle=theQuestionnaire.barTitle language=theQuestionnaire.language else: workingQuestionnaireTag = '' # no longer exists questName = '' firstPageInQuestTag = '' barTitle = '' language = '' currentContext = { 'workingQuestionnaireTag' : workingQuestionnaireTag, 'workingProjectTag' : workingProjectTag, 'allQuestionnaireInfo' : allQuestionnaireInfo, 'allowToggleEnable' : False, 'questName' : questName, 'firstPageInQuestTag' : firstPageInQuestTag, 'barTitle' : barTitle, 'language' : language, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, 'errMsg' : errMsg, } currentContext.update(csrf(request)) DebugOut('setSessionProjectQuestionnaireDefault: exit') return render(request, workingPageTemplateRoot + 'setSessionProjectQuestionnaireDefault.html', currentContext) @login_required() def editDefaultPageTransitions(request): """Shuffle page order within a Questionnaire. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('editDefaultPageTransitions: enter') errMsg = [] [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) DebugOut('Project: %s, Questionnaire: %s' %(theProject, theQuestionnaire)) if not theProject: # select a project. DebugOut('The Project has not been selected') errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) theProjectTag = theProject.shortTag if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) workingQuestionnaireTag = theQuestionnaire.shortTag # Will be problems if no pages. pagesTF = testForPages(theQuestionnaire) if not pagesTF: errMsg.append('This questionnaire has no associated pages') if request.method == 'POST': DebugOut('after POST') theForm = editDefaultTransitions(request.POST) if 'acceptEdits' in request.POST: # accept page transition DebugOut('after submitButton') if theForm.is_valid(): DebugOut('Form is valid') cleanedData = theForm.cleaned_data DebugOut('Cleaned data: %s' %cleanedData) # save ptl list separately savePTL = cleanedData['ptlString'] # edits submitted # maintain uniqueness of Questionnaire shortTag # set the new ptl whether edited or not DebugOut('savePTL: %s' %savePTL) [tagsMissing, tagsAdded] = savePTLToDB(theQuestionnaire, savePTL) # if errors, do not save! DebugOut('tagsMissing: %s' %str(tagsMissing)) if tagsMissing: errMsg.append('The following Pages in the Questionnaire were not found in the entered transition table.') for aTag in tagsMissing: errMsg.append(aTag) errMsg.append('Correct this error by adding them to the transition table.') errMsg.append('All Pages in the Questionnaire must have a place in the transition table.') if tagsAdded: errMsg.append('The following Page tags are not in the Questionnaire.') for aTag in tagsAdded: errMsg.append(aTag) errMsg.append('Correct this error by removing new pages from the transition table:') errMsg.append('New Pages cannot be added here.') if errMsg: # any errors, do not save the transition table errMsg.append('The Page transition table is unchanged') errMsg.append('Try again with another edit to the page transition table') theForm = editDefaultTransitions(cleanedData) else: # no errors, update the transition table display to the user defaultPTDict = getPageToPageShortTags( theQuestionnaire ) # returns as Dictionary! defaultPTString = transitionMatrixToMultiLineDisplay(defaultPTDict) DebugOut('No errors, so update defaultPTString: %s' %defaultPTString) fieldValueDict = {'ptlString' : defaultPTString} errMsg.append('Transition matrix updated.') theForm = editDefaultTransitions(initial=fieldValueDict) else: pass #Form data is not valid DebugOut('Form data is not valid') elif 'startPage' in request.POST: # accept new start page DebugOut('after startPage') startPageTag = request.POST['startPage'] [pageTagToRecord, recordToPageTag ] = getPageToRecordMapping(theQuestionnaire) # returns two dictionaries DebugOut('pageTagToRecord: %s' %str(pageTagToRecord)) # try: startPageObj = Page.objects.get(id=pageTagToRecord[startPageTag]) errMsg.append('Start page "%s" selected.' %startPageTag) # update or create the start page record setStartPageObj(theQuestionnaire, startPageObj) # except: # DebugOut('syserrmsg: Not able to select start page') elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) elif 'executeQuestionnaire' in request.POST: redirectURL = url_base + theProjectTag + '/' + workingQuestionnaireTag return HttpResponseRedirect(redirectURL) else: pass #Unknown button hit DebugOut('syserrmsg: Unknown button hit') DebugOut('request.POST') DebugOut(str(request.POST)) else: # GET DebugOut('after GET') # retrieve from the db the transition matrix between pages defaultPTDict = getPageToPageShortTags( theQuestionnaire ) # returns as Dictionary! defaultPTString = transitionMatrixToMultiLineDisplay(defaultPTDict) DebugOut('defaultPTString: %s' %defaultPTString) fieldValueDict = {'ptlString' : defaultPTString} DebugOut('after GET, fieldValueDict: %s' %fieldValueDict) theForm = editDefaultTransitions(initial=fieldValueDict) defaultPT = getDefaultPageTransitions( theQuestionnaire) # as transition list # defaultPT is a 2D List of strings - shortTags if not defaultPT: DebugOut('defaultPT is blank') errMsg.append('The page transition matrix does not exist for this questionnaire.') questName = theQuestionnaire.pageTitle firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageInQuestTag = firstPageObj.shortTag else: firstPageInQuestTag = '' [pageTagToRecord, recordToPageTag ] = getPageToRecordMapping(theQuestionnaire) # returns two dictionaries allPageTags = pageTagToRecord.keys() barTitle=theQuestionnaire.barTitle language=theQuestionnaire.language # getFirstPageObj currentContext = { 'theForm' : theForm, 'defaultPT' : defaultPT, # from/to pairs 'workingQuestionnaireTag' : workingQuestionnaireTag, 'theProjectTag' : theProjectTag, 'allPageTags' : allPageTags, 'questName' : questName, 'firstPageInQuestTag' : firstPageInQuestTag, 'barTitle' : barTitle, 'language' : language, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, 'errMsg' : errMsg, } DebugOut('editDefaultPageTransitions: exit') return render(request, workingPageTemplateRoot + 'editDefaultPageTransitions.html', currentContext) @login_required() def editQuestionnaire(request): """Create a new Questionnaire, or edit an existing Questionnaire. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('editQuestionnaire: enter') errMsg = [] [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) workingQuestionnaireTag = theQuestionnaire.shortTag if not theProject: # select a project. errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) theProjectTag = theProject.shortTag # May be problems if no pages. pagesTF = testForPages(theQuestionnaire) if not pagesTF: errMsg.append('This questionnaire has no associated pages') if request.method == 'POST': DebugOut('after POST') # DebugOut('request.POST: %s'%request.POST) if 'acceptEdits' in request.POST: # accept questionnaire edits DebugOut('after submitButton') theForm = editQuestionnaireForm(request.POST) if theForm.is_valid(): DebugOut('Form is valid') # check if project change selected. if 'ProjectSelect' in request.POST: newProjectTag = request.POST['ProjectSelect'] DebugOut('newProjectTag: %s'%newProjectTag) newProjectObj = getProjectObj( newProjectTag) setSessionProject(request, newProjectObj) setProjectForQuestionnaire(newProjectObj, theQuestionnaire) theProject=newProjectObj theProjectTag=newProjectTag # check the questionnaire tag for identity with an existing tag cleanedData = theForm.cleaned_data DebugOut('Cleaned data: %s' %cleanedData) cleanedData['versionDate'] = str(cleanedData['versionDate']) request.session['editQuestionnaireForm'] = cleanedData # save cleaned data # edits submitted tempShortTag = cleanedData['shortTag'] # must be unchanged or different from the remainder # maintain uniqueness of Questionnaire shortTag questTags = getQuestionnaireTagsForProject(theProject) workingQuestionnaireTag = theQuestionnaire.shortTag # from database if tempShortTag == workingQuestionnaireTag: # same record - tag unchanged DebugOut('tag is unchanged') theQuestionnaire = updateQuestionnaireObj( theQuestionnaire, cleanedData ) # update the record theQuestionnaire.save() # update the questionnaire record # saveQuestionnaireObj( theQuestionnaire) # test for Submission against Questionnaire elif tempShortTag in questTags: DebugOut('Another existing tag selected. No no! Will overwrite') # Selected a different existing tag for editing. errMsg.append('Questionnaire name %s is identical to an existing Questionnaire.' %stempShortTag) errMsg.append('Delete the other Questionnaire first.') errMsg.append('Questionnaires %s and %s are untouched.' %(workingQuestionnaireTag,tempShortTag)) else: # tag is different from any existing tag. DebugOut('tag is different') theQuestionnaire = updateQuestionnaireObj( theQuestionnaire, cleanedData ) # update the record theQuestionnaire.save() # update the questionnaire record errMsg.append('Questionnaire %s has been updated.' %tempShortTag) DebugOut('Time field in object: %s' %str(theQuestionnaire.versionDate)) workingQuestionnaireTag = tempShortTag theForm = editQuestionnaireForm(cleanedData) else: pass #Form data is not valid DebugOut('Form data is not valid') elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: pass #Unknown button hit DebugOut('syserrmsg: Unknown button hit') DebugOut('request.POST') DebugOut(str(request.POST)) else: # GET DebugOut('after GET') # retrieve from the database fieldValueDict = questionnaireOutput( theQuestionnaire ) DebugOut('after GET, fieldValueDict: %s' %fieldValueDict) # Dates cannot be saved to session data, therefore make into a string # delete the "lastUpdate" tag del fieldValueDict['lastUpdate'] fieldValueDict['versionDate'] = str(fieldValueDict['versionDate']) fieldValueDict['imageFilePath'] = str(fieldValueDict['imageFilePath']) theForm = editQuestionnaireForm(initial=fieldValueDict) request.session['editQuestionnaireForm'] = fieldValueDict questName = theQuestionnaire.pageTitle firstPageInQuestTag = getStartPageObj(theQuestionnaire).shortTag barTitle=theQuestionnaire.barTitle language=theQuestionnaire.language questTags = getQuestionnaireTagsForProject(theProject) questTagsList = ', '.join(questTags) allProjectTags = getAllProjectTags() currentContext = { 'theForm' : theForm, 'questTagsList' : questTagsList, 'theProjectTag' : theProjectTag, 'allProjectTags' : allProjectTags, 'workingQuestionnaireTag' : workingQuestionnaireTag, 'questName' : questName, 'firstPageInQuestTag' : firstPageInQuestTag, 'barTitle' : barTitle, 'language' : language, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, 'errMsg' : errMsg, } DebugOut('editQuestionnaire: exit') return render(request, workingPageTemplateRoot + 'editQuestionnaire.html', currentContext) @login_required() def bulkQuestionEdit(request): """Edit existing questions. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('bulkQuestionEdit: enter') errMsg = [] # get default Project and Questionnaire [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) DebugOut('Project: %s, Questionnaire: %s' %(theProject, theQuestionnaire)) if not theProject: # select a project. DebugOut('The Project has not been selected') errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) theProjectTag = theProject.shortTag if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # must have pages associated with the Questionnaire to do anything. pagesTF = testForPages(theQuestionnaire) if not pagesTF: errMsg.append('The questionnaire has no associated pages.') return render(request, 'system_error.html', { 'syserrmsg': errMsg}) # and the pages must have questions allQuestions = getAllQuestionObjsForQuestionnaire(theQuestionnaire) if allQuestions.count() == 0: errMsg.append('The questionnaire has no associated Questions.') return render(request, 'system_error.html', { 'syserrmsg': errMsg}) # questionnaire information firstPageObj = getStartPageObj(theQuestionnaire) firstPageInQuestTag = firstPageObj.shortTag # retrieve current page, if any if 'currentPageTag_bulkPageEdit' in request.session: thisPageObjid = request.session['currentPageTag_bulkPageEdit'] thisPageObj = Page.objects.get(id=thisPageObjid) else: thisPageObj = firstPageObj # Update form with questions thePageQuestions = getPageQuestions(thisPageObj) initialValues = [] for aQuestion in thePageQuestions: theQRespType = aQuestion.responseType theQTag = aQuestion.questionTag theQText = aQuestion.questionText # allow html initialValues.update({theQTag : theQText}) theQuestionForm = BulkQuestionEditForm(initial=initialValues, questions=thePageQuestions) if request.method == 'POST': DebugOut('after POST') if 'acceptQuestionEdits' in request.POST: theQuestionForm = BulkQuestionEditForm(request.POST, questions=thePageQuestions) if theQuestionForm.is_valid(): DebugOut('after theQuestionForm.is_valid') # check the question tag for identity with an existing tag cleanedData = theQuestionForm.cleaned_data DebugOut('Cleaned data: %s' %cleanedData) # Update the Question record. for theQuestion in thePageQuestions: [aQuestion, isQuestionUpdated] = updateObjFields(theQuestion,cleanedData) if isQuestionUpdated: # so update DebugOut('Question updated %s' %theQuestion.shortTag) # aQuestion.save() # debugxx elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: DebugOut('syserrmsg: bulkQuestionEdit: unknown button option') errMsg.append('bulkQuestionEdit: unknown button option') currentContext = { 'questionDescription' : 'Good question', } DebugOut('bulkQuestionEdit: exit') return render(request, 'working_pages/bulkPageEdit.html', currentContext) @login_required() def bulkPageEdit(request): """Edit existing pages. Args: "request" input Returns: return_value: html. Raises: None. """ DebugOut('bulkPageEdit: enter') errMsg = [] infoMsg = [] hasEdits = False # no edits yet # get default Project and Questionnaire [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) DebugOut('Project: %s, Questionnaire: %s' %(theProject, theQuestionnaire)) if not theProject: # select a project. DebugOut('The Project has not been selected') errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # must have pages associated with the Questionnaire to do anything. pagesTF = testForPages(theQuestionnaire) if not pagesTF: errMsg.append('The questionnaire has no associated pages.') return render(request, 'system_error.html', { 'syserrmsg': errMsg}) # questionnaire information firstPageObj = getStartPageObj(theQuestionnaire) firstPageInQuestTag = firstPageObj.shortTag language=theQuestionnaire.language # retrieve current page, if any if 'currentPageTag_bulkPageEdit' in request.session: thisPageObjid = request.session['currentPageTag_bulkPageEdit'] try: thisPageObj = Page.objects.get(id=thisPageObjid) except Page.DoesNotExist: thisPageObj = firstPageObj else: thisPageObj = firstPageObj # Make sure this page is part of the project! Might have switched questionnaires allPages = getAllPageObjsForQuestionnaire(theQuestionnaire) allPageTags = [ap.shortTag for ap in allPages] if thisPageObj not in allPages: thisPageObj = firstPageObj # choose the first page not legal. Should not happen! initialValues ={ # for forms initial data 'pageTitle' : theQuestionnaire.pageTitle, 'pageSubTitle' : theQuestionnaire.pageSubTitle, 'description' : thisPageObj.description, 'explanation' : thisPageObj.explanation, 'prologue' : thisPageObj.prologue, 'epilogue' : thisPageObj.epilogue, } # Update form with questions thePageQuestions = getPageQuestions(thisPageObj) # add a blank question to the list thePageQuestions.append(Question()) thePageForm = BulkPageEditForm(initial=initialValues, questions=thePageQuestions) theResponseChoices = getResponseChoicesForAPage(thisPageObj) if request.method == 'POST': DebugOut('after POST') #DebugOut('request.POST %s'%request.POST) if 'acceptPageEdits' in request.POST: DebugOut('after accept Page Edits') thePageForm = BulkPageEditForm(request.POST, questions=thePageQuestions) if thePageForm.is_valid(): DebugOut('after thePageForm.is_valid') # check the question tag for identity with an existing tag cleanedData = thePageForm.cleaned_data #DebugOut('Cleaned data: %s' %cleanedData) # check the page record and all questions isPageUpdated = False if thisPageObj.description != cleanedData['description']: thisPageObj.description = cleanedData['description'] isPageUpdated = True if thisPageObj.explanation != cleanedData['explanation']: thisPageObj.explanation = cleanedData['explanation'] isPageUpdated = True if thisPageObj.prologue != cleanedData['prologue']: thisPageObj.prologue = cleanedData['prologue'] isPageUpdated = True if thisPageObj.epilogue != cleanedData['epilogue']: thisPageObj.epilogue = cleanedData['epilogue'] isPageUpdated = True if isPageUpdated: # so update the Page record if thisPageObj.shortTag == '': # Invent a name of the name is null in the object (may or may not be saved) newShortTag = 'Page' maxLength = 30 newUniqueName = makeUniqueTag( allPageTags, newShortTag, maxLength) thisPageObj.shortTag = newUniqueName DebugOut('Page updated %s' %thisPageObj.shortTag) infoMsg.append('Page updated') thisPageObj.save() # remove for sessionstest************** # Update the Question record. questionCount = 0 for theQuestion in thePageQuestions: # already sorted in order of appearance on page questionCount+=1 theQuestionFormTag = 'QuestionText_'+str(questionCount) theQuestionTypeTag = 'QuestionType_'+str(questionCount) DebugOut('questionCount: %s'%questionCount) questSeq = str(questionCount).zfill(3) # will be character sorted questionText = theQuestion.questionText if theQuestion.questionTag == '': theQuestion.questionTag = 'Quest'+questSeq # Kludge - insert a non-blank tag updatedQuestionText = cleanedData[theQuestionFormTag] responseType = theQuestion.responseType upatedResponseType = cleanedData[theQuestionTypeTag] DebugOut('Question text: %s' %questionText) DebugOut('Question form tag: %s' %theQuestionFormTag) if updatedQuestionText == '': # signal to delete the Question if it exists in the DB DebugOut('Question text is blank') # therefore delete if theQuestion.id: # avoid AssertionError if id set to None DebugOut('Question "%s" deleted'%theQuestionFormTag) theQuestion.delete() continue # continue to the next question elif questionText != updatedQuestionText or responseType != upatedResponseType: # so update theQuestion.questionText = updatedQuestionText if upatedResponseType: theQuestion.responseType = upatedResponseType elif not responseType: theQuestion.responseType = 'CharField' DebugOut('Question updated %s' %theQuestionFormTag) theQuestion.save() # remove for sessionstest************** # Update or create the PageRecord table updatePageQuestionSequence(thisPageObj,theQuestion, questSeq) else: DebugOut('Question NOT updated %s' %theQuestionFormTag) # however, update PageQuestion table which might have changed due to deletions updatePageQuestionSequence(thisPageObj,theQuestion, questSeq) # theResponses = ResponseChoice.objects.order_by('choiceSequence').filter(questionID=theQuestion) theResponses = theResponseChoices.order_by('choiceSequence').filter(questionID=theQuestion) numResponses = theResponses.count() newChoiceList = numResponses == 0 and upatedResponseType in multipleChoiceTypes if upatedResponseType in multipleChoiceTypes: # convert choices to a list rather than a query set and add one blank choice responseObjList = [] for aResp in theResponses: responseObjList.append(aResp) # add one more empty Choice blkResp = ResponseChoice( questionID = theQuestion, ) responseObjList.append(blkResp) # add blank response to the end. if numResponses == 0: # first entry # A newly created multiple choice has no "choices", so add an entry # Add text as if the user created the entry cleanedData.update({'Choice_'+str(1):'this is choice 1'}) else: responseObjList = [] choiceCount=0 for aResponse in responseObjList: choiceCount+=1 DebugOut('choiceCount: %s'%choiceCount) choiceTag = 'Choice_'+str(choiceCount) choiceSequence = str(choiceCount).zfill(2) # zfill pads a string with zeroes updatedChoiceText = cleanedData.get(choiceTag,'') isResponseChoiceUpdated = False if updatedChoiceText == '': # blank so delete the record DebugOut('updatedChoiceText text is blank') if aResponse.id: # avoid AssertionError if id set to None aResponse.delete() DebugOut('Choice "%s" deleted'%choiceTag) continue # continue to next choice elif aResponse.choiceText != updatedChoiceText: # so update aResponse.choiceText = updatedChoiceText if aResponse.choiceTag == '': aResponse.choiceTag = choiceTag aResponse.choiceSequence = choiceSequence DebugOut('ResponseChoice choiceTag updated %s' %choiceTag) DebugOut('ResponseChoice choiceText updated %s' %cleanedData[choiceTag]) isResponseChoiceUpdated = True else: if aResponse.choiceTag == '': aResponse.choiceTag = choiceTag isResponseChoiceUpdated = True DebugOut('ResponseChoice choiceTag was null, now is updated.' %choiceTag) if aResponse.choiceSequence != choiceSequence: aResponse.choiceSequence = choiceSequence isResponseChoiceUpdated = True DebugOut('ResponseChoice Sequence number is updated.' %choiceTag) aResponse.save() else: msg = 'Page edits not accepted' DebugOut(msg) errMsg.append(msg) elif 'changePageTag' in request.POST: # rename the current page DebugOut('in changePageTag') # change the name of this page if 'newPageTag' in request.POST: newShortTag = request.POST['newPageTag'] # interpret this as a "new" page name DebugOut('after newPageTag: %s'%newShortTag) # subtract the current page name # find all existing page shortTag's for this questionnaire if newShortTag == thisPageObj.shortTag: # name is unchanged infoMsg.append('Page name unchanged.') elif newShortTag in allPageTags: # Different from current, but not unique among all tags maxLength = 30 newUniqueName = makeUniqueTag( allPageTags, newShortTag, maxLength) infoMsg.append('Page tags for this questionnaire are:') infoMsg.append(allPageTags) infoMsg.append('Name "%s" changed to unique name: %s'%(newShortTag,newUniqueName)) newShortTag = newUniqueName thisPageObj.shortTag = newShortTag thisPageObj.save() else: thisPageObj.shortTag = newShortTag thisPageObj.save() else: errMsg.append('No page name specified.') # not sure when this would happen. DebugOut('out of changePageTag') elif 'Back' in request.POST: [pageToPageTrackNext, pageToPageTrackPrev] = oneTrackPageToPage(theQuestionnaire) # errMsg.append('Input page is %s' %thisPageObj.shortTag) # for kw,kv in pageToPageTrackPrev.iteritems(): # errMsg.append('%s to %s' %(kw.shortTag,kv.shortTag)) try: thisPageObj = pageToPageTrackPrev[thisPageObj] request.session['currentPageTag_bulkPageEdit'] = thisPageObj.id except: errMsg.append('No more pages') elif 'Next' in request.POST: [pageToPageTrackNext, pageToPageTrackPrev] = oneTrackPageToPage(theQuestionnaire) try: thisPageObj = pageToPageTrackNext[thisPageObj] request.session['currentPageTag_bulkPageEdit'] = thisPageObj.id except: errMsg.append('No more pages') elif 'createNewPageAfter' in request.POST: # maintain uniqueness of the short tags for this questionnaire. DebugOut('in createNewPageAfter') if 'newPageTag' in request.POST: newShortTag = request.POST['newPageTag'] # find all page shortTag's for this questionnaire if newShortTag in allPageTags: # not unique maxLength = 30 newUniqueName = makeUniqueTag( allPageTags, newShortTag, maxLength) errMsg.append('Name "%s" changed to unique name: %s'%(newShortTag,newUniqueName)) newShortTag = newUniqueName # tag name is unique theNewPageObj = createNewPageForQuestionnaireAfter(theQuestionnaire, thisPageObj, newShortTag) # remove for sessiontest******** request.session['currentPageTag_bulkPageEdit'] = theNewPageObj.id # define this as new page thisPageObj = theNewPageObj else: DebugOut('newPageTag not found') errMsg.append('newPageTag not found') DebugOut('exit createNewPageAfter') elif 'createNewPageBefore' in request.POST: # maintain uniqueness of the short tags for this questionnaire. DebugOut('in createNewPageBefore') if 'newPageTag' in request.POST: newShortTag = request.POST['newPageTag'] # find all page shortTag's for this questionnaire if newShortTag in allPageTags: # not unique maxLength = 30 newUniqueName = makeUniqueTag( allPageTags, newShortTag, maxLength) errMsg.append('Page tags for this questionnaire are:') errMsg.append(allPageTags) errMsg.append('Name "%s" changed to unique name: %s'%(newShortTag,newUniqueName)) newShortTag = newUniqueName # tag name is unique theNewPageObj = createNewPageForQuestionnaireBefore(theQuestionnaire, thisPageObj, newShortTag) # remove for sessiontest******** request.session['currentPageTag_bulkPageEdit'] = theNewPageObj.id # define this as new page thisPageObj = theNewPageObj else: DebugOut('newPageTag not found') errMsg.append('newPageTag not found') DebugOut('exit createNewPageBefore') elif 'deleteThisPage' in request.POST: DebugOut('in deleteThisPage') # try changing the default to the "next" page [pageToPageTrackNext, pageToPageTrackPrev] = oneTrackPageToPage(theQuestionnaire) DebugOut('pageToPageTrackNext; %s'%str(pageToPageTrackNext)) try: nextPageObj = pageToPageTrackNext[thisPageObj] deletePageInQuestionnaire(theQuestionnaire, thisPageObj) # repairs the transition matrix thisPageObj = nextPageObj request.session['currentPageTag_bulkPageEdit'] = thisPageObj.id except: # no pages following. deletePageInQuestionnaire(theQuestionnaire, thisPageObj) # repairs the transition matrix thisPageObj = getStartPageObj(theQuestionnaire) if thisPageObj: errMsg.append('No more pages. Go to start page.') request.session['currentPageTag_bulkPageEdit'] = thisPageObj.id else: errMsg.append('The questionnaire has no start page.') return render(request, 'system_error.html', { 'syserrmsg': errMsg}) elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: DebugOut('syserrmsg: bulkPageEdit: unknown button option') errMsg.append('bulkPageEdit: unknown button option') # Update form with questions (page perhaps changed with Back or Next thePageQuestions = getPageQuestions(thisPageObj) # add a blank question to the list thePageQuestions.append(Question()) initialValues ={ 'pageTitle' : theQuestionnaire.pageTitle, # from Questionnaire object 'pageSubTitle' : theQuestionnaire.pageSubTitle, # from Questionnaire object 'description' : thisPageObj.description, 'explanation' : thisPageObj.explanation, 'prologue' : thisPageObj.prologue, 'epilogue' : thisPageObj.epilogue, } thePageForm = BulkPageEditForm(initial=initialValues, questions=thePageQuestions) # infoMsg.append('before attempt') # test # infoMsg.append(thePageForm['Quest_1']) # infoMsg.append('after attempt') pageDescription = thisPageObj.description # Questionnaires referencing this page sharingQuestionnaires = getAllQuestionnairesReferencingAPage(thisPageObj) # remove the Questionnaire we are editing! sharingQuestionnaireTags = [] for aQuest in sharingQuestionnaires: if aQuest != theQuestionnaire: sharingQuestionnaireTags.append(aQuest.shortTag) lastUpdate = str(thisPageObj.lastUpdate) currentContext = { 'pageDescription' : pageDescription, 'sharingQuestionnaireTags' : sharingQuestionnaireTags, 'thePageForm' : thePageForm, 'theProjectTag' : theProject.shortTag, 'theQuestionnaire' : theQuestionnaire, # object 'thisPageObj' : thisPageObj, # object 'thePageQuestions' : thePageQuestions, # query set 'thisPageTag' : thisPageObj.shortTag, 'errMsg' : errMsg, 'infoMsg' : infoMsg, } DebugOut('bulkPageEdit: exit') return render(request, 'working_pages/bulkPageEdit.html', currentContext) @login_required() def editQuestionNames( request): """All questions in the entire questionnaire are presented in table form. Various aspects can be edited: including the question names. """ def makeQuestionInfoList(allQuestions): allQuestionInfo = [] ii = 0 for aQuestion in allQuestions: # get all Pages where this Question appears. pageTagList = [] allPQs = PageQuestion.objects.filter(questionID=aQuestion) allTags = [aPQ.pageID.shortTag for aPQ in allPQs] # list comprehension tagListStr = ', '.join(allTags) aRow = [ aQuestion.questionText, # Text aQuestion.questionTag, # Short tag aQuestion.explanation, # Explanation (viewed by respondent) aQuestion.description, # Description (not viewed by respondent) aQuestion.responseType, # Response type str(tagListStr), # pages which contain this question str(aQuestion.id), # Question record number ] allQuestionInfo.append(aRow) ii += 1 return allQuestionInfo DebugOut('editQuestionNames: enter') errMsg = [] # Initialize error messages # get default Project and Questionnaire [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) DebugOut('Project: %s, Questionnaire: %s' %(theProject, theQuestionnaire)) if not theProject: # select a project. DebugOut('The Project has not been selected') errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) theQuestionnaireTag = theQuestionnaire.shortTag theProjectTag = theProject.shortTag # get all possible questions and question tags allQuestions = getAllQuestionObjsForQuestionnaire(theQuestionnaire) allQuestionInfo = makeQuestionInfoList(allQuestions) # List the columns in the Question model colList = [ 'Text', 'Short tag', 'Explanation', 'Description (not viewed by respondent)', 'Response type', "Page Tag('s)", ] if request.method == 'POST': DebugOut('after POST') DebugOut('request.POST: %s'%request.POST) DebugOut('request.POST type: %s'%type(request.POST)) if 'acceptEdits' in request.POST: # accept questionnaire edits # search for any changes in the data for aRow in allQuestionInfo: theQRec = aRow[6] # the record number theQuestion = allQuestions.get(id=int(theQRec)) # Test each field for an update. updateRecord = False if request.POST['ShortTag_Rec_'+theQRec] != theQuestion.questionTag: theQuestion.questionTag = request.POST['ShortTag_Rec_'+theQRec] updateRecord = True if request.POST['Descr_Rec_'+theQRec] != theQuestion.description: theQuestion.description = request.POST['Descr_Rec_'+theQRec] updateRecord = True if updateRecord: theQuestion.save() DebugOut('Record "%s" updated'%theQRec) allQuestions = getAllQuestionObjsForQuestionnaire(theQuestionnaire) allQuestionInfo = makeQuestionInfoList(allQuestions) elif 'returnToHome' in request.POST: redirectURL = registrationURL_base + 'userLanding/' DebugOut('selectProjectDefault: exit to %s'%redirectURL) return HttpResponseRedirect(redirectURL) else: pass #Unknown button hit DebugOut('syserrmsg: Unknown button hit') DebugOut('request.POST') DebugOut(str(request.POST)) else: # GET DebugOut('after GET') currentContext = { 'allQuestionInfo' : allQuestionInfo, 'theProjectTag' : theProjectTag, 'theQuestionnaireTag' : theQuestionnaireTag, 'colList' : colList, 'field_types' : FIELD_TYPES, 'url_base' : url_base, 'errMsg' : errMsg, } DebugOut('editQuestionNames: exit') return render(request, workingPageTemplateRoot + 'editQuestionNames.html', currentContext) def questionnaireOutput( theQuestionnaire ): """extract Questionnaire data from a query object, and reformat for text display via form output is a dictionary """ DebugOut('questionnaireOutput: enter') fieldValueDict = getModelFieldValueDict(theQuestionnaire) # Make some corrections to make the data display properly! # fix the time stamp if 'versionDate' in fieldValueDict: # clip off the right most characters for the time zone setting. # must be a better way to do this *** versionDateVal = str(fieldValueDict['versionDate']) if len(versionDateVal) > 19: # must have timezone information versionDateVal = versionDateVal[:-6] # clip it off fieldValueDict['versionDate'] = versionDateVal DebugOut('questionnaireOutput: exit') return fieldValueDict def createQuestionnaireObj( inputDict ): # Create a questionnaire Object from the input dictionary which is not saved. # Will accept a dictionary from questionnaireOutput() localInput = {} localInput.update(inputDict) # Don't change the input dictionary if 'globalFlags' in localInput: # make any corrections to the format gflunclean = localInput['globalFlags'] localInput['globalFlags'] = cleanUpKeywords( gflunclean) # remove blanks, & newlines if 'versionDate' not in localInput: # required date field localInput['versionDate'] = timezone.now() try: ptlText = localInput['ptl'].replace(" ","") # assume text input except: # don't set ptl value because of error. Perhaps not included in input theQuestionnaireObj = Questionnaire(**localInput) return theQuestionnaireObj if ptlText: # not null ptlListOut = ptlText.split(os.linesep) # splits at the end of line # now split each csv line a the comma, eliminating blanks. ptlListInput = [] for aLine in ptlListOut: fieldsInLine = aLine.replace(" ","").replace("'","").split(',') newLine = [] for oldField in fieldsInLine: newLine.append(oldField.strip()) ptlListInput.append(newLine) # get rid of whitespace and trailing & leading blanks localInput['ptl'] = pickle.dumps(ptlListInput) # pickle the list of lists theQuestionnaireObj = Questionnaire(**localInput) return theQuestionnaireObj def updateQuestionnaireObj( qObj, inputDict ): DebugOut('updateQuestionnaireObj: enter') #Update a questionnaire Object from the input dictionary. # The questionnaire Object is not saved. #Will accept a dictionary from questionnaireOutput() localInput = {} localInput.update(inputDict) # Don't change the input dictionary if 'globalFlags' in localInput: # make any corrections to the format gflunclean = localInput['globalFlags'] localInput['globalFlags'] = cleanUpKeywords( gflunclean) # remove blanks, & newlines if 'versionDate' not in localInput: # required date field localInput['versionDate'] = timezone.now() for key,value in localInput.iteritems(): setattr(qObj, key, value) DebugOut('updateQuestionnaireObj: exit') return qObj def cleanUpKeywords( kwInput): # Input is a character string with possibly 'linesep' and commas. # Linesep are converted to commas. CSV values have blanks removed within and left right. kwLinesep = kwInput.split(os.linesep) # break lines into elements of a list kwList = [] for aLine in kwLinesep: fieldsInLine = aLine.replace(" ","").split(',') newLine = [] for oldField in fieldsInLine: newLine.append(oldField.strip()) kwList.extend(newLine) # get rid of whitespace and trailing & leading blanks kwStr = ','.join(kwList) return kwStr def respondentIdent(request, whichProject, whichQuest): DebugOut( 'In respondentIdent. whichProject: %s whichQuest: %s' %(whichProject, whichQuest)) errMess = [] # Standard verification w.r.t. project and questionnaire [theProject, theQuestionnaire, errMess] = verifyQuestionnaireProject(request, whichProject, whichQuest) if errMess != []: return render(request, 'system_error.html', { 'syserrmsg': errMess}) pageBaseURL = request.session['pageBaseURL'] this_page = 'respondentIdent' # Standard page object retrieval [thePageObj, success] = getPageObj(theQuestionnaire, this_page) if not success: errMsg=['Could not find a page transition for %s'%this_page] return render(request, 'system_error.html', {'syserrmsg': errMess}) description = thePageObj.description prologue = thePageObj.prologue if 'constantPageDataDict' in request.session: constantPageDataDict = request.session['constantPageDataDict'] else: return render(request, 'system_error.html', {'syserrmsg': ['Debug: header and footer page data is missing.']}) # fill fields with previously entered data from this session - if any # query Session data for previously entered pt name & bd if 'currentRespondent' in request.session: DebugOut('form data: %s' %str(request.session['currentRespondent'])) currentRespondent = request.session['currentRespondent'] # retrieve a dictionary of values theForm = RespondentIdentForm(currentRespondent) else: theForm = RespondentIdentForm() errmsg = '' computerT = computertype(request) # identify computer type if request.method == 'POST': theForm = RespondentIdentForm(request.POST) if request.POST['submitButton'] == 'Back': # save no data back_to = UpdateLast_URL_Back(request, this_page) return HttpResponseRedirect(pageBaseURL+back_to) # previous screen url # Assume clicked button 'Next' elif theForm.is_valid(): UpdateLast_URL_Next(request, this_page) # ignore 'back to' output DebugOut('form data: %s' %str(theForm.cleaned_data)) if 'birthDate' in theForm.cleaned_data: # make it JSON searlializable by making it a string theForm.cleaned_data['birthDate'] = str(theForm.cleaned_data['birthDate']) request.session['currentRespondent'] = theForm.cleaned_data if respondentIDDict in request.session: # aggregate user identification request.session[respondentIDDict].update(theForm.cleaned_data) else: # create user identification request.session[respondentIDDict] = theForm.cleaned_data next_pageObj = pageCalc(request,theQuestionnaire, thePageObj ) next_page = next_pageObj.shortTag DebugOut( 'respondentIdent: exit') return HttpResponseRedirect(pageBaseURL+next_page) # next screen url computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] fontSizeTextBox = dynamicPageDetails['fontSizeTextBox'] contextDict = {'theForm': theForm, 'errmsg' : errmsg, 'computerT' : computertype(request), 'theProject' : theProject, 'explanation' : SubstituteWords( thePageObj.explanation ), 'prologue' : prologue, 'field_border' : '0', # border width - zero is ok. 'field_style' : 'as_p', 'fontSize' : fontSize, 'fontSizeTextBox' : fontSizeTextBox, 'barTitle' : 'Respondent Identity', } currentContext = constantPageDataDict.copy() currentContext.update(contextDict) DebugOut( 'respondentIdent: exit') return render(request, 'respondentIdent.html', currentContext) def pageCalc(request,theQuestionnaire, thePageObj, **kwargs ): # calculates the next page tag given the current state of the session data. DebugOut('pageCalc: entering') currentPageTag = thePageObj.shortTag DebugOut('pageCalc: current page is %s' %currentPageTag) nextPageObj = getNextPageFromDB(theQuestionnaire, thePageObj) if nextPageObj: nextPageTag = nextPageObj.shortTag DebugOut('pageCalc: used Default to calculate current/next page %s/%s' %(currentPageTag,nextPageTag)) else: DebugOut('syserrmsg: pageCalc: no default page available!') nextPageTag = 'completion' # Standard page object retrieval [nextPageObj,success] = getPageObj(theQuestionnaire, nextPageTag) if not success: nextPageObj = Page() # Punt the problem upstairs if 'questionResults' in kwargs: # incoming question results **************** DebugOut('pageCalc: incoming question results') questionResults = kwargs.pop('questionResults') DebugOut('pageCalc: questionResults: %s' %questionResults) # check for calculated next page nextfromCalc =getNextPageFromCalculation(theQuestionnaire, thePageObj, questionResults) if nextfromCalc: nextPageTag = nextfromCalc.shortTag nextPageObj = nextfromCalc DebugOut('pageCalc: Have a match for a calculated next page: %s' %nextPageTag) else: DebugOut('pageCalc: No match for a calculated next page') # Check for global flags match to question response [nextfromGlobal, useGlobal] = getNextPageFromGlobalFlags(request, theQuestionnaire, thePageObj) if useGlobal: nextPageObj = nextfromGlobal # next page DebugOut('pageCalc: Match for a global flag determined next page %s' %nextPageObj.shortTag) DebugOut('pageCalc: exit') return nextPageObj def imageCalc(current_page ): # calculates True or False, if an image is present on the page. if current_page in ['P1','P2']: imagePresent = True else: imagePresent = False return imagePresent def Completion(request, whichProject, whichQuest): """Completion is the last page of the questionnaire. This page offers buttons to email the summary data or to return to the start page. """ DebugOut( 'In Completion.') # Standard verification w.r.t. project and questionnaire [theProject, theQuestionnaire, errMess] = verifyQuestionnaireProject(request, whichProject, whichQuest) if errMess != []: return render(request, 'system_error.html', { 'syserrmsg': errMess}) firstpage = getStartPageObj(theQuestionnaire).shortTag # return to first page if 'constantPageDataDict' in request.session: constantPageDataDict = request.session['constantPageDataDict'] else: return render(request, 'system_error.html', {'syserrmsg': ['Debug: header and footer page data is missing.']}) current_date = timezone.now() pageBaseURL = request.session['pageBaseURL'] try: request.session.delete_test_cookie() # remove cookie DebugOut('Completion: cookie removed.') except: DebugOut('Completion: cookie not removed.') if respondentIDDict in request.session: # aggregate user identification try: contactEmail = request.session[respondentIDDict]["contactEmail"] except: contactEmail = "" else: contactEmail = "" if not contactEmail: removeResponsesFromSessionData(request) # No contact email, so delete # pt data in session data. if "summaryPagehtml" in request.session: summaryExist = True else: summaryExist = False sentMail = "Questionnaire summary data not created" sentMail = "" if request.method == 'POST': DebugOut( 'In POST.') if "submitButton" in request.POST: DebugOut( 'In submitButton.') if request.POST["submitButton"] == "Submit e-mail": # html checks contactEmail DebugOut( 'In Submit e-mail.') current_date_short = str(current_date)[:16] emailSubj = 'screener results for %s' % current_date_short questionnaireEmail = theProject.email # email "from" this address DebugOut('questionnaireEmail: %s'%questionnaireEmail) if summaryExist: # send risk page with html DebugOut('Found summary information to send.') html_content = "%s" %request.session["summaryPagehtml"] msg = EmailMessage(emailSubj, html_content, questionnaireEmail, [contactEmail]) msg.content_subtype = "html" # Main content is now text/html sentMail = "Email has been sent to: " + contactEmail summaryExist = True else: DebugOut('No summary information.') adminEmail = settings.DEFAULT_FROM_EMAIL # send error message back to screener emailBody = 'Error message to '+adminEmail +'\n Error, no summary data %s' % current_date msg = EmailMessage(emailSubj, emailBody, questionnaireEmail, [adminEmail]) sentMail = 'Admin has been informed of an error: ' + adminEmail summaryExist = False try: msg.send() removeResponsesFromSessionData(request) # remove Respondent data # except SMTPAuthenticationError: # DebugOut('SMTPAuthenticationError ') # sentMail = 'SMTP Authenticaion Error - try again in a few minutes' except: DebugOut('Other exception upon attempting to send email ') sentMail = 'Unknown error sending email. Please report.' removeResponsesFromSessionData(request) # remove Respondent data elif request.POST["submitButton"] == "start": # return to start page DebugOut( 'In start.') removeResponsesFromSessionData(request) # remove Respondent data questionnaireEnvironmentPrep( request, theProject, theQuestionnaire) urltogo = questionnaireToGo(request, theProject, theQuestionnaire) return HttpResponseRedirect(urltogo) else: # not contactEmail removeResponsesFromSessionData(request) # remove respondent data computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] fontSizeTextBox = dynamicPageDetails['fontSizeTextBox'] contextDict = { 'thishost' : request.get_host(), 'summaryExist' : summaryExist, 'contactEmail' : contactEmail, 'current_date' : current_date, 'fontSize' : fontSize, 'fontSizeTextBox' : fontSizeTextBox, 'sentMail' : sentMail, 'fontSize' : fontSize, } currentContext = constantPageDataDict.copy() currentContext.update(contextDict) return render(request, 'Completion.html', contextDict) def uniquePTID(firstName, middleName, lastName, birthDate): # construct a unique Respondent id respondentName = firstName+' '+middleName+' '+lastName respondentName = respondentName.title() # capitalize each word to reduce variation respondentName = respondentName.replace(' ','').replace('.','') # reduce variation uid = "%s %s" % (birthDate, respondentName) return uid def ListQuestionsForQuestionnaire(aQuaireObj): """List all questions from all pages belonging to a Questionnaire Args: aQuaireObj: a Questionnaire object Returns: a list with the record structure: [pageList, fieldList, theList, tagToText] pageList: a list of Page.shortTags in a standard order fieldList: a list of Unique tags for questions (or muliple choices) This tag is constructed out of the record numbers, which guarentees uniqueness theList: a list with record structure: [aPageTag, theQLabel, qText] aPageTag: Page.shortTag theQLabel: a Unique tag for question (or muliple choices) qText: human readable text which is displayed with the multiple choice Question.questionText for question prompt OR ResponseChoice.choiceText for multiple choice tagToText: a dictionary tranlation of the Unique tag to question text theQLabel: (key) qText: Question.questionText OR qText: ResponseChoice.choiceText """ DebugOut('Entering ListQuestionsForQuestionnaire') qpObj = allPagesInDefaultOrder(aQuaireObj) fieldList = [] theList = [] pageList = [] tagToText = {} for ap in qpObj: # examine each page in the questionnaire DebugOut('Top of page loop') aPageObj = ap aPageTag = aPageObj.shortTag DebugOut('processing page: %s' %aPageTag) pageList.append(aPageTag) thePageQuestionsAll = getPageQuestions(aPageObj) # get all questions on the page DebugOut('Number of questions found: %s' %len(thePageQuestionsAll)) DebugOut('thePageQuestionsAll: %s' %thePageQuestionsAll) for aQuest in thePageQuestionsAll: # examine each question on a page DebugOut('at the top of the questions on the page loop') theQRecNum = str(aQuest.id) theQLabel = encodeQuestionResponseLabel(theQRecNum,'') DebugOut('after theQLabel: %s'% theQLabel) qText = aQuest.questionText DebugOut('question text: %s' %qText) questionType = aQuest.responseType # look for MultipleChoiceField DebugOut('Before determining multichoice') responseCount = ResponseChoice.objects.filter( questionID=aQuest).count() if responseCount>0: # go down to sublist for MultipleChoiceField DebugOut('found a MultipleChoiceField for question label: %s' %theQLabel) DebugOut('questionType: %s' %questionType) tagToText.update({theQLabel:qText}) # add the tag for the multi choice fieldList.append(theQLabel) theList.append([aPageTag, theQLabel, qText]) theResponses = ResponseChoice.objects.order_by('choiceSequence').filter(questionID=aQuest) # collect the multiple responses DebugOut('Number of multiple responses: %s' %len(theResponses)) for aResponse in theResponses: DebugOut('aResponse: "%s"'%aResponse.choiceText) theChoiceRecNum = str(aResponse.id) theQResponseLabel = encodeQuestionResponseLabel(theQRecNum,theChoiceRecNum) DebugOut('Multiple choice label %s' %theQResponseLabel) qText = aResponse.choiceText DebugOut('MultipleChoiceField tag & text: %s %s' %(theQResponseLabel,qText)) tagToText.update({theQResponseLabel:qText}) # add Subchoices fieldList.append(theQResponseLabel) theList.append([aPageTag, theQResponseLabel, qText]) DebugOut('Multiple choice appended to the list %s' %theQResponseLabel) DebugOut('Exiting multiple choice.') else: DebugOut('found a single choice for tag: %s' %theQLabel) tagToText.update({theQLabel:qText}) fieldList.append(theQLabel) theList.append([aPageTag, theQLabel, qText]) DebugOut('Single choice appended to the list') # make the output list of question field tags unique by eliminating the first of a succession of duplicate DebugOut('Before makeUniqueListReverse') fieldList = makeUniqueListReverse(fieldList) DebugOut('After makeUniqueListReverse') DebugOut('Exiting ListQuestionsForQuestionnaire') return [pageList, fieldList, theList, tagToText] def formatResponseforDisplay(request): """Pull questionnaire response data from session data, then reformat into a list ultimately for display via a template. """ DebugOut('formatResponseforDisplay: enter') success = True if allResultsList in request.session: allResults = request.session[allResultsList] DebugOut('Have results data') else: errMsg = 'No questionnaire response session data' DebugOut(errMsg) success = False questionResponseList = [''] return [questionResponseList, success] # go through all key values, in order answered questionResponseList = [] # create the page results list # reverse the list to get time-ordered output # allResults.reverse() for aline in allResults: # request.session[allResultsList] structure: # [questionResponse, questionText,questionRecNum,responseChoiceRecNum,pageShortTag,pageRecNum, uniqueQuestionLabel, questionTag] rawQuestionResponse = aline[0] questionText = strip_tags(aline[1]) # no html in the Summary #DebugOut('questionText: %s' %questionText) questionRecNum = aline[2] responseChoiceRecNum = aline[3] pageShortTag = aline[4] pageRecNum = aline[5] uniqueTagNotUsed = aline[6] questionTag = aline[7] if type(rawQuestionResponse) == list: # null value since value is a set of keywords listLevel = 'sub' questionResponseList.append([listLevel, questionText,"", pageShortTag]) #DebugOut('rawQuestionResponse: "%s"'%rawQuestionResponse) for aValue in rawQuestionResponse: # create additional lines, one for each element in the list #DebugOut('in choice loop: aValue %s' %aValue) questionResponseList.append([listLevel, aValue,'', pageShortTag]) else:# not a list, therefore at the main level listLevel = 'main' questionResponse = str(rawQuestionResponse) #DebugOut('questionResponse: %s' %questionResponse) theLine = [listLevel, questionText, questionResponse, pageShortTag] questionResponseList.append(theLine) #DebugOut(theLine) # questionResponseList record structure: # [listLevel, questionText, questionResponse, pageShortTag] DebugOut('formatResponseforDisplay: exit') return [questionResponseList, success] def questionnaireSummary(request, whichProject, whichQuest, whichPage): DebugOut("questionnaireSummary: enter") # Standard verification w.r.t. project and questionnaire [theProject, aQuaireObj, errMess] = verifyQuestionnaireProject(request, whichProject, whichQuest) if errMess != []: return render(request, 'system_error.html', { 'syserrmsg': errMess}) [thePageObj, success] = getPageObj(aQuaireObj, whichPage) if not success: errMsg=['Could not find page %s'%whichPage] return render(request, 'system_error.html', {'syserrmsg': errMess}) this_page = whichPage pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' + whichProject+'/'+whichQuest+'/' DebugOut('Current page url: %s' %this_page) explanation = SubstituteWords( thePageObj.explanation ) prologue = SubstituteWords( thePageObj.prologue ) epilogue = SubstituteWords( thePageObj.epilogue ) # debug # [pageList, fieldList, theList, tagToText ] = List__QuestionsForQuestionnaire(aQuaireObj) # name mangled intentionally. # reformat the responses residing in session data to a list [questionResponseList, success] = formatResponseforDisplay(request) # strip_tags if not success: errMsg = ['No questionnaire response session data'] DebugOut(errMsg) return render(request, 'system_error.html', {'syserrmsg': errMess}) if allResultsDict not in request.session: errMsg = ['No session data'] DebugOut(errMsg) return render(request, 'system_error.html', {'syserrmsg': errMess}) # find key values in session data which are NOT in "fieldList". If so document # keyList = allResultsDictValues.keys() # DebugOut('Debug only: Following is a list of pt entered keys unknown:') # kk = 0 # for aKey in keyList: # if aKey not in fieldList: # DebugOut('syserrmsg: questionnaireSummary: Unknown key: %s' %aKey) # kk = kk+1 # if kk == 0: # DebugOut('All keys were found.') if 'constantPageDataDict' in request.session: constantPageDataDict = request.session['constantPageDataDict'] else: return render(request, 'system_error.html', {'syserrmsg': ['Debug: header and footer page data is missing.']}) # must have the following data if respondentIDDict in request.session: respIDDict = request.session[respondentIDDict] else: # pt data is missing # return to respondent id page next_pageObj = pageCalc(request,aQuaireObj, thePageObj ) next_page = next_pageObj.shortTag DebugOut('Pt data NOT found for questionnaireSummary page. Next page is: %s' %next_page) return HttpResponseRedirect(pageBaseURL+next_page) # next screen url if "lastName" in respIDDict: lastName = respIDDict['lastName'].title() # capitalize each word respIDDict['lastName'] = lastName # save capitalized form else: # if no Respondent name, return to splash screen return render(request, 'system_error.html', {'syserrmsg': ['Debug: Pt lastName is missing.']}) if "middleName" in respIDDict: middleName = respIDDict['middleName'].title() # capitalize each word respIDDict['middleName'] = middleName # save capitalized form else: # if no Respondent name, return to splash screen pass # not required if "firstName" in respIDDict: firstName = respIDDict['firstName'].title() # capitalize each word respIDDict['firstName'] = firstName # save capitalized form else: # if no Respondent name, return to splash screen return render(request, 'system_error.html', {'syserrmsg': ['Debug: Pt firstName is missing.']}) if len(middleName) == 0: respondentName = lastName+', '+firstName else: respondentName = lastName+', '+firstName+', '+middleName if "birthDate" in respIDDict: birthDate = respIDDict['birthDate'] else: # if no respondent bd, return to splash screen return render(request, 'system_error.html', {'syserrmsg': ['Debug: Pt birthdate is missing.']}) current_date = timezone.now() DebugOut('birthDate') DebugOut(str(birthDate)) DebugOut('data type: %s' %type(birthDate)) # pt_currentAge = calculate_ptAge_now( datetime.strptime(str(birthDate), '%Y-%m-%d')) pt_currentAge = '' # *** the preceding line is a mess and should be improved - but how? # error is obtained without "datetime.strptime(str(birthDate), '%Y-%m-%d')" # the following obtains a TypeError: # 'tzinfo' is an invalid keyword argument for this function # Location: /Library/Python/2.7/site-packages/django/utils/timezone.py in make_aware # make_aware, inside calculate_ptAge_now, is very simple: value.replace(tzinfo=timezone) #pt_currentAge = calculate_ptAge_now( birthDate) if 'contactEmail' in respIDDict: contactEmail = respIDDict['contactEmail'] else: contactEmail = "" # not required if 'contactPhone' in respIDDict: contactPhone = respIDDict['contactPhone'] else: contactPhone = "" # not required pageBaseURL = request.session['pageBaseURL'] projectAbbrev = theProject.abbrev projectContactPhone = theProject.contactPhone DebugOut('questionnaireSummary: creating contextDict') computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] fontSizeTextBox = dynamicPageDetails['fontSizeTextBox'] contextDict = { 'barTitle' : 'Questionnaire Summary Page', 'respondentName' : respondentName, 'birthDate' : birthDate, 'pt_currentAge': pt_currentAge, 'startQURL' : pageBaseURL, 'contactEmail' : contactEmail, 'contactPhone' : contactPhone, # respondent contact phone 'current_date' : current_date, 'explanation' : explanation, 'prologue' : prologue, 'epilogue' : epilogue, 'projectAbbrev' : whichProject, 'projectContactPhone' : projectContactPhone, 'questionResponseList': questionResponseList, 'fontSize' : fontSize, 'fontSizeTextBox' : fontSizeTextBox, # 'respondentCallbackNumber' : request.session["respondentCallbackNumber"], } if request.method == 'POST': DebugOut('questionnaireSummary: inside POST') DebugOut('this_page %s' %this_page) if request.POST['submitButton'] == 'Back': DebugOut( 'BACK button clicked') back_to = UpdateLast_URL_Back(request, this_page) DebugOut('back to page %s' %back_to) return HttpResponseRedirect(pageBaseURL+back_to) # previous screen url elif request.POST['submitButton'] == 'Next': DebugOut('Next button clicked') UpdateLast_URL_Next(request, this_page) # ignore 'back to' output # make a copy of the summary page and save it currentContext = constantPageDataDict.copy() currentContext.update(contextDict) currentContext.update({'buttons_not_enabled': True}) # leave off the buttons for email! # DebugOut('questionnaireSummary: page context: %s' %currentContext) summaryPagehtml = render(request, 'questionnaireSummary.html', currentContext) request.session["summaryPagehtml"]=str(summaryPagehtml) # save the html for possible email savePtResponse(request) # save data to database next_pageObj = pageCalc(request,aQuaireObj, thePageObj ) next_page = next_pageObj.shortTag UpdateLast_URL_Next(request, this_page) # ignore 'back to' output if next_page != '': DebugOut('Edits to the summary done, so exit page "%s" to next page "%s"' %(this_page, next_page)) return HttpResponseRedirect(pageBaseURL+next_page) # next screen url else: # assume at the end of the questionnaire DebugOut( 'syserrmsg: Next page is null. Completion? this_page: %s, next_page: %s' %(this_page,next_page)) return HttpResponseRedirect( pageBaseURL+'completion/') else: # not POST DebugOut('questionnaireSummary: inside GET') DebugOut('this_page %s' %this_page) currentContext = constantPageDataDict.copy() currentContext.update(contextDict) # summaryPagehtml = render(request, 'questionnaireSummary.html', contextDict) # request.session["summaryPagehtml"]=str(summaryPagehtml) # save the context for possible email DebugOut('questionnaireSummary: exit') return render(request, 'questionnaireSummary.html', contextDict) def respondentName( respodentObj ): # return respondent concatenated name firstName = respodentObj.firstName middleName = respodentObj.middleName lastName = respodentObj.lastName if len(middleName) == 0: respName = lastName+', '+firstName else: respName = lastName+', '+middleName+', '+firstName return respName @login_required() def displaySubmissionDataForProject(request): """Displays all submissions pointing to questionnaires in a project. """ theProject = getSessionProject(request) if not theProject: # fall back to user default theUser = request.user theProject = getAssociatedProjectForUser(theUser) if not theProject: # Redirect if still no project redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # Display Submissions DebugOut('Output csv file for Proejct %s'%theProject.shortTag) result = responseViewer(request, forProject=theProject) return result def makeSubmissionListForDisplay(allSubmissions, firstColLabel='Select', firstColPrefix='R_'): """ Format Submissions as a list to prepare for display. """ submitTable = [] ii = 1 for aSubmission in allSubmissions: theResppondent = aSubmission.respondentID DebugOut('Including Respondent: %s' %theResppondent.ptUniqueID) respObj = aSubmission.respondentID respName = respondentName( respObj ) contactEmail = respObj.contactEmail aRow = [ firstColPrefix+str(ii), # provide a selection method aSubmission.lastUpdate, respName, aSubmission.questionnaireID.barTitle, # aSubmission.completedYN, contactEmail, aSubmission.reviewedBy, aSubmission.reviewDate, aSubmission.okForExport, ] submitTable.append(aRow) ii = ii+1 submitTableCols = [ firstColLabel, 'Submit date', "Respondent's Name", 'Questionnaire', "Respondent's Email", # 'Completed?', 'Reviewed By', 'Review Date', 'Ok for data Export?', ] return [submitTable, submitTableCols] def dumpSubmissionTable(request): """ # Dump the Submission table. Do not limit scope to that of the Project """ DebugOut('responseViewerAll: entering') errMsg = [] allSubmissions = Submission.objects.all().order_by('questionnaireID__shortTag', '-lastUpdate') if len(allSubmissions) == 0: errMsg.append('Zero submissions. No Questionnaire submissions to display for this Project.') urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': [errMsg], 'wsgiPrefix':urlPrefix}) # make a table of submissions [submitTable, submitTableCols] = makeSubmissionListForDisplay(allSubmissions) tableName = 'List the Submission Table - all Projects' return render(request, workingPageTemplateRoot + 'tablelisting.html', {'pageTitle' : tableName, 'allValues' : submitTable, 'colList' : submitTableCols, 'bannerText' : tableName, 'bannerText1' : '', 'back_to' : registrationURL_base + 'userLanding/', 'back_toPrompt' : 'Return to the Home Page', 'errMsg' : errMsg, }) def getSubmissionsForProject(theProject): """ Retrieve all Submission objects for a Project """ # Get the Questionnaires for this project. allQuestionnaires = getQuestionnaireObjsForProject(theProject) # get all Submissions for these questionnaires # set up a query "OR" if allQuestionnaires.count() == 0: # no Projects, so return empty queryset allSubmissions = Submission.objects.none() else: queryOR = Q(questionnaireID=allQuestionnaires[0].id) DebugOut('Including Questionnaire: %s' %allQuestionnaires[0].shortTag) if len(allQuestionnaires) >1: for aQuestionnaire in allQuestionnaires[1:]: DebugOut('Including Questionnaire: %s' %aQuestionnaire.shortTag) queryOR = queryOR | Q(questionnaireID=aQuestionnaire.id) allSubmissions = Submission.objects.filter(queryOR).order_by('questionnaireID__shortTag', '-lastUpdate') return allSubmissions @login_required() def responseDelete(request,selectAllSubmissions=False): """ # Select and delete questionnaire responses. Limit scope to that of the Project """ DebugOut('responseDelete: entering') errMsg = [] theProject = getSessionProject(request) if not theProject: # not in session data # fall back to user default theUser = request.user theProject = getAssociatedProjectForUser(theUser) if not theProject: # Redirect if still no project redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # Get the Submissions for this project or for all projects. if selectAllSubmissions: allSubmissions = Submission.objects.all() else: allSubmissions = getSubmissionsForProject(theProject) if len(allSubmissions) == 0: errMsg.append('Zero submissions. No Questionnaire submissions to display for this Project.') urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': errMsg, 'wsgiPrefix':urlPrefix}) # make a table of submissions [submitTable, submitTableCols] = makeSubmissionListForDisplay(allSubmissions, firstColLabel='Delete', firstColPrefix='D_') deleteSelected = False # initialize whether a submission has been selected if request.method == 'POST': DebugOut('after POST') DebugOut('POST: %s' %str(request.POST)) if 'deleteSelected' in request.POST: DebugOut('deleteSelected button hit') respSelectionText = request.POST['deleteSelected'] DebugOut('respSelectionText: %s' %respSelectionText) responseIndex = int(respSelectionText[2:])-1 # requires detailed format knowledge!!! 'D_'+int theSubmission = allSubmissions[responseIndex] DebugOut('theSubmission: %s' %str(theSubmission)) # delete theSubmission # make a table of submissions - again theSubmission.delete() errMsg.append('Selection deleted.') if selectAllSubmissions: allSubmissions = Submission.objects.all() else: allSubmissions = getSubmissionsForProject(theProject) if len(allSubmissions) == 0: errMsg.append('Zero submissions. No Questionnaire submissions to display for this Project.') urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': errMsg, 'wsgiPrefix':urlPrefix}) [submitTable, submitTableCols] = makeSubmissionListForDisplay(allSubmissions, firstColLabel='Delete', firstColPrefix='D_') elif 'returnToHome' in request.POST: DebugOut('returnToHome button hit') redirectURL = registrationURL_base + 'userLanding/' DebugOut('responseViewer: exiting to Home') return HttpResponseRedirect(redirectURL) # previous screen url else: DebugOut('Unknown button hit') pass else: DebugOut('NOT A POST') pass currentContext = { 'theProject' : theProject, 'submitTableCols' : submitTableCols, 'submitTable' : submitTable, 'back_to_intro' : 'Return to the Home Page', 'url_base' : url_base, 'errMsg' : errMsg, } DebugOut('responseViewer: exiting') return render(request, 'working_pages/responseDelete.html', currentContext) @login_required() def responseViewer(request,forProject=None): """ # Select and view questionnaire responses. Limit scope to that of the Project """ DebugOut('responseViewer: entering') errMsg = [] theProject = getSessionProject(request) if not theProject: # not in session data # fall back to user default theUser = request.user theProject = getAssociatedProjectForUser(theUser) if not theProject: # Redirect if still no project redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # Get the Questionnaires for this project. allSubmissions = getSubmissionsForProject(theProject) # allSubmissions = Submission.objects.all().order_by('questionnaireID__shortTag', '-lastUpdate') if len(allSubmissions) == 0: errMsg.append('Zero submissions. No Questionnaire submissions to display for this Project.') urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': [errMsg], 'wsgiPrefix':urlPrefix}) # make a table of submissions [submitTable, submitTableCols] = makeSubmissionListForDisplay(allSubmissions) submitSelected = False # initialize whether a submission has been selected if 'submitSelected' in request.session: DebugOut('submitSelected in request.session') responseIndex = request.session['submitSelected'] theSubmission = allSubmissions[responseIndex] submitSelected = True if request.method == 'POST': DebugOut('after POST') if 'respSelection' in request.POST: respSelectionText = request.POST['respSelection'] responseIndex = int(respSelectionText[2:])-1 # requires detailed format knowledge!!! 'R_'+int theSubmission = allSubmissions[responseIndex] DebugOut('theSubmission: %s' %str(theSubmission)) request.session['submitSelected'] = responseIndex submitSelected = True elif 'dataItemSelection' in request.POST: DebugOut('dataItemSelection in request.POST') dataItemSelection = request.POST['dataItemSelection'] elif 'returnToHome' in request.POST: DebugOut('returnToHome button hit') redirectURL = registrationURL_base + 'userLanding/' return HttpResponseRedirect(redirectURL) # previous screen url else: DebugOut('NOT A POST') pass # make a table of Questionnaire responses if submitSelected: DebugOut('submit Selected') # get the questionnaire object aquaireObj = theSubmission.questionnaireID # construct a table with field names and field values # Again add pt id and header information respObj = theSubmission.respondentID respName = respondentName( respObj ) birthDay = str(respObj.birthDate) respondentDataCol = [ theSubmission.lastUpdate, respName, birthDay, aquaireObj.barTitle, aquaireObj.version, aquaireObj.versionDate, theSubmission.reviewedBy, theSubmission.reviewDate, theSubmission.okForExport, ] respondentQuestIDCol = [ 'Last updated', "Respondent's name", "Respondent's birthday", 'Questionnaire name', 'Questionnaire version', 'Questionnaire version date', 'Reviewed by', 'Review date', 'Ok for export?', ] submissionResponseTable = [] # put global flags and descriptions up front sessAnalysis = SubmissionAnalysis.objects.filter( submissionID = theSubmission) for aSessAnalysis in sessAnalysis: aGlobalFlag = aSessAnalysis.testResultFlag aGlobalFlagPriority = aSessAnalysis.testResultFlagPriority aGlobalFlagDescription = aSessAnalysis.testResultDescription submissionResponseTable.append([aGlobalFlag,"Priority: "+aGlobalFlagPriority,aGlobalFlagDescription,"Global Flag",""]) DebugOut('before responseQuestions') # get all possible questions and question tags [pageList, fieldList, theList, tagToText ] = ListQuestionsForQuestionnaire(aquaireObj) # get all response questions for this submission responseQuestions = Response.objects.filter(submissionID = theSubmission) DebugOut('number of entries in responseQuestions loop %s'%len(responseQuestions)) for aResponse in responseQuestions: theQuestionObj = aResponse.questionID thePageTag = aResponse.questionOnPageID.shortTag theQuestionTag = theQuestionObj.questionTag theQuestionText = strip_tags( theQuestionObj.questionText) responseType = theQuestionObj.responseType allRespForQuestionObj = ResponseSelection.objects.filter(responseID=aResponse) # for multiple choices for a question DebugOut('theQuestionTag: %s' %theQuestionTag) DebugOut('number of entries in allRespForQuestionObj loop %s'%len(allRespForQuestionObj)) responseList = [] numResponses = len(allRespForQuestionObj) # number of responses for a single question if numResponses == 1: # keyword and keyvalue responseRaw = allRespForQuestionObj[0].responseText responseList.append(responseRaw) elif numResponses > 1: # list of tags for aRespToQuestion in allRespForQuestionObj: responseRaw = aRespToQuestion.responseText DebugOut('responseRaw: %s' %responseRaw) # responseRaw is the responseChoice text # also append to a loop in case of multiple sub responses # translate tag to text responseList.append(responseRaw) else: DebugOut('No value for question tag %s, therefore "None"' %theQuestionTag) responseRaw = 'None' responseList.append(responseRaw) # convert from list to a string. if len(allRespForQuestionObj) == 0: responseText = 'None' else: responseText = ', '.join(responseList) # collect multiple responses for a question into a string DebugOut('Creating record for question tag %s' %theQuestionTag) DebugOut('responseText: %s' %responseText) submissionResponseTable.append([theQuestionTag,theQuestionText,responseText,responseType,thePageTag]) submissionResponseTableCols = [ 'Question tag', 'Question text', 'Response text', 'Response type', "On Page", ] fieldNameCol = respondentQuestIDCol + submissionResponseTableCols else: submissionResponseTable = '' # false submissionResponseTableCols = '' respondentQuestIDCol = '' respondentDataCol = '' currentContext = { 'submissionResponseTable' : submissionResponseTable, 'theProject' : theProject, 'submissionResponseTableCols' : submissionResponseTableCols, 'respondentDataCol' : respondentDataCol, 'respondentQuestIDCol' : respondentQuestIDCol, 'submitTableCols' : submitTableCols, 'submitTable' : submitTable, 'back_to_intro' : 'Return to the Home Page', 'url_base' : url_base, } DebugOut('responseViewer: exiting') return render(request, 'working_pages/responseViewer.html', currentContext) def savePtResponse(request): """This function moves Session data to the database""" # The respondent response is assumed to be in Session data DebugOut('savePtResponse: Enter') # must have the following data errmsg = [] if respondentIDDict in request.session: respIDDict = request.session[respondentIDDict] else: # return to respondent id page errmsg.append('savePtResponse: Pt data is missing.') if allResultsDict not in request.session: errmsg.append('savePtResponse: no questionnaire results data.') # process respondent identity, insert into database "Respondent". if "lastName" in respIDDict: lastName = respIDDict['lastName'].title() # capitalize each word respIDDict['lastName'] = lastName # save capitalized form else: # if no respondent name, return to splash screen errmsg.append('savePtResponse: Pt lastName is missing.') if "middleName" in respIDDict: middleName = respIDDict['middleName'].title() # capitalize each word respIDDict['middleName'] = middleName # save capitalized form else: # if no respondent name, return to splash screen pass # not required if "firstName" in respIDDict: firstName = respIDDict['firstName'].title() # capitalize each word respIDDict['firstName'] = firstName # save capitalized form else: # if no respondent name, return to splash screen errmsg.append('savePtResponse: Pt firstName is missing.') if "birthDate" in respIDDict: birthDate = respIDDict['birthDate'] else: # if no respondent bd, return to splash screen errmsg.append('Debug: Pt birthdate is missing.') current_date = timezone.now() DebugOut('Before calculate_ptAge_now( birthDate)') # DebugOut('birthdate converted to string %s' %str(birthDate)) # pt_currentAge = calculate_ptAge_now( birthDate) # pt_currentAge = calculate_ptAge_now( datetime.strptime(str(birthDate), '%Y-%m-%d')) pt_currentAge = '' DebugOut('After calculate_ptAge_now( birthDate)') # create a unique id ptUniqueID = uniquePTID(firstName, middleName, lastName, birthDate), if errmsg != []: DebugOut('syserrmsg: exiting with message: %s'%errmsg) return render(request, 'system_error.html', { 'syserrmsg': errmsg}) # create a record of the respondent, if it doesn't already exist try: therespondentID = Respondent.objects.get( ptUniqueID = ptUniqueID, ) DebugOut("savePtResponse: found respondent data") except Respondent.DoesNotExist: DebugOut("savePtResponse: Respondent doesn't already exist, so create it.") therespondentID = Respondent.objects.create( lastName = lastName, middleName = middleName, firstName = firstName, birthDate = birthDate, ptUniqueID = ptUniqueID, ) DebugOut('respIDDict: %s' %str(respIDDict)) # update optional fields if 'contactPhone' in respIDDict: therespondentID.contactPhone = respIDDict['contactPhone'] DebugOut("Saved contactPhone to respIDDict") if 'contactEmail' in respIDDict: therespondentID.contactEmail = respIDDict['contactEmail'] if 'externalID' in respIDDict: therespondentID.externalID = respIDDict['externalID'] if 'externalIDAuthority' in respIDDict: therespondentID.externalIDAuthority = respIDDict['externalIDAuthority'] therespondentID.save() DebugOut("savePtResponse: updated respondent data") # retrieve the current questionnaire object [theProject, quaire] = getSessionQuestionnaireProject(request) DebugOut('before creating a submission record') try: #create a submission record theSubmit = Submission( questionnaireID = quaire, # objects respondentID = therespondentID, # objects completedYN = True, okForExport = False, # not yet reviewed ) theSubmit.save() except: DebugOut('error saving Submission object.') return render(request, 'system_error.html', { 'syserrmsg': errmsg}) DebugOut('after creating a submission record') # Save analysis global flags, if any exist in this session if 'pageGlobalFlags' in request.session: allGlobalFlagsInSession = request.session['pageGlobalFlags'] for aGlobalFlag in allGlobalFlagsInSession: # get further information about the flag from the PageAnalysis table testResultFlagInfo = PageAnalysis.objects.filter( testResultFlag = aGlobalFlag, ) # select the first record since all descriptions and priorities should be the same for the same global flag! flagInfo = testResultFlagInfo[0] testResultFlagPriority = flagInfo.testResultFlagPriority testResultFlagDescription = flagInfo.testResultFlagDescription sessAnalysis = SubmissionAnalysis( submissionID = theSubmit, testResultFlag = aGlobalFlag, testResultFlagPriority = testResultFlagPriority, testResultDescription = testResultFlagDescription, ) sessAnalysis.save() # Retrieve a list of questionnaire results from Session data sessionResultList = request.session[allResultsList] # request.session[allResultsList] structure: # [questionResponse, questionText,questionRecNum,responseChoiceRecNum,pageShortTag,pageRecNum, uniqueQuestionLabel, questionTag] for aline in sessionResultList: # save each line to the database DebugOut('aline: %s' %aline) qResponse = aline[0] # user response to the question questionRecNum = aline[2] responseChoiceRecNum = aline[3] aPageTag = aline[4] uniqueTagWithEncoding = aline[6] qQuestionTag = aline[7] pageObj = Page.objects.get(id=int(aline[5])) theQuestionObj = Question.objects.get(id=int(questionRecNum)) qQuestionTag = theQuestionObj.questionTag if qResponse == '': pass DebugOut('syserrmsg: Error null value for question response %s' %qQuestionTag) aResp = Response.objects.create( questionID = theQuestionObj, questionOnPageID = pageObj, submissionID = theSubmit, ) if type(qResponse) == list: # oops, sub values! for aSubResponse in qResponse: # save multiple responses DebugOut('savePtResponse: list response: %s'%aSubResponse) aRSObj = ResponseSelection.objects.create( responseID = aResp, # responseChoiceID = responseText = aSubResponse, # This is ResponseChoice.choiceTag ) else: # a single response aRSObj = ResponseSelection.objects.create( responseID = aResp, # responseChoiceID = responseText = qResponse, # This is User response ) DebugOut('savePtResponse: Exit') return errmsg def savecsvDecoder(request): """Dumps file decoding tags found in the csv-type file of all submissions. Args: argument_one: This is of some type a and does x. arg....:... Returns: http response Raises: none. """ DebugOut('savecsvDecoder: Enter') # Create the HttpResponse object with the appropriate plain text header. response = HttpResponse(content_type='text/plain') now = str(timezone.now()) outdecodeFileName = "Questionnaire tag decoder %s.txt" %now[:26] # cut off time zone contentDispo = 'attachment; filename=' + '"' + outdecodeFileName + '"' response['Content-Disposition'] = contentDispo # get all Submissions and corresponding questionnaires allSubmissions = Submission.objects.all().order_by('-lastUpdate') theQIDs = [] for aSubmission in allSubmissions: theQIDs.append(aSubmission.questionnaireID.id) # make a queryset of all questionnaires referenced by the submissions allQObjs = retrieveBulk( Questionnaire, theQIDs ) for aQ in allQObjs: # for each questionnaire response.write('**********Questionnaire_separator'+os.linesep) # Questionnaire identification response.write('**********Questionnaire_identification'+os.linesep) response.write('Questionnaire short name: %s%s' %(aQ.shortTag,os.linesep)) response.write('Questionnaire description: %s%s' %(aQ.description,os.linesep)) response.write('Questionnaire version: %s%s' %(aQ.version,os.linesep)) response.write('Questionnaire version date: %s%s' %(aQ.versionDate,os.linesep)) response.write('Questionnaire last update: %s%s' %(aQ.lastUpdate,os.linesep)) response.write('Questionnaire primary key: %s%s' %(aQ.id,os.linesep)) # Project identification response.write('**********Project_identification'+os.linesep) theProject = getProjectObjForQuestionnaire(aQ) if theProject: # exists response.write('Project short name: %s%s' %(theProject.shortTag,os.linesep)) response.write('Project name: %s%s' %(theProject.name,os.linesep)) response.write('Project last update: %s%s' %(theProject.lastUpdate,os.linesep)) response.write('Project primary key: %s%s' %(theProject.id,os.linesep)) else: response.write('Project short name: %s%s' %('(None)',os.linesep)) response.write('Project name: %s%s' %('(None)',os.linesep)) response.write('Project last update: %s%s' %('(None)',os.linesep)) response.write('Project primary key: %s%s' %('(None)',os.linesep)) response.write('*********Field_decoding'+os.linesep) response.write('**********Field count : Field tag : Field text'+os.linesep) [pageList, fieldList, theList, tagToText ] = ListQuestionsForQuestionnaire(aQ) # decode all the fields fieldCount = 1 for aField in fieldList: response.write(fieldCount) # field count fieldCount+=1 [questionRecNum,responseChoiceRecNum] = decodeQuestionResponseLabel(aField) if questionRecNum: # use question tag qRec = int(questionRecNum) aFieldName = Question.objects.get(id=qRec).questionTag if responseChoiceRecNum: # use ResponseChoice tag. Overrides the question tag rcRec = int(responseChoiceRecNum) aFieldName = ResponseChoice.objects.get(id=rcRec).choiceTag response.write(' : ') response.write(strip_tags(aFieldName)) # field tag response.write(' : ') try: textValue = strip_tags(tagToText[aField]).replace("\r"," ").replace("\n"," ") except KeyError: textValue = 'Text not found' DebugOut('Text not found for tag: %s' %aField) response.write(textValue) response.write(os.linesep) DebugOut('savecsvDecoder: exit') return response def savepdf(request): """Dumps a pdf-type file of all pages in the default questinnaire. Args: http request Returns: http response Raises: none. """ DebugOut('savepdf: Enter') # Create the HttpResponse object with the appropriate PDF header. response = HttpResponse(content_type='application/pdf') now = str(timezone.now()) outpdfFileName = "Questionnaire Pages %s.pdf" %now[:16] # cut off time zone & seconds fraction contentDispo = 'attachment; filename=' + '"' + outpdfFileName + '"' response['Content-Disposition'] = contentDispo # Create the PDF object, using the response object as its "file." pdfObj = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. pdfObj.drawString(100, 500, "Hello world.") # Close the PDF object cleanly, and we're done. pdfObj.showPage() pdfObj.save() DebugOut('savepdf: Exit') return response @login_required() def dumpSubmissionDataForProject(request): """Dumps a csv-type file for all submissions pointing to questionnaires in a project. """ theProject = getSessionProject(request) if not theProject: # fall back to user default theUser = request.user theProject = getAssociatedProjectForUser(theUser) if not theProject: # Redirect if still no project redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) # output csv DebugOut('Output csv file for Proejct %s'%theProject.shortTag) result = savecsv(request, forProject=theProject) return result def toCSV(aListOfStrings): # Simple as possible. commaString = ','.join(aListOfStrings) commaString = commaString+'/n' return commaString def savecsv(request, forProject=None): """Dumps a csv-type file of all submissions. This is a one line or more descriptive summary. Blah Blah Blah. Args: argument_one: This is of some type a and does x. arg....:... Returns: http response Raises: none. """ DebugOut('savecsv: Enter') errMsg = [] # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') now = str(timezone.now()) outcsvFileName = "Questionnaire Responses %s.csv" %now[:16] # cut off time zone & seconds fraction contentDispo = 'attachment; filename=' + '"' + outcsvFileName + '"' response['Content-Disposition'] = contentDispo # dump the header text for respondent ID writer = csv.writer(response) # check if there are Submissions iCountSubmissions = Submission.objects.all().count() DebugOut('iCountSubmissions %s'%iCountSubmissions) if iCountSubmissions == 0: errMsg = 'Zero submissions available. No export submissions file created.' DebugOut(errMsg) return render(request, 'system_error.html', { 'syserrmsg': [errMsg]}) # get all global flags allGFlagRecs = SubmissionAnalysis.objects.all() for aRec in allGFlagRecs: DebugOut('aRec %s' %str(aRec)) # Make a list of unique flags. May be null globalFlagNames = list(set([aFlagRec.testResultFlag for aFlagRec in allGFlagRecs])) globalFlagNames.sort() DebugOut('globalFlagNames %s' %globalFlagNames) # Find if the scope is to a project. Get the questionnaires if forProject: theProject = forProject projectTag = theProject.shortTag allProjectsRaw = Project.objects.filter(shortTag=projectTag).order_by('-lastUpdate') # get "inactive" projects as well else: allProjectsRaw = Project.objects.all().order_by('-lastUpdate') # get "inactive" projects as well # remove Projects that have the wrong attribute allIDs = [] # collect the record numbers into a list for aProject in allProjectsRaw: # get the corresponding Attributes aProjectAttributes = getProjectAttributes(aProject) if 'Display' in aProjectAttributes: allIDs.append(aProject.id) elif 'DoNotDisplay' not in aProjectAttributes: allIDs.append(aProject.id) allProjects = retrieveBulk( Project, allIDs ) # get all questionnaires for all projects allQuestionnaireids = [] for aProject in allProjects: pqObjs = ProjectQuestionnaire.objects.filter(projectID=aProject) questRecList = [pqObj.questionnaireID.id for pqObj in pqObjs] allQuestionnaireids.extend(questRecList) uniqueQuestRecList = list(set(questRecList)) # make unique. Might be sharing! allQuestionnaires = retrieveBulk( Questionnaire, uniqueQuestRecList ).order_by('-lastUpdate','shortTag') if len(allQuestionnaires) == 0: if forProject: allerrMsg = ['No Questionnaires available for this project: %s.'%theProject.shortTag] else: allerrMsg = ['No Questionnaires available'] allerrMsg.append('No export submissions file created.') DebugOut(allerrMsg) urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': allerrMsg, 'wsgiPrefix':urlPrefix}) # Loop through Questionnaires, Pages, Questions, ResponseChoices in a standard way icountExports = 0 # count the exported submissions for aQuestionnaire in allQuestionnaires: DebugOut('Top of Questionnaire loop') submissionsForQuestionnaire = Submission.objects.filter(questionnaireID=aQuestionnaire) # A requirement is to maintain the same order for the same questionnaire, for each Submission # Start with getting the pages in canonical order allPages = allPagesInDefaultOrder(aQuestionnaire) DebugOut( 'Pages in Questionnaire "%s": "%s"'%(aQuestionnaire.shortTag,len(allPages))) DebugOut( 'Number of Submissions "%s" in Questionnaire "%s"'%(submissionsForQuestionnaire.count(),aQuestionnaire.shortTag)) oldHeaderCopy = [] # save the old header here DebugOut('Submissions loop') for aSubmission in submissionsForQuestionnaire: DebugOut('Top of submissions loop') aRow = [] # add respondent ID, questionnaire ID, question responses colm_headers = [] # save the new header here icountExports+=1 # Dump the Submission record aRow.append(aSubmission.lastUpdate) colm_headers.append('lastUpdate') aRow.append(aSubmission.reviewedBy) colm_headers.append('reviewedBy') aRow.append(aSubmission.reviewDate) colm_headers.append('reviewDate') aRow.append(aSubmission.okForExport) colm_headers.append('okForExport') # dump questionnaire data # dump Respondent data responderObj = aSubmission.respondentID DebugOut('Unique patient id: %s' %responderObj.ptUniqueID) # Respondent fields respFields = ['lastName', 'middleName', 'firstName', 'birthDate', 'contactPhone', 'contactEmail', 'externalID', 'externalIDAuthority'] for respField in respFields: # process respondent identifiction try: theItem = unicode(getattr(responderObj, respField)).encode('utf-8') aRow.append(theItem) #DebugOut('respField field: %s value: %s' %(respField,theItem)) colm_headers.append(respField) except AttributeError: DebugOut('syserrmsg: respField field: %s not found in database.' %(respField)) except: DebugOut('syserrmsg: respField field: %s error in db retrieval' %(respField)) # process questionnaire name and version aquaireObj = aSubmission.questionnaireID # Project shortTag projectShortTag = getProjectObjForQuestionnaire(aquaireObj).shortTag aRow.append(projectShortTag) colm_headers.append('Project') # Questionnaire fields ************************** BEGIN aRow.append(aquaireObj.shortTag) colm_headers.append('Questionnaire') aRow.append(aquaireObj.version) colm_headers.append('version') aRow.append(aquaireObj.versionDate) colm_headers.append('versionDate') aRow.append(aquaireObj.language) colm_headers.append('language') # Questionnaire fields ************************** END # retrieve any global flags for this submission *** BEGIN # sort the flags so that the order is the same for different submissions theFlagInfo = SubmissionAnalysis.objects.order_by( 'testResultFlag','testResultFlagPriority').filter( submissionID = aSubmission, ) allFlagsThisSubmit = [aGlobalFlag.testResultFlag for aGlobalFlag in theFlagInfo] DebugOut('allFlagsThisSubmit: %s' %allFlagsThisSubmit) for aFlag in globalFlagNames: colm_headers.append(aFlag) if aFlag in allFlagsThisSubmit: aRow.append("Yes") else: aRow.append("No") # retrieve any global flags for this submission *** END # retrieve all Response objects belonging to this Submission allResponses = Response.objects.filter(submissionID=aSubmission) DebugOut('Response count: %s'%allResponses.count()) fieldCount = 1 for aPage in allPages: DebugOut('top of Page loop: %s'%aPage.shortTag) allQuestionsOnPage = getPageQuestions( aPage) for aQuestion in allQuestionsOnPage: DebugOut('top of Question loop') questionid = aQuestion.id # Select the response (if any) questionTag = aQuestion.questionTag DebugOut('Question tag: %s'%questionTag) responsesPerQuestion = allResponses.filter(questionID=aQuestion) # select only one if multiple. # "responsesPerQuestion" a Response queryset DebugOut('Number of responses for this question: %s'%responsesPerQuestion.count()) if responsesPerQuestion: if responsesPerQuestion.count() >1: # more than one response to a question. Choose one. # Question appears more than once in a Questionnaire # Note the error condition DebugOut('syserrmsg: Question "%s" appears more than once in "%s"'%(questionTag,aQuestionnaire.shortTag)) DebugOut('syserrmsg: Arbitrarily select one question for output into the csv') theResponse = responsesPerQuestion[0] # choose arbitrarily responseSelections = ResponseSelection.objects.filter(responseID=theResponse) # Question asked responseValues = [rpq.responseText for rpq in responseSelections] # Gather all responses DebugOut('responseValues: %s'%responseValues) elif responsesPerQuestion.count() == 0: # No response, but add header info at top of column # provide for strange case of Question asked, but no responses responseValues = [] DebugOut('No response to Question %s'%questionTag) # aRow.append('') # colm_headers.append(questionTag+'_'+str(fieldCount)) # choice text is the tag # fieldCount+=1 # break # go to next question # now consult the Questionnaire design for a list of all responses responseChoices = ResponseChoice.objects.order_by('choiceSequence').filter(questionID=aQuestion) # may be none allResponsechoices = [arc.choiceText for arc in responseChoices] # responseValues is from the User, allResponsechoices is from the Questionnaire design DebugOut('responseValues "%s", allResponsechoices "%s"'%(responseValues,allResponsechoices)) if len(responseValues) > 1 and len(allResponsechoices) == 0: DebugOut('syserrmsg: multiple choices for a non-muliple choice question!! Question: "%s"'%questionTag) elif len(responseValues) > len(allResponsechoices) > 0: DebugOut('syserrmsg: more responses than choices!!') if len(allResponsechoices) > 0 and len(responseValues) > 0: theValue = 'Multiple Choice Question' # a list elif len(allResponsechoices) > 0 and len(responseValues) == 0: theValue = 'No Choice Selected' # a list elif len(responseValues) == 1: # one value theValue = smart_str(responseValues[0]) else: DebugOut('Question result: '+questionTag+'_'+str(fieldCount)+' Null result') theValue = '' DebugOut('Question result: '+questionTag+'_'+str(fieldCount)+' The Value: ' +str(theValue)) aRow.append(theValue) colm_headers.append(questionTag+'_'+str(fieldCount)) # choice text is the tag fieldCount+=1 if responseChoices: # examine a list of all possible responses per question # Question is multiple choice # top of a list. Name of a list. Values are placed in the following loop # multiple choice per record. Perhaps none selected. for aResponseChoice in responseChoices: DebugOut('top of ResponseChoice per Question loop') # create the unique record which might be a response, if there is any response. choiceText = aResponseChoice.choiceText choiceTag = aResponseChoice.choiceTag DebugOut('choiceText: "%s", choiceTag: "%s"'%(choiceText, choiceTag)) # DebugOut('choiceText: "%s", responseValues: "%s"'%(choiceText, responseValues)) # DebugOut('choiceText type: "%s", responseValues type: "%s"'%(type(choiceText), type(responseValues))) # if len(responseValues) >0: # DebugOut('element type: "%s"'%type(responseValues[0])) if choiceText in responseValues: # check for this response aRow.append(choiceText) colm_headers.append(choiceTag+'_'+str(fieldCount)) # choice text is the tag DebugOut('choiceText: "%s" added to row string.'%(choiceText)) else: aRow.append('') DebugOut('choiceText: "%s" NOT added to row string.'%(choiceText)) colm_headers.append(choiceTag+'_'+str(fieldCount)) # choice text is the tag fieldCount+=1 DebugOut('End of responses') DebugOut('Row %s' %aRow) if oldHeaderCopy != colm_headers: writer.writerow(colm_headers) oldHeaderCopy = list(colm_headers) # Save the new header if different colm_headers = list([]) # annihilate the current list writer.writerow(aRow) # append the submission to the csv file DebugOut('After writing a row') if icountExports == 0: if forProject: allerrMsg = ['No Submissions available for this project: %s.'%theProject.shortTag] else: allerrMsg = ['No Submissions available'] allerrMsg.append('No export submissions file created.') DebugOut(allerrMsg) urlPrefix = request.get_host()+settings.WSGI_URL_PREFIX return render(request, 'InfoScreenExit.html', { 'errMsg': allerrMsg, 'wsgiPrefix':urlPrefix}) DebugOut('savecsv: Exit') return response def displayAndEditQuestion(request): # select a question to add to the page. # find all existing question shortTag's try: allQuestions=Question.objects.all().order_by('questionTag') except: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Question data is missing.']}) allQuestionTags = [allQuestions.questionTag for allQuestions in allQuestions] # list comprehension # select a default question tag to start. if 'currentQuestionTag' in request.session: # first look in sessions data currentQuestionTag = request.session['currentQuestionTag'] else: # if not in sessions data, then use last tag currentQuestionTag = allQuestionTags[-1] request.session['currentQuestionTag'] = currentQuestionTag try: # try to retrieve the question theQuestion=Question.objects.get(questionTag=currentQuestionTag) except Question.DoesNotExist: # done everything, so bail return render(request, 'system_error.html', {'syserrmsg': ['Debug: Most recent question data is missing.']}) pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' oldQuestionTag = currentQuestionTag # check for a change on the other side of this if statement if request.method == 'POST': theForm = QuestionForm( request.POST) if 'submitButton' in request.POST: if request.POST['submitButton'] == 'Discard Question Edits': # Return to previous page return HttpResponseRedirect(pageBaseURL+'intro/') # previous screen url if theForm.is_valid(): currentQuestionTag = theForm.cleaned_data['questionTag'] # may be overridden by text box if 'questionTag' in request.POST: currentQuestionTag = request.POST['questionTag'] request.session['currentQuestionTag'] = currentQuestionTag if 'submitButton' in request.POST: if request.POST['submitButton'] == 'Save Question Edits': theQuestion.questionTag = currentQuestionTag theQuestion.questionText = theForm.cleaned_data['questionText'] theQuestion.description = theForm.cleaned_data['description'] theQuestion.responseType = theForm.cleaned_data['responseType'] theQuestion.lastUpdate = timezone.now() theQuestion.save() responseMsg = 'Question "%s" edited and saved.' %currentQuestionTag request.session['currentQuestionTag'] = currentQuestionTag elif request.POST['submitButton'] == 'Delete Current Question': # Return to previous page Question.objects.filter(shortTag=currentQuestionTag).delete() return HttpResponseRedirect(pageBaseURL+'intro/') # previous screen url else: initialValues ={'questionTag' : currentQuestionTag, 'questionText' : theQuestion.questionText, 'description' : theQuestion.description, 'responseType' : theQuestion.responseType, 'lastUpdate' : theQuestion.lastUpdate, } theForm = QuestionForm(initial=initialValues) if currentQuestionTag != oldQuestionTag: try: # try to retrieve the question theQuestion=Question.objects.get(questionTag=currentQuestionTag) except Question.DoesNotExist: # done everything, so bail return render(request, 'system_error.html', {'syserrmsg': ['Debug: Most recent question data is missing.']}) currentContext = { 'theForm' : theForm, 'questionTag' : currentQuestionTag, 'allQuestionTags' : allQuestionTags, 'lastUpdate' : theQuestion.lastUpdate, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, } return render(request, 'working_pages/displayAndEditQuestion.html', currentContext) def createPageQuestionLink(request): DebugOut( 'createPageQuestionLink: Enter.') # Create a link from a page to one or more questions. # find all existing page shortTag's try: allP=Page.objects.all() except: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Page data is missing.']}) allPageTags = [aPage.shortTag for aPage in allP] pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' # find all existing question shortTag's try: allQuestions=Question.objects.all() except: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Question data is missing.']}) allQuestionTags = [aQuestion.questionTag for aQuestion in allQuestions] # Find all existing Page/Question links pqLinks = PageQuestion.objects.all() pqList = [] for pq in pqLinks: pqList.append([ pq.pageID.shortTag, pq.questionID.questionTag, pq.questionID.questionText ]) # select a default page tag to start. if 'currentPageTag' in request.session: # first look in sessions data currentPageTag = request.session['currentPageTag'] else: # if not in sessions data, then use last tag currentPageTag = allPageTags[-1] request.session['currentPageTag'] = currentPageTag if 'currentQuestionTag' in request.session: # first look in sessions data currentQuestionTag = request.session['currentQuestionTag'] else: # if not in sessions data, then use last tag currentQuestionTag = allQuestionTags[-1] request.session['currentQuestionTag'] = currentQuestionTag try: # try to retrieve the page thePage=Page.objects.get(shortTag=currentPageTag) except Page.DoesNotExist: # so set to a legal value theMess = 'System error: Page data is missing for tag: %s. Select a different page.' %currentPageTag DebugOut(theMess) errmsg.append(theMess) try: # try to retrieve the question theQuestion=Question.objects.get(questionTag=currentQuestionTag) except Question.DoesNotExist: # done everything, so bail theMess = 'System error: Question data is missing for tag: %s. Select a different question.' %currentQuestionTag DebugOut(theMess) errmsg.append(theMess) errmsg = [] newPage = False newQuestion = False if request.method == 'POST': theForm = PageQuestionLinkForm( request.POST) if 'pageSelection' in request.POST: currentPageTag = request.POST['pageSelection'] request.session['currentPageTag'] = currentPageTag newPage = True elif 'submitButton' in request.POST: if request.POST['submitButton'] == 'Return to Introduction': # Return to Intro DebugOut( 'button: Return to introduction.') # Save the cleaned data return HttpResponseRedirect(settings.WSGI_URL_PREFIX + 'multiquest/'+'intro/') # previous screen url elif request.POST['submitButton'] == 'Save Question to Page': # Attach question to page DebugOut( 'button: Save Question to Page.') # Save the cleaned data if theForm.is_valid(): # have valid data from page DebugOut( 'Form is valid. Saving data.') # Save the cleaned data qs = theForm.cleaned_data # save only this page data for redisplay of the page DebugOut('thePage: %s' %str(thePage)) DebugOut('theQuestion: %s' %str(theQuestion)) try: pageQuest = PageQuestion(pageID=thePage, questionID=theQuestion, questionSequence=qs) pageQuest.save() except: errmsg.append('Select a page and question to be added to the page.') else: DebugOut( 'Form is not valid. Not saving data.') # Save the cleaned data elif 'questionSelection' in request.POST: currentQuestionTag = request.POST['questionSelection'] request.session['currentQuestionTag'] = currentQuestionTag DebugOut('The new current question is: %s' %currentQuestionTag) newQuestion = True else: # not a POST theForm = PageQuestionLinkForm() if newPage: try: # try to retrieve the page thePage=Page.objects.get(shortTag=currentPageTag) except Page.DoesNotExist: # so set to a legal value theMess = 'System error: Page data is missing for tag: %s. Select a different page.' %currentPageTag DebugOut(theMess) errmsg.append(theMess) if newQuestion: try: # try to retrieve the question theQuestion=Question.objects.get(questionTag=currentQuestionTag) except Question.DoesNotExist: # done everything, so bail theMess = 'System error: Question data is missing for tag: %s. Select a different question.' %currentQuestionTag DebugOut(theMess) errmsg.append(theMess) try: thePageQuestionLinks=PageQuestion.objects.filter(pageID=thePage) # Extract all questions for thePage questionsForThisPage = [aQuestion.questionID.questionText for aQuestion in thePageQuestionLinks] except PageQuestion.DoesNotExist: theMess = 'page/question link not found for page "%s"' %thePage DebugOut(theMess) questionsForThisPage = [] except: theMess = 'Error: page/question link not found for page "%s"' %thePage DebugOut(theMess) questionsForThisPage = [] DebugOut('errmsg: %s' %str(errmsg)) DebugOut( 'createPageQuestionLink: Exit.') currentContext = { 'theForm' : theForm, 'errmsg' : errmsg, 'pqList' : pqList, 'currentPageTag' : currentPageTag, 'currentQuestionTag' : currentQuestionTag, 'allQuestionTags' : allQuestionTags, 'allPageTags' : allPageTags, 'questionsForThisPage' : questionsForThisPage, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, } return render(request, 'working_pages/createPageQuestionLink.html', currentContext) def setPageToPageTransitionGlobalFlags(request): # determine page transition depending upon the existence of a global flag DebugOut('setPageToPageTransitionGlobalFlags: entering') # select a default Questionnaire and Project tag to start. [workingProject, workingQuestionnaire] = getSessionQuestionnaireProject(request) if not workingQuestionnaire: errMsg = ['The questionnaire has not been selected'] return render(request, 'system_error.html', { 'syserrmsg': errMsg}) # Retrieve the Questionnaire Tag workingQuestionnaireTag=workingQuestionnaire.shortTag # Retrieve the Project tag workingProjectTag=workingProject.shortTag # notice the entire object is stored! # find all existing page shortTag's for this questionnaire allPageObjs = getAllPageObjsForQuestionnaire(workingQuestionnaire) allPageTags = getAllPageTags(workingQuestionnaire) DebugOut('allPageTags: %s' %allPageTags) # select a default page tag to start. This is the 'from' page. currentPageSessionTag = 'currentPageTag_admin' [workingPageTag, theWorkingPage] = selectCurrentPage(request, currentPageSessionTag, allPageObjs) errMsgs = [] # got all starting data DebugOut('Default values:') DebugOut('workingQuestionnaireTag: %s' %workingQuestionnaireTag) DebugOut('workingPageTag: %s' %workingPageTag) pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' + workingProjectTag+'/'+workingQuestionnaireTag+'/' #request.session['pageBaseURL'] = pageBaseURL # not sure if this is needed if 'globalFlagSelect' in request.session: globalFlagSelect = request.session['globalFlagSelect'] else: globalFlagSelect = '' if 'nextPageGlobalFlag' in request.session: nextPageGlobalFlag = request.session['nextPageGlobalFlag'] else: nextPageGlobalFlag = '' flagAndConditionMsg = '' # msg to user "Global flag is, and test condition is" nextPAndConditionMsg = '' # message that the test condition was saved to the database needMsg = '' if request.method == 'POST': DebugOut('setPageToPageTransitionGlobalFlags: After POST') DebugOut('request.POST %s' %str(request.POST)) if 'submitButton' in request.POST: DebugOut('Submit button hit') if request.POST['submitButton'] == 'Return to the administration page': # Return to previous page return HttpResponseRedirect(settings.WSGI_URL_PREFIX + 'multiquest/'+'intro/') # previous screen url else: # clicked on a page button - change working page workingPageTag = request.POST['submitButton'] try: theWorkingPage=Page.objects.get(shortTag=workingPageTag) DebugOut('The new working page: %s' %workingPageTag) except Page.DoesNotExist: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Page does not exist: %s' %workingPageTag]}) request.session[currentPageSessionTag] = theWorkingPage.id elif 'globalFlagSelectButton' in request.POST: # select a global flag globalFlagSelect = request.POST['globalFlagSelectButton'] request.session['globalFlagSelect'] = globalFlagSelect DebugOut('The new global flag selected: %s' %globalFlagSelect) elif 'nextPageGlobalFlagButton' in request.POST: # select a NEXT page if the global flag exists at runtime nextPageGlobalFlag = request.POST['nextPageGlobalFlagButton'] request.session['nextPageGlobalFlag'] = nextPageGlobalFlag DebugOut('The new global flag "next page" selection: %s' %nextPageGlobalFlag) elif 'deleteSelection' in request.POST: # delete the selected record # delete the selected line from the condition table lineSelect = int(request.POST['deleteSelection']) - 1 # line selected [transitionGlobalFlags, success] = getGlobalFlagTransitions(workingQuestionnaire) # record structure is: # record number, global flag name, next page short tag, global flag priority recSelect = transitionGlobalFlags[lineSelect][0] deleteTestConditonFromQuestionnairePage(recSelect) elif 'saveToDBButton' in request.POST: if globalFlagSelect and nextPageGlobalFlag: recordType = 'globalFlag' saveTestConditonToQuestionnairePage(globalFlagSelect, nextPageGlobalFlag, theWorkingPage, workingQuestionnaire, recordType) flagAndConditionMsg = 'The global flag "%s" and the next page "%s" were saved' %(globalFlagSelect, nextPageGlobalFlag) needMsg = [] if not globalFlagSelect: needMsg.append('Please select a global flag') if not nextPageGlobalFlag: needMsg.append('Please select a "next page" transition when the global flag, "%s" is present.' %globalFlagSelect) else: # a 'GET' # obtain any prior setting for 'next page' DebugOut('"GET" posted - restore data if any') # Retrieve all global flags allGlobalFlags = listAllGlobalFlags(workingQuestionnaire) DebugOut('allGlobalFlags: %s' %allGlobalFlags) if 'nextPageGlobalFlag' in request.session: nextPageGlobalFlag = request.session['nextPageGlobalFlag'] else: nextPageGlobalFlag = '' # pgNext = retrieveDefaultNextPage(workingQuestionnaireTag, workingPageTag) # delete this line after confimation pageToPageRecs = getPageToPageObjs(workingQuestionnaire) pgNext = (pageToPageRecs[theWorkingPage]).shortTag # test retrieve barTitle=workingQuestionnaire.barTitle DebugOut('barTitle: %s' %barTitle) if allGlobalFlags == ['']: globalFlagExist = False else: globalFlagExist = True [transitionGlobalFlags, success] = getGlobalFlagTransitions(workingQuestionnaire) if not success: DebugOut('Unsuccessful retrieval of global flag info.') transitionGlobalFlags = '' DebugOut('globalFlagSelect: %s' %globalFlagSelect) DebugOut('allGlobalFlags: %s' %allGlobalFlags) DebugOut('globalFlagSelect: %s' %globalFlagSelect) DebugOut('nextPageGlobalFlag: %s' %nextPageGlobalFlag) DebugOut('globalFlagExist: %s' %globalFlagExist) currentContext = { 'workingPageTag' : workingPageTag, 'pgNext' : pgNext, 'allPageTags' : allPageTags, 'globalFlagExist' : globalFlagExist, 'allGlobalFlags' : allGlobalFlags, 'globalFlagSelect' : globalFlagSelect, 'nextPageGlobalFlag' : nextPageGlobalFlag, 'transitionGlobalFlags' : transitionGlobalFlags, 'nextPAndConditionMsg' : nextPAndConditionMsg, 'flagAndConditionMsg' : flagAndConditionMsg, 'barTitle' : barTitle, 'errMsgs' : errMsgs, 'needMsg' : needMsg, 'workingQuestionnaireTag' : workingQuestionnaireTag, } DebugOut('setPageToPageTransitionGlobalFlags: exiting') return render(request, 'working_pages/setPageToPageTransitionGlobalFlags.html', currentContext) def setGlobalFlags(request): # Set global flags based upon response to questions. DebugOut('setGlobalFlags: entering') # select a default Questionnaire and Project tag to start. [workingProject, workingQuestionnaire] = getSessionQuestionnaireProject(request) if not workingQuestionnaire: errMsg = ['The questionnaire has not been selected'] return render(request, 'system_error.html', { 'syserrmsg': errMsg}) # refresh # Retrieve the Questionnaire Tag workingQuestionnaireTag=workingQuestionnaire.shortTag barTitle=workingQuestionnaire.barTitle # find all existing pages with questions for this questionnaire allPageObjs = findAllPageObjWQuestions(workingQuestionnaire) allPageTags = [anObj.shortTag for anObj in allPageObjs] if not allPageTags: # no tags return render(request, 'system_error.html', {'syserrmsg' :["No pages have questions for this questionnaire %s"%workingQuestionnaireTag]}) # select a default page tag to start. This is the 'from' page. if 'setGlobalFlags_pageid' in request.session: [theWorkingPageid, workingPageTag] = request.session['setGlobalFlags_pageid'] theWorkingPage = Page.objects.get(id=theWorkingPageid) else: theWorkingPage = allPageObjs[0] # Select a default starting page (no prior selection) workingPageTag = theWorkingPage.shortTag request.session['setGlobalFlags_pageid'] = [theWorkingPage.id, workingPageTag] # retrieve the questions on this page DebugOut('theWorkingPage before getPageQuestions: %s' %theWorkingPage) thePageQuestions=getPageQuestions(theWorkingPage) DebugOut('thePageQuestions after getPageQuestions: %s' %thePageQuestions) if 'globalFlagSelect' in request.session: # Global flag has already been entered or selected DebugOut('globalFlagSelect exists') globalFlagExists = True theGlobalFlag = request.session['globalFlagSelect'] else: DebugOut('globalFlagSelect does not exist in session data') theGlobalFlag = '' globalFlagExists = False if 'globalFlagSelectPriority' in request.session: theGlobalFlagPriority = request.session['globalFlagSelectPriority'] else: theGlobalFlagPriority = '' if 'globalFlagSelectDescription' in request.session: theGlobalFlagDescription = request.session['globalFlagSelectDescription'] else: theGlobalFlagDescription = '' if 'globalFlagEntered' in request.session: # display previous entry for the global flag form theForm = setGlobalFlagForm(request.session['globalFlagEntered']) # three values in form: globalFlagExists = True else: # display a pristine form theForm = setGlobalFlagForm() if 'testCondition_exists' in request.session: # a test condition has already been entered testCondition = request.session['testCondition_exists'] [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, testCondition, useQuestionTag=True) # theQForm collects responses to questions which become the testCondition else: [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) testCondition = '' flagAndConditionMsg = False errMsgs = '' if request.method == 'POST': DebugOut('request.POST: %s' %request.POST) if 'currentPageButton' in request.POST: # Select the CURRENT page for calculation workingPageTag = request.POST['currentPageButton'] DebugOut('The new working page: %s' %workingPageTag) [theWorkingPage, success] = getPageObj(workingQuestionnaire, workingPageTag) # should never fail!? if success: request.session['setGlobalFlags_pageid'] = [theWorkingPage.id, theWorkingPage.shortTag] thePageQuestions=getPageQuestions(theWorkingPage) [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) else: errMsgs = 'Page "%s" not found.' %workingPageTag elif 'SubmitResponsesButton' in request.POST: # write to database DebugOut('SubmitResponsesButton: enter') # question responses have been entered [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, request.POST, useQuestionTag=True) if theQForm.is_valid(): DebugOut('SubmitResponsesButton: theQForm.is_valid') # collect question responses which become the test condition testCondition = theQForm.cleaned_data request.session['testCondition_exists'] = testCondition DebugOut('testCondition: %s' %testCondition) DebugOut('globalFlagExists: %s' %globalFlagExists) [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, testCondition, useQuestionTag=True) if globalFlagExists: DebugOut('SubmitResponsesButton: globalFlagExists') createGlobalFlagRecord(workingQuestionnaire, theWorkingPage, testCondition, theGlobalFlag, theGlobalFlagPriority, theGlobalFlagDescription) flagAndConditionMsg = True DebugOut('Saved tag %s with test condition %s' %(theGlobalFlag,testCondition)) else: [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, request.POST, useQuestionTag=True) elif 'analysisAlternatives' in request.POST: # write to database # Set flag when any button is "yes" # no need to check theQForm. # verify existence of global flag DebugOut('Save analy flag') [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) testCondition = testCondChoices[request.POST['analysisAlternatives']] # get button text indicating condition if globalFlagExists: createGlobalFlagRecord(workingQuestionnaire, theWorkingPage, testCondition, theGlobalFlag, theGlobalFlagPriority, theGlobalFlagDescription) flagAndConditionMsg = True DebugOut('Saved tag %s with test condition %s' %(theGlobalFlag,testCondition)) elif 'deleteSelection' in request.POST: # delete the selected record # delete the selected line from the global flag list delTag = request.POST['deleteSelection'] globalFlagExists = False DebugOut('delTag: %s' %delTag) recSelect = int(delTag[4:]) # extract list number (not the same as the record number) DebugOut('recSelect: %s' %recSelect) allGlobalFlagsRecordList = request.session['allGlobalFlagsRecordList'] DebugOut('allGlobalFlagsRecordList %s' %allGlobalFlagsRecordList) recNum = allGlobalFlagsRecordList[recSelect][4] # record to delete DebugOut('recNum: %s' %recNum) deleteGlobalFlagRecord(workingQuestionnaire, recNum) [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) elif 'globalFlagEnteredButton' in request.POST: # A new global flag name entered DebugOut('globalFlagEnteredButton: enter') # collect name for for global flag theForm = setGlobalFlagForm(request.POST) if theForm.is_valid(): DebugOut('theForm.cleaned_data: %s' %theForm.cleaned_data) theGlobalFlag = theForm.cleaned_data['testResultFlag'] theGlobalFlagPriority = theForm.cleaned_data['testResultFlagPriority'] theGlobalFlagDescription = theForm.cleaned_data['testResultFlagDescription'] # save forms output to session data request.session['globalFlagEntered'] = theForm.cleaned_data # save variables to session data globalFlagExists = True request.session['globalFlagSelect'] = theGlobalFlag request.session['globalFlagSelectPriority'] = theGlobalFlagPriority request.session['globalFlagSelectDescription'] = theGlobalFlagDescription [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) DebugOut('globalFlagEnteredButton: exit') elif 'globalFlagSelectButton' in request.POST: # A different global flag is selected from the displayed list of previously existing global flags # save variables to session data theGlobalFlag = request.POST['globalFlagSelectButton'] [theGlobalFlagPriority, theGlobalFlagDescription, success] = getGlobalFlagPriority(workingQuestionnaire, theGlobalFlag) # get the priority DebugOut('Global flag selected: %s' %theGlobalFlag) globalFlagExists = True request.session['globalFlagSelect'] = theGlobalFlag request.session['globalFlagSelectPriority'] = theGlobalFlagPriority request.session['globalFlagSelectDescription'] = theGlobalFlagDescription [theQForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) DebugOut('The global flag selected: %s' %theGlobalFlag) elif 'submitButton' in request.POST: # return to the admin page return HttpResponseRedirect(settings.WSGI_URL_PREFIX + 'multiquest/'+'intro/') # previous screen url else: # a 'GET' # obtain any prior setting for 'next page' pass DebugOut('"GET" posted - restore data if any') # Retrieve all global flags allGlobalFlags = listAllGlobalFlags(workingQuestionnaire) DebugOut('allGlobalFlags: %s' %allGlobalFlags) if 'globalFlagSelect' in request.session: # Global flag has already been entered or selected DebugOut('globalFlagSelect exists') globalFlagExists = True theGlobalFlag = request.session['globalFlagSelect'] else: DebugOut('globalFlagSelect does not exist in session data') theGlobalFlag = '' globalFlagExists = False if 'globalFlagSelectPriority' in request.session: theGlobalFlagPriority = request.session['globalFlagSelectPriority'] else: theGlobalFlagPriority = '' if 'globalFlagSelectDescription' in request.session: theGlobalFlagDescription = request.session['globalFlagSelectDescription'] else: theGlobalFlagDescription = '' # retrieve the questions on the page (theWorkingPage may have changed) DebugOut('theWorkingPage now: %s' %theWorkingPage) DebugOut('theWorkingPage type: %s' %type(theWorkingPage)) thePageQuestions=getPageQuestions(theWorkingPage) DebugOut('thePageQuestions after getPageQuestions #2: %s' %thePageQuestions) otherAnalysisOption = allYesNoTypeQuestions( thePageQuestions ) # List all global flags set by all pages allGlobalFlagsRecordList = listGlobalFlagsInfo(workingQuestionnaire) request.session['allGlobalFlagsRecordList']=allGlobalFlagsRecordList # build a similar list just for this page allGlobalFlagsRecordDict = getGlobalFlagRecord(workingQuestionnaire) testConditionTransitionList = [] for item in allGlobalFlagsRecordDict: ptag = Page.objects.get(id=item['pageID']).shortTag if ptag == workingPageTag: testConditionTransitionList.append([item['testCondition'],item['testResultFlag'],item['testResultFlagPriority']]) if len(testConditionTransitionList) == 0: testConditionTransitionList = '' currentContext = { 'theQForm' : theQForm, 'theForm' : theForm, 'globalFlagExists' : globalFlagExists, 'allGlobalFlags' : allGlobalFlags, 'allGlobalFlagsRecordList' : allGlobalFlagsRecordList, 'theGlobalFlag' : theGlobalFlag, 'theGlobalFlagPriority' : theGlobalFlagPriority, 'flagAndConditionMsg' : flagAndConditionMsg, 'workingQuestionnaireTag' : workingQuestionnaireTag, 'workingPageTag' : workingPageTag, 'allPageTags' : allPageTags, 'testConditionTransitionList' : testConditionTransitionList, 'otherAnalysisOption' : otherAnalysisOption, 'allYesButton' : allYesButton, 'anyYesButton' : anyYesButton, 'allNoButton' : allNoButton, 'anyNoButton' : anyNoButton, 'anySelectedButton' : anySelectedButton, 'noneSelectedButton' : noneSelectedButton, 'barTitle' : barTitle, 'errMsgs' : errMsgs, } DebugOut('setGlobalFlags: exiting') return render(request, 'working_pages/setGlobalFlags.html', currentContext) def allYesNoTypeQuestions( thePageQuestions ): # check if all questions are of the "yes/no" variety otherAnalysisOption = False questTypeList = [] for aQuest in thePageQuestions: respTyp = aQuest.responseType if 'SingleChoiceField' == respTyp: # special handling # Special handling for 'SingleChoiceField' - check the choices theResponseChoice = ResponseChoice.objects.filter(questionID=aQuest) responseList = [aResp.choiceTag for aResp in theResponseChoice] DebugOut('allYesNoTypeQuestions: responseList %s' %responseList) if responseList.sort() == ['Yes','No'].sort(): # responses delivered will be only yes no, so "acts like" yes/no question type respTyp = 'YesNoField' questTypeList.append(respTyp) DebugOut('Question type list: %s' %questTypeList) # Find if the question response data fields are all of one type. # The supported homogeneous data types are YesNoField and MultipleChoiceField. if len(questTypeList) >1: theResponseType =list(set(questTypeList)) # should be one element if all one response type if len(theResponseType) >1: otherAnalysisOption = "DoNotDisplay" # forget it. Question responses must be of homogeneous type. elif len(theResponseType) == 1: if theResponseType[0] == 'YesNoField': otherAnalysisOption = 'YesNoField' # allow, all_yes, any_yes, all_no, any_no # store this value - bleed00 elif theResponseType[0] == 'MultipleChoiceField': otherAnalysisOption = 'MultipleChoiceField' # allow, all_slected, some_selected, none_selected # store this value - bleed00 # forget the other options. Not yet implemented elif len(questTypeList) == 1: if questTypeList[0] == 'MultipleChoiceField': otherAnalysisOption = 'MultipleChoiceField' else: # must have more than one question to display for otherAnalysisOption = "DoNotDisplay" else: otherAnalysisOption = "DoNotDisplay" # no question types return otherAnalysisOption def deleteGlobalFlag(workingQuestionnaire, theGlobalFlagToDelete): # Delete the global flag from PageAnalysis PageAnalysis.objects.filter( questionnaireID = workingQuestionnaire, testResultFlag = theGlobalFlagToDelete, ).delete() return True @login_required() def setPageToPageTransitionCalculated(request): # Set "next page" transition based upon response to questions. DebugOut('setPageToPageTransitionCalculated: entering') # select a default Questionnaire and Project tag to start. [workingProject, workingQuestionnaire] = getSessionQuestionnaireProject(request) if not workingProject: # select a project. errMsg = ['The Project has not been selected'] redirectURL = registrationURL_base + 'selectProjectDefault/' DebugOut('No project, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) if not workingQuestionnaire: errMsg = ['The questionnaire has not been selected'] redirectURL = registrationURL_base + 'selectQuestionnaireDefault/' DebugOut('No questionnaire selected, so redirect to: %s' %redirectURL) return HttpResponseRedirect(redirectURL) errMsgs = [] # messages to the user! Caution. # Retrieve the Questionnaire Tag workingQuestionnaireTag=workingQuestionnaire.shortTag # Retrieve the Project tag workingProjectTag=workingProject.shortTag # find all existing page shortTag's for this questionnaire allPageTags = getAllPageTags(workingQuestionnaire) DebugOut('allPageTags (only pages with questions): %s' %allPageTags) # find all existing pages with questions for this questionnaire allPageWQs = findAllPagesWQuestions(workingQuestionnaire) # allPageTagsQs: list of tags for pages with questions attached. allPageTagsQs = [aPage.shortTag for aPage in allPageWQs] # for Session data - tracking current page currentPageSessionTag = 'currentPageTag_admin' # select a default page tag to start. This is the 'from' page. [workingPageTag, theWorkingPage] = selectCurrentPage(request, currentPageSessionTag, allPageWQs) DebugOut('workingPageTag: %s' %workingPageTag) # got all starting data DebugOut('Default values:') DebugOut('workingQuestionnaireTag: %s' %workingQuestionnaireTag) DebugOut('workingPageTag: %s' %workingPageTag) # Define session values tags for later use pageBaseURL = url_base + workingProjectTag+'/'+workingQuestionnaireTag+'/' testCondition = '' # test condition then proceed to the indicated next page nextPAndConditionMsg = '' # message that the test condition was saved to the database # Do not automatically display the questions theQForm = '' pgNextCalc = '' recordType = 'calculated' # this function creates, edits and deletes # records of this type in QuestionnairePage if request.method == 'POST': DebugOut('setPageToPageTransitionCalculated: After POST') DebugOut('request.POST %s' %str(request.POST)) if 'returnToHome' in request.POST: DebugOut('returnToHome button hit') redirectURL = registrationURL_base + 'userLanding/' return HttpResponseRedirect(redirectURL) # previous screen url elif 'currentPage' in request.POST: # Selected a new current working page workingPageTag = request.POST['currentPage'] [theWorkingPage, success]=getPageObj(workingQuestionnaire, workingPageTag) if not success: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Page does not exist: %s' %workingPageTag]}) request.session[currentPageSessionTag] = theWorkingPage.id DebugOut('The new working page: %s' %workingPageTag) elif 'nextPageButton' in request.POST: # select the NEXT page for calculation newNextPageTag = request.POST['nextPageButton'] [newNextPageObj, success]=getPageObj(workingQuestionnaire, newNextPageTag) request.session['setPageTransPageNextCalc'] = newNextPageObj.id DebugOut('The new calculated next page: %s' %newNextPageObj.shortTag) elif 'Save responses to questions' in request.POST: DebugOut('In Save responses to questions') # display questions, accept responses, save to db # retrieve the questions on the page thePageQuestions=getPageQuestions(theWorkingPage) if len(thePageQuestions) == 0: emsg = 'No questions can be found for the page "%s"' % workingPageTag errMsgs.append(emsg) DebugOut(emsg) else: DebugOut('Display questions and gather responses.') # display questions, prepare for data entry theQForm = UserDynamicFormCreation( thePageQuestions, request.POST, useQuestionTag=True) if 'setPageTransPageNextCalc' in request.session: newNextPageid = request.session['setPageTransPageNextCalc'] try: newNextPageObj = Page.objects.get(id=newNextPageid) except: newNextPageObj = None errMsgs.append('next page not retrieved. Select the desired "next page" for the transition first.') else: DebugOut('next page not defined.') errMsgs.append('next page not defined. Select the desired "next page" for the transition first.') newNextPageObj = None if theQForm.is_valid() and newNextPageObj: DebugOut('Question response data is valid') # tag for 'next page' questionResponsesWithTags = theQForm.cleaned_data testCondition = questionResponsesWithTags # uses tags from database when available. Unique tag per page saveTestConditonToQuestionnairePage(testCondition, newNextPageObj, theWorkingPage, workingQuestionnaire, recordType) nextPAndConditionMsg = 'The test conditon "%s" for transition to the next page "%s" was saved' %(testCondition, newNextPageObj.shortTag) theQForm = UserDynamicFormCreation( thePageQuestions, questionResponsesWithTags, useQuestionTag=True) DebugOut('testCondition: %s' %testCondition) DebugOut('workingQuestionnaireTag: %s' %workingQuestionnaireTag) DebugOut('workingPageTag: %s' %workingPageTag) elif 'deleteSelection' in request.POST: # delete the selected record # delete the selected line from the condition table lineSelect = int(request.POST['deleteSelection']) # line selected testConditionTransitionList = getTestConditionFromQuestionnairePage(workingQuestionnaire, theWorkingPage) # record structure is: # record number, test condition, next page short tag, next page object DebugOut('lineSelect: %s' %lineSelect) DebugOut('Length of list %s' %len(testConditionTransitionList)) DebugOut('Length of record in list %s' %len(testConditionTransitionList[0])) DebugOut('The line: %s' %testConditionTransitionList[lineSelect]) recSelect = int(testConditionTransitionList[lineSelect][0]) deleteTestConditonFromQuestionnairePage(recSelect) else: # a 'GET' # obtain any prior setting for 'next page' DebugOut('"GET" posted - restore data if any') # retrieve the questions on the page, theWorkingPage may have changed thePageQuestions=getPageQuestions(theWorkingPage) pageQuestionsExist = len(thePageQuestions) != 0 pluralQuestions = len(thePageQuestions) > 1 if theQForm == '' and len(thePageQuestions) != 0: theQForm = UserDynamicFormCreation( thePageQuestions, [''], useQuestionTag=True) # find existing test conditions for this page testConditionTransitionList = getTestConditionFromQuestionnairePage(workingQuestionnaire, theWorkingPage) # record structure is: # record number, test condition, next page short tag DebugOut('testConditionTransitionList: %s' %testConditionTransitionList) # retrieve "nextPage" if set if 'setPageTransPageNextCalc' in request.session: newNextPageid = request.session['setPageTransPageNextCalc'] try: newNextPageObj = Page.objects.get(id=newNextPageid) newNextPageTag = newNextPageObj.shortTag except: newNextPageTag = '' else: newNextPageTag = '' defaultNextPageObj = getNextPageFromDB(workingQuestionnaire, theWorkingPage) if defaultNextPageObj: defaultNextPageTag = defaultNextPageObj.shortTag else: defaultNextPageTag = '' readyToSubmit = newNextPageTag and workingPageTag and testCondition # get all page transition based upon calculation (testCondition) [calculatedTransitionList, success] = getTestConditionTransitions(workingQuestionnaire) if not success: calculatedTransitionList = '' # flag indicating "do not display" currentContext = { 'theQForm' : theQForm, 'workingProject' : workingProject, 'workingQuestionnaire' : workingQuestionnaire, 'workingPageTag' : workingPageTag, 'newNextPageTag' : newNextPageTag, 'defaultNextPageTag' : defaultNextPageTag, 'readyToSubmit' : readyToSubmit, 'pgNextCalc' : pgNextCalc, 'allPageTagsQs' : allPageTagsQs, # only pages with questions 'allPageTags' : allPageTags, # with or without questions 'nextPAndConditionMsg' : nextPAndConditionMsg, 'pageQuestionsExist' : pageQuestionsExist, 'pluralQuestions' : pluralQuestions, 'testConditionTransitionList' : testConditionTransitionList, 'calculatedTransitionList' : calculatedTransitionList, 'errMsgs' : errMsgs, } currentContext.update(csrf(request)) DebugOut('setPageToPageTransitionCalculated: exiting') return render(request, 'working_pages/setPageToPageTransitionCalculated.html', currentContext) def selectCurrentPage(request, currentPageSessionTag, allPageObjs): # select a default page tag to start. This is the 'from' page. if currentPageSessionTag in request.session: # first look in sessions data workingPageID = request.session[currentPageSessionTag] try: workingPageObj = allPageObjs.get(id=workingPageID) except: workingPageObj = allPageObjs.latest('lastUpdate') # use last updated object request.session[currentPageSessionTag] = workingPageObj.id workingPageTag = workingPageObj.shortTag else: # if not in sessions data, then use last page workingPageObj = allPageObjs.latest('lastUpdate') # use last updated object workingPageTag = workingPageObj.shortTag request.session[currentPageSessionTag] = workingPageObj.id DebugOut('Current page session tag %s: has the value: %s' %(currentPageSessionTag, workingPageTag)) return [workingPageTag, workingPageObj] def getQuestionnairePageInfo(pageObj, questionnaireObj): # retrieves the testCondition and calculated condition # required to transition to page nextPage. # Needed: QuestionnairePage # separate the different types of records # there are three different "next pages": next_page_default, calculated, globalFlag directed # only one default try: nextPageDefault = QuestionnairePage.objects.get( pageID = pageObj, questionnaireID = questionnaireObj, recordType = 'next_page_default' ).nextPage # should be only one!! except QuestionnairePage.DoesNotExist: nextPageDefault = '' # no default # perhaps more than one global flag try: testGlobalFlagObj = QuestionnairePage.objects.filter( pageID = pageObj ).filter( questionnaireID = questionnaireObj ).filter( recordType = 'globalFlag' ) testGlobalFlagDict = {} for item in testGlobalFlagObj: testGlobalFlagDict.update({item.testCondition : item.nextPage}) except QuestionnairePage.DoesNotExist: # bleed1 *** what's behavior when no flag? Not an exception! testGlobalFlagDict = {} # may be more than one condition directing to the "next page" try: testConditionvsNextPageObj = QuestionnairePage.objects.filter( pageID = pageObj ).filter( questionnaireID = questionnaireObj ).filter( recordType = 'calculated' ) testConditionvsNextPageDict = {} for item in testConditionvsNextPageObj: testConditionvsNextPageDict.update({item.testCondition : item.nextPage}) except QuestionnairePage.DoesNotExist: testConditionvsNextPageDict = {} return [nextPageDefault, testGlobalFlagDict, testConditionvsNextPageDict ] def createPageList(allPages): pageListCols = [ 'Select', 'Page tag', 'Page type', 'Description', 'Explanation', 'Prologue', 'Epilogue', ] ii = 1 pageList = [] for aPage in allPages: aRow = [ 'R_'+str(ii), aPage.shortTag, aPage.pageType, aPage.description, aPage.explanation, aPage.prologue, aPage.epilogue, ] pageList.append(aRow) ii = ii + 1 return [pageList, pageListCols] def editSummaryAndAnalysisPage(request): DebugOut('editSummaryAndAnalysisPage: Entering') #*** select a default project tag and questionnaire tag to start. May have been reset by user [theProject, theQuestionnaire] = getSessionQuestionnaireProject(request) if not theQuestionnaire: errMsg = ['The questionnaire has not been selected'] return render(request, 'system_error.html', { 'syserrmsg': errMsg}) if errMsg: DebugOut('taking system error exit') DebugOut(str(errMsg)) return render(request, 'system_error.html', { 'syserrmsg': errMsg}) errMsg = [] try: allQuestionnaires = Questionnaire.objects.all().order_by('shortTag') except: DebugOut('List Questionnaires: query to database failed.') errMsg.append('List Questionnaires: query to database failed.') if errMsg != []: DebugOut(str(errMsg)) return render(request, 'system_error.html', { 'syserrmsg': errMsg}) questTags = [aQuest.shortTag for aQuest in allQuestionnaires] # list comprehension workingQuestionnaireTag = theQuestionnaire.shortTag # find all existing Summary pages try: allSummaryPages=Page.objects.filter(pageType = 'questionnaireSummary').order_by('shortTag') except: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Page data is missing.']}) allPageTags = [aPage.shortTag for aPage in allSummaryPages] theForm = editSummaryAndAnalysisForm() currentContext = { 'theForm' : theForm, 'questTags' : questTags, 'workingQuestionnaireTag' : workingQuestionnaireTag, 'allPageTags' : allPageTags, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, 'errMsg' : errMsg, } DebugOut('editSummaryAndAnalysisPage: Exit') return render(request, workingPageTemplateRoot + 'editSummaryAndAnalysisPage.html', currentContext) def displayAndEditPage(request): # edit a page pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' # find all existing page shortTag's try: allP=Page.objects.all() except: return render(request, 'system_error.html', {'syserrmsg': ['Debug: Page data is missing.']}) allTags = [aPage.shortTag for aPage in allP] # select a default page tag to start. if 'currentPageTag' in request.session: # first look in sessions data currentPageTag = request.session['currentPageTag'] else: # if not in sessions data, then use last tag currentPageTag = allTags[-1] request.session['currentPageTag'] = currentPageTag # try to retrieve the page try: thePage=Page.objects.filter(shortTag=currentPageTag).latest('lastUpdate') except Page.DoesNotExist: # so set to a legal value return render(request, 'system_error.html', {'syserrmsg': ['Debug: Most recent page data is missing.']}) if request.method == 'POST': theForm = PageForm( request.POST) if request.POST['submitButton'] == 'Discard Page Edits': # Return to previous page return HttpResponseRedirect(pageBaseURL+'intro/') # previous screen url if theForm.is_valid(): if request.POST['submitButton'] in allTags: # click on page button - change pages currentPageTag = request.POST['submitButton'] try: thePage=Page.objects.get(shortTag=currentPageTag) except Page.DoesNotExist: # so set to a legal value return render(request, 'system_error.html', {'syserrmsg': ['Debug: Most recent page data is missing.']}) initialValues ={'shortTag' : currentPageTag, 'description' : thePage.description, 'explanation' : thePage.explanation, 'prologue' : thePage.prologue, 'epilogue' : thePage.epilogue, 'lastUpdate' : thePage.lastUpdate, } theForm = PageForm(initial=initialValues) elif request.POST['submitButton'] == 'Save Page Edits': if theForm.cleaned_data['shortTag'] != currentPageTag: currentPageTag = theForm.cleaned_data['shortTag'] try: thePage=Page.objects.get(shortTag=currentPageTag) except Page.DoesNotExist: # so create the page thePage=Page(shortTag=currentPageTag) thePage.shortTag = currentPageTag thePage.description = theForm.cleaned_data['description'] thePage.explanation = theForm.cleaned_data['explanation'] thePage.prologue = theForm.cleaned_data['prologue'] thePage.epilogue = theForm.cleaned_data['epilogue'] thePage.lastUpdate = timezone.now() thePage.save() responseMsg = 'Page "%s" edited and saved.' %currentPageTag request.session['currentPageTag'] = currentPageTag return HttpResponseRedirect(pageBaseURL+'intro/') # previous screen url elif request.POST['submitButton'] == 'Delete Current Page': # Return to previous page Page.objects.filter(shortTag=currentPageTag).delete() return HttpResponseRedirect(pageBaseURL+'intro/') # previous screen url else: initialValues ={'shortTag' : currentPageTag, 'description' : thePage.description, 'explanation' : thePage.explanation, 'prologue' : thePage.prologue, 'epilogue' : thePage.epilogue, 'lastUpdate' : thePage.lastUpdate, } theForm = PageForm(initial=initialValues) currentContext = { 'theForm' : theForm, 'shortTag' : currentPageTag, 'allTags' : allTags, 'lastUpdate' : thePage.lastUpdate, 'back_to_intro' : 'Return to the Introduction Page', 'url_base' : url_base, } return render(request, 'working_pages/displayAndEditPage.html', currentContext) def QuestContinue(request, whichProject, whichQuest, whichPage): DebugOut( 'In QuestContinue. whichProject: %s whichQuest: %s whichPage: %s' %(whichProject, whichQuest, whichPage)) errMess = [] # Standard verification w.r.t. project and questionnaire [theProject, theQuestionnaire, errMess] = verifyQuestionnaireProject(request, whichProject, whichQuest) if errMess != []: return render(request, 'system_error.html', {'syserrmsg': errMess}) urlprefix = settings.WSGI_URL_PREFIX # backward compatibility! for Explanations pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' + whichProject+'/'+whichQuest+'/' request.session['pageBaseURL'] = pageBaseURL if whichPage == 'completion': return HttpResponseRedirect( pageBaseURL+'completion') # Standard page object retrieval [thePageObj, success] = getPageObj(theQuestionnaire, whichPage) if not success: errMsg=['Could not find a page transition for %s'%whichPage] return render(request, 'system_error.html', {'syserrmsg': errMess}) thisPageTag = whichPage # Indicate if this is a start page for special logic. startPage = False firstPage = getStartPageObj(theQuestionnaire) if firstPage == thePageObj: startPage = True # *** rework the following errors # if not request.session.test_cookie_worked(): # check for cookie function and therefore session existence # DebugOut('QuestContinue: Please enable cookies in your browser.') # return render(request, 'system_error.html', {'syserrmsg': ['Please enable cookies in your browser.']}) if 'constantPageDataDict' in request.session: constantPageDataDict = request.session['constantPageDataDict'] else: return render(request, 'system_error.html', {'syserrmsg': ['Debug: header and footer page data is missing.']}) # pull questions from the database theQuestionsOnThePage = getPageQuestions( thePageObj) if len(theQuestionsOnThePage) == 0: errMsg = '#1No questions can be found for the page! None in the database. %s' % thisPageTag # continue - display the Page fields # got everything - GO # Determine if there is an image imageFileName = thePageObj.imageFileName # false if no image # Determine the page type pageType = thePageObj.pageType DebugOut('pageType: %s' %pageType) if pageType == 'hasTemplateAndFunction': # This type of page has a template and function - both of the same name # and the last part of the url. pass # *** later? prologue = SubstituteWords( thePageObj.prologue ) # replace keywords with current values epilogue = SubstituteWords( thePageObj.epilogue ) # special logic for 'sendQuestions' page type useQuestionsFromSessionTag = 'useQuestionsFromSessionTag_' + thisPageTag useAlternateQuestions = useQuestionsFromSessionTag in request.session and pageType != 'sendQuestions' if useQuestionsFromSessionTag in request.session: previousPageQuestionResults = request.session[useQuestionsFromSessionTag] DebugOut("previousPageQuestionResults") DebugOut(str(previousPageQuestionResults)) haveQuestions = True else: haveQuestions = False if useAlternateQuestions and haveQuestions and thisPageTag == 'H7a': DebugOut('YES sendQuestions entry questions:') # get previous questions from Session data # flatten the dictionary tagListFromPrev = convertFormsDataToDict(previousPageQuestionResults) DebugOut('Tags from previous questions: %s' %tagListFromPrev) # set up for page 'H7a' # build question follow up table qFollow = [ ['Birth control pills' , 'pHxHormUseBCAgeStart'], ['Birth control pills' , 'pHxHormUseBCAgeEnd'], ['Estrogen replacement', 'pHxHormUseEstrogenAgeStart'], ['Estrogen replacement', 'pHxHormUseEstrogenAgeEnd'], ['Progesterone replacement', 'pHxHormUseProgesteroneAgeStart'], ['Progesterone replacement' , 'pHxHormUseProgesteroneAgeEnd'], ['Tamoxifen', 'pHxHormUseTamoxifenAgeStart'], ['Tamoxifen' , 'pHxHormUseTamoxifenAgeEnd'], ['Raloxifene', 'pHxHormUseRaloxifeneAgeStart'], ['Raloxifene' , 'pHxHormUseRaloxifeneAgeEnd'], ['Arimidex', 'pHxHormUseArimidexAgeStart'], ['Arimidex' , 'pHxHormUseArimidexAgeEnd'], ] followQTags = [] # make a list of followOn question tags for prevTag in tagListFromPrev.keys(): for followOn in qFollow: if prevTag in followOn: followQTags.append(followOn[1]) if followQTags != []: DebugOut('Selected tags for followOn questions: %s' %followQTags) # retrieve these questions from the database # construct the query using the "Q object" (see page 104) in pdf from Django site # and: https://docs.djangoproject.com/en/1.5/topics/db/queries/#complex-lookups-with-q qtSum = Q(questionID__questionTag=followQTags[0]) for aQuestTag in followQTags: qtSum = qtSum | Q(questionID__questionTag=aQuestTag) # Sum the queries as "or"'s qtAll = qtSum & Q(pageID=thePageObj) # make sure the question belong to this Page! replacePQ = PageQuestion.objects.order_by('questionSequence').filter( qtAll) replacePageQuestions = [aPQ.questionID for aPQ in replacePQ] # Kludge: append the record number to get a unique page tag. for aQuestion in replacePageQuestions: theQID = str(aQuestion.id) # will not be used as an integer (not used) theQTag = aQuestion.questionTag + '_' + theQID # Kludge: append Question record to tag. aQuestion.questionTag = theQTag # Don't save this object!! else: theQuestionsOnThePage = "" if not theQuestionsOnThePage: # no questions available, continue to next page # *** change to go to next page when 'sendQuestions' page type next_pageObj = pageCalc(request,theQuestionnaire, thePageObj ) if next_pageObj: next_page = next_pageObj.shortTag else: next_page = '' errMsg = '#2No questions can be found for this page (%s), so go to the next page (%s)!' % (thisPageTag,next_page) DebugOut( errMsg) if next_page != '': return HttpResponseRedirect(pageBaseURL+next_page) # next screen url else: # assume at the end of the questionnaire DebugOut( 'NEXT button clicked. Completion? this_page: %s, next_page: %s' %(thisPageTag,next_page)) return HttpResponseRedirect( pageBaseURL+'completion/') theQuestionsOnThePage = replacePageQuestions # replace with the selected questions # *** delete this Session data after use! Just before exiting to a new page # del request.session[useQuestionsFromSessionTag] DebugOut('YES sendQuestions generated (pruned):') DebugOut(theQuestionsOnThePage) else: DebugOut('NO sendQuestions') # else use questions from database if theQuestionsOnThePage: DebugOut('QuestContinue: Questions are: \n%s' %theQuestionsOnThePage) else: DebugOut('#3No questions can be found for this page (%s).' % (thisPageTag)) # Define session values tags for later use pageSessionTag = 'HavePageResults_' + thisPageTag # concoct a name unique to this page for forms results straight from form errmsg = '' # to display on the page if request.method == 'POST': DebugOut( 'after POST') [theForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( theQuestionsOnThePage, request.POST, useQuestionTag=True) if useAlternateQuestions: # questions already responded to in Form. Delete communication for "sendQuestions" page del request.session[useQuestionsFromSessionTag] # delete questions data if theForm.is_valid(): # have valid data from page DebugOut( 'Form is valid. Saving data.') # Save the cleaned data questionResponsesWithTags = theForm.cleaned_data DebugOut('The cleaned data with question tags is:') DebugOut(str(questionResponsesWithTags)) # save this page data for redisplay of the page at Questionnaire Summary request.session[pageSessionTag] = questionResponsesWithTags savePageData(request, questionResponsesWithTags, thePageObj, theQuestionsOnThePage, qustionTagToRecordNum,choiceTagToRecordNum) # save for recap at the end of session if request.POST['submitButton'] == 'Next': UpdateLast_URL_Next(request, thisPageTag) # ignore 'back to' output saveGlobalFlagsToSessionData(request, theQuestionnaire, thePageObj, questionResponsesWithTags) next_pageObj = pageCalc(request,theQuestionnaire, thePageObj, questionResults=questionResponsesWithTags ) if next_pageObj: next_page = next_pageObj.shortTag pageTypeNextPage = next_pageObj.pageType else: next_page = '' pageTypeNextPage = '' if next_page != '': if pageType == 'sendQuestions': # save data for next page useQuestionsFromSessionTag = 'useQuestionsFromSessionTag_' + next_page nextPageQuestions = followOnQuestions(thisPageTag, questionResponsesWithTags) request.session[useQuestionsFromSessionTag] = questionResponsesWithTags if pageTypeNextPage == 'questionnaireSummary': # append to the url next_pagePageType = next_page + '/' + pageTypeNextPage DebugOut('PageType appended to next_page url: %s' %next_pagePageType) return HttpResponseRedirect(pageBaseURL+next_pagePageType) # next screen url DebugOut( 'NEXT button clicked. thisPageTag: %s, next_page: %s' %(thisPageTag,next_page)) return HttpResponseRedirect(pageBaseURL+next_page) # next screen url else: # assume at the end of the questionnaire DebugOut( 'NEXT button clicked. Completion? thisPageTag: %s, next_page: %s' %(thisPageTag,next_page)) return HttpResponseRedirect( pageBaseURL+'completion') else: # assume button pressed is 'Back' back_to = UpdateLast_URL_Back(request, thisPageTag) DebugOut( 'not NEXT button clicked. thisPageTag: %s, back_to: %s' %(thisPageTag,back_to)) return HttpResponseRedirect(pageBaseURL+back_to) # previous screen url elif request.POST['submitButton'] == 'Back': # save no data since it is not valid DebugOut( 'BACK button clicked') back_to = UpdateLast_URL_Back(request, thisPageTag) DebugOut('next page %s' %back_to) return HttpResponseRedirect(pageBaseURL+back_to) # previous screen url else: # not a POST DebugOut('Not a POST') # Recover session values for this page, if any if pageSessionTag in request.session: # fill fields with previously entered data from this session - if any DebugOut('Page data is in session tag, so fill the form with previous data. Page: %s' %thisPageTag) # this data has been 'cleaned' [theForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( theQuestionsOnThePage, request.session[pageSessionTag], useQuestionTag=True) # so retrieve the data DebugOut('session data dump start:') DebugOut('Session: %s' %request.session[pageSessionTag]) DebugOut('session data dump end') DebugOut('bound?: %s' %theForm.is_bound) else: # no valid data from prior visit to this page DebugOut('No page data in session tag: %s' %thisPageTag) [theForm, qustionTagToRecordNum,choiceTagToRecordNum] = UserDynamicFormCreation( theQuestionsOnThePage, [''], useQuestionTag=True) computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] fontSizeTextBox = dynamicPageDetails['fontSizeTextBox'] debugOn = settings.DEBUG contextDict = { 'explanation' : SubstituteWords( thePageObj.explanation ), 'theForm' : theForm, 'prologue' : prologue, 'epilogue' : epilogue, 'errmsg' : errmsg, 'computerT' : computerT, 'field_border' : '1', # border width - zero is ok. 'field_style' : 'as_p', 'fontSize' : fontSize, 'fontSizeTextBox' : fontSizeTextBox, 'haveImage' : imageFileName, 'thisPageTag' : thisPageTag, 'thisPageRecNum' : thePageObj.id, 'debugOn' : debugOn, #'haveImage' : imageCalc(thisPageTag), } currentContext = constantPageDataDict.copy() currentContext.update(contextDict) if startPage: # no back button on the start page currentContext.update({'back_not_enabled' : True}) UpdateLast_URL_Next(request, thisPageTag) DebugOut( 'rendering page %s' %thisPageTag) currentContext.update(csrf(request)) DebugOut( 'QuestContinue: exit') return render(request, 'generic_page.html', currentContext) def savePageData(request, cleanedData, thePageObj, thePageQuestions, qustionTagToRecordNum,choiceTagToRecordNum ): # Use this function to save question responses to Session Data DebugOut('savePageData: enter') # cleanedData is a dictionary # always use this function to update allResultsDict and allResultsList #DebugOut('Cleaned data as input is:') #DebugOut(str(cleanedData)) #DebugOut('Input questions are: ') #DebugOut(str(thePageQuestions)) # Questions are associated with a sequential number. This number is incremented throughout the session if 'questionSequenceNumber' in request.session: seqNumber = request.session['questionSequenceNumber'] else: # initialize seqNumber = 0 request.session['questionSequenceNumber'] = seqNumber # create a version of the cleaned data with a tag unique with respect to the entire questionnaire cleanedDataUniqueTag = {} for uniqueQuestionLabel, questionResponseValue in cleanedData.iteritems(): if uniqueQuestionLabel in qustionTagToRecordNum: questionRecNum = qustionTagToRecordNum[uniqueQuestionLabel] aQuest = Question.objects.get(id=questionRecNum) else: DebugOut('syserrmsg: A question label without a corresponding record.') return if uniqueQuestionLabel in choiceTagToRecordNum: responseChoiceRecNum = choiceTagToRecordNum[uniqueQuestionLabel] else: responseChoiceRecNum = None # no problem # find values for output questionRecNumStr = str(questionRecNum) responseChoiceRecNumStr = str(responseChoiceRecNum) uniqueTag = encodeQuestionResponseLabel(questionRecNum,responseChoiceRecNum) # with encoded record numbers seqNumber+=1 if type(questionResponseValue) == list: multipleResponses = [] for aResponse in questionResponseValue: if '_' in aResponse: [questionRecNumLoop,responseChoiceRecNumLoop] = decodeQuestionResponseLabel(aResponse) try: loopResponse = ResponseChoice.objects.get(id=int(responseChoiceRecNumLoop)).choiceText DebugOut('Should be a unique id with encoding "%s"'%aResponse) except: DebugOut('savePageData: failed inside loop: aResponse: "%s"'%aResponse) loopResponse = 'Fail' else: loopResponse = aResponse # make a guess: actual choiceText multipleResponses.append(loopResponse) questionResponseValue = multipleResponses # Prepare a record in Session Data aLine = [ questionResponseValue, # 0 aQuest.questionText, # 1 questionRecNumStr, # 2 responseChoiceRecNumStr,# 3 thePageObj.shortTag, # 4 thePageObj.id, # 5 uniqueTag, # 6 # with encoded record numbers aQuest.questionTag, # 7 seqNumber, # 8 ] #DebugOut('savePageData: uniqueTag: "%s"'%uniqueTag) #DebugOut('aLine %s' %aLine) cleanedDataUniqueTag.update({uniqueTag:aLine}) request.session['questionSequenceNumber'] = seqNumber if allResultsDict in request.session: # add to the previous responses # *** warning, duplicate uniqueQuestionLabels are trashed request.session[allResultsDict].update(cleanedDataUniqueTag) #DebugOut('Session dict data updated in savePageData') else: request.session[allResultsDict] = cleanedDataUniqueTag #DebugOut('Session dictionary data initialized in savePageData') # DebugOut('Dump the data dictionary after updating') # for Debug # for keyname,keyvalue in request.session[allResultsDict].iteritems(): # DebugOut('keyname %s,keyvalue %s' %(keyname,keyvalue)) # DebugOut('Dump the data dictionary end') # also save page data as a list with unique tags. Duplicates have been removed. allSessionResultsList = [] for uniqueQuestionLabel, lineInfo in request.session[allResultsDict].iteritems(): allSessionResultsList.append(lineInfo) allSessionResultsListSorted = sorted( allSessionResultsList, key=itemgetter(8)) allSessionResultsListOut = [] for aLine in allSessionResultsListSorted: allSessionResultsListOut.append(aLine[:8]) # strip the sequence number # DebugOut('Sorted question response: %s'%aLine[:8]) request.session[allResultsList] = allSessionResultsListOut # destroy previous list - this list is complete with no dups DebugOut('Session list data updated in savePageData') DebugOut('savePageData: exiting') return True def followOnQuestions(this_page, cleaned_data): # Query database for follow-on questions for this page return cleaned_data def convertDictDataToList(theDictData): #convert dict data to list DebugOut('entering convertDictDataToList') listOut = [] for itemValue in theDictData: if type(itemValue) == list: # go another level for itemList2ndLevel in itemValue: listOut.append([itemList2ndLevel , True]) else: listOut.append([item.html_name , itemValue]) listOut.sort() # make sure changing the order of the questions has no effect on the list order DebugOut(str(listOut)) DebugOut('Exiting convertDictDataToList') return listOut def convertFormsDataToDict(theCleanedData): """flatten the incoming dictionary, which prepares items for saving to Session data """ DebugOut('entering convertFormsDataToDict') dictOut = {} for itemKey in theCleanedData.keys(): itemValue = theCleanedData[itemKey] if type(itemValue) == list: # go to another level for itemKey2 in itemValue: dictOut.update({itemKey2 : True}) # Assume Boolean!! else: dictOut.update({itemKey : itemValue}) DebugOut(str(dictOut)) DebugOut('Exiting convertFormsDataToDict') return dictOut def encodeQuestionResponseLabel(questionRecNum,responseChoiceRecNum): """ Encodes Question and QuestionResponse record numbers into a special label. """ if responseChoiceRecNum: rcRec = str(responseChoiceRecNum) else: rcRec = '' uniqueQuestionLabel = 'Question_'+str(questionRecNum)+'_'+rcRec return uniqueQuestionLabel def decodeQuestionResponseLabel(uniqueQuestionLabel): """ Decodes special label set by encodeQuestionResponseLabel """ msgOut = [] if '_' not in uniqueQuestionLabel: # wrong format DebugOut('decodeQuestionResponseLabel: wrong format: "%s"'%uniqueQuestionLabel) return ['',''] labelParts = uniqueQuestionLabel.split('_') try: part1 = labelParts[1] try: questionRecNum = int(part1) except ValueError: questionRecNum = 'ValueXError' except IndexError: questionRecNum = 'xxx' msgOut.append('decodeQuestionResponseLabel: Index of part 1 out of range') try: part2 = labelParts[2] if part2: try: responseChoiceRecNum = int(part2) except ValueError: responseChoiceRecNum = 'ValueYError' else: responseChoiceRecNum = '' except IndexError: responseChoiceRecNum = '' msgOut.append('decodeQuestionResponseLabel: Index of part 2 out of range') for aMess in msgOut: DebugOut(aMess) return [questionRecNum,responseChoiceRecNum] def MakeUniqueKeyToTagDict(thePageQuestions): """Create dictionary for converting from Unique key to Question.shortTag Some functions: saveGlobalFlagsToSessionData, require the original Question.shortTag to be associated with the question response. """ UtoTdict = {} for aQuestion in thePageQuestions: theQRecNum = str(aQuestion.id) theQLabel = encodeQuestionResponseLabel(theQRecNum,'') theQTag = aQuestion.questionTag UtoTdict.update({theQLabel:theQTag}) choiceCount = ResponseChoice.objects.filter(questionID=aQuestion).count() if choiceCount > 0: # multiple choice question. theResponses = ResponseChoice.objects.filter(questionID=aQuestion) for aResponse in theResponses: theChoiceRecNum = str(aResponse.id) choiceText = aResponse.choiceText choiceType = aResponse.choiceType choiceTag = aResponse.choiceTag theQResponseLabel = encodeQuestionResponseLabel(theQRecNum,theChoiceRecNum) UtoTdict.update({theQResponseLabel:choiceText}) return UtoTdict def replaceUniqueKeysWithDBQuestionTags(questionResponses, thePageQuestions): """Replaces the Unique key with local keys. The result, limited to the page, is unique and not null Note: keep this logic the same is as in UserDynamicFormCreation Args: questionResponses: dictionary of question responses: key word, key value thePageQuestions: query set or list of pages Returns: questionResponsesWithTags: unique key names in dictionary questionResponses, with new key names from the question record """ DebugOut('replaceUniqueKeysWithDBQuestionTags: enter') UtoTdict = MakeUniqueKeyToTagDict(thePageQuestions) questionResponsesWithTags = {} ii = 1 tagKeyList = [] # accumulate the encountered tags for uniquekey, keyValue in questionResponses.iteritems(): # Change the unique key. DebugOut('uniquekey: "%s",keyValue: "%s"'%(uniquekey, keyValue)) DebugOut('Data type of keyValue "%s"'%type(keyValue)) tagKey = UtoTdict[uniquekey] if tagKey == '': tagKey = 'QuestionTag_' + str(ii) if tagKey in tagKeyList: # if already in the list tagKey = tagKey + "_" + str(ii) # force the tag to be unique tagKeyList.append(tagKey) questionResponsesWithTags.update({tagKey:keyValue}) ii+=1 DebugOut('replaceUniqueKeysWithDBQuestionTags: exit') return questionResponsesWithTags def UserDynamicFormCreation( thePageQuestions, formData, useQuestionTag=False): """Create a form for a set of Questions in a query set. Args: allQuestions: a query set containing questions returns: aForm: a form with the questions and response choices (if any) """ DebugOut('UserDynamicFormCreation: enter') DebugOut('formData: %s'%formData) if formData == ['']: formData = None # "None" is acceptable input. DebugOut('UserDynamicFormCreation: no forms data input (ok)') else: DebugOut('UserDynamicFormCreation: has forms data input') multCount=0 # count 'MultipleChoiceField' to flag an error if there is more than one # at the moment, can handle only one "multiple choice' field. # This might make the best sense from the user interface point of view as well. questionList = [] # each element of the List is a dictionary ii = 0 labelList = [] # accumulate a list of tags to make sure they are unique on the page qustionTagToRecordNum = {} # tag to record number translation for Question choiceTagToRecordNum = {} # tag to record number translation for ResponseChoice for aQuestion in thePageQuestions: ii+=1 theQRecNum = str(aQuestion.id) # used as a label, so string is needed if useQuestionTag: # use short tag if it is non-null if aQuestion.questionTag: theQLabel = aQuestion.questionTag if theQLabel in labelList: theQLabel = theQLabel+'_'+ str(ii) else: # tag is null. Invent a tag. Use the same logic as in replaceUniqueKeysWithDBQuestionTags theQLabel = 'QuestionTag_' + str(ii) else: theQLabel = encodeQuestionResponseLabel(theQRecNum,'') # creates a unique label labelList.append(theQLabel) qustionTagToRecordNum.update({theQLabel:aQuestion.id}) # save to object with substitutions updatedQuestionText = SubstituteWords(aQuestion.questionText) questionList.append({ 'questionTag':aQuestion.questionTag, 'responseType':aQuestion.responseType, 'questionText':updatedQuestionText, 'theQLabel':theQLabel, }) # Note: do not "save" aQuestion!! DebugOut('aQuestion record number: "%s"' %aQuestion.id) DebugOut('aQuestion.questionTag1: "%s"' %aQuestion.questionTag) DebugOut('aQuestion.responseType2: "%s"' %aQuestion.responseType) DebugOut('aQuestion.questionText3: "%s"' %smart_str(aQuestion.questionText)) DebugOut('updatedQuestionText4: "%s"' %smart_str(updatedQuestionText)) DebugOut('theQLabel5: "%s"' %theQLabel) # are there multiple responses?? responseCount = ResponseChoice.objects.filter( questionID=aQuestion).count() if responseCount >0: # query for the multiple choices for a specific question tag theResponseChoices=ResponseChoice.objects.order_by('choiceSequence').filter( questionID=aQuestion) DebugOut('Choices follow:') multCount=multCount+1 # allowed only one multiple choice question per page, so count them choiceList = [] for aChoice in theResponseChoices: ii+=1 theChoiceTextTemp = aChoice.choiceText theChoiceText = SubstituteWords(theChoiceTextTemp) theChoiceRecNum = str(aChoice.id) # used as a label, so string is needed # if useQuestionTag: # use short tag if it is non-null # if aChoice.choiceTag: # theChoiceLabel = aChoice.choiceTag # if theChoiceLabel in labelList: # theChoiceLabel = theChoiceLabel+'_'+ str(ii) # else: # tag is null. Invent a tag. Use the same logic as in replaceUniqueKeysWithDBQuestionTags # theChoiceLabel = 'ChoiceTag_' + str(ii) # else: # theChoiceLabel = encodeQuestionResponseLabel(theQRecNum,theChoiceRecNum) # creates a unique label theChoiceLabel = theChoiceText # bigChange! labelList.append(theChoiceLabel) choiceTagToRecordNum.update({theChoiceLabel:aChoice.id}) DebugOut('Choice tag: '+aChoice.choiceTag+' Choice Text: '+theChoiceText) DebugOut('Choice label: '+theChoiceLabel) choiceList.append( [theChoiceLabel , theChoiceText]) DebugOut('End Choices') if multCount == 1: DebugOut('Choices end. Count: %s' %str(len(choiceList))) DebugOut('choiceList: %s' %choiceList) aForm = UserFormPoly(formData, questions=questionList, choices=choiceList) elif multCount > 1: DebugOut('Error: too many multichoice: %s. All questions will get the same choices (the last one).' %str(multCount)) # aForm = '' # will crash at return elif multCount == 0: DebugOut('UserDynamicFormCreation: No choiceList for this question (ok)') aForm = UserFormPoly(formData, questions=questionList) DebugOut('UserDynamicFormCreation: exit') return [aForm, qustionTagToRecordNum,choiceTagToRecordNum] def SubstituteWords( inputText ): # DebugOut('SubstituteWords: enter') # DebugOut('inputText %s' %inputText) explainURLprefix = settings.WSGI_URL_PREFIX + 'multiquest/explanations/' # backward compatibility! for Explanations *** outputText = inputText.replace('{{explainURLprefix}}', explainURLprefix) # returns input string if no replacement # DebugOut('outputText %s' %outputText) # DebugOut('SubstituteWords: exit') return outputText def scrnrexpln(request, whichpage): #all explanations # click to an explanation screen, then back to the calling page DebugOut('scrnrexpln: enter') computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] fontSizeTextBox = dynamicPageDetails['fontSizeTextBox'] if 'pageBaseURL' in request.session: DebugOut('in request session') pageBaseURL = request.session['pageBaseURL'] back_to_temp = UpdateLast_URL_Back(request, whichpage) if back_to_temp: DebugOut('back_to_temp %s' %back_to_temp) back_to = pageBaseURL + back_to_temp DebugOut('back_to %s' %back_to) else: # no sensible "back to" page. Go back to questionnaire selection. back_to = questionnaireSelectionPage DebugOut('questionnaireSelectionPage %s' %questionnaireSelectionPage) else: back_to = questionnaireSelectionPage DebugOut('no request session, questionnaireSelectionPage %s' %questionnaireSelectionPage) if request.method == 'POST': if request.POST['submitButton'] == 'Back': DebugOut( 'BACK button clicked') DebugOut( 'Return destination is: %s' %back_to) return HttpResponseRedirect(back_to) DebugOut( 'In scrnrexpln. whichpage: %s, back_to: %s' %(whichpage,back_to)) contextDict = { 'back_to' : back_to, 'fontSize' : fontSize, 'fontSizeTextBox' : fontSizeTextBox, 'imageloc' : settings.MEDIA_URL, } if whichpage == 'ashkenazijewishrelatives': return render(request, 'Explanations/ashkenazijewishrelatives.html', contextDict) if whichpage == 'brcatesting': return render(request, 'Explanations/brcatesting.html', contextDict) if whichpage == 'closebloodrelatives': return render(request, 'Explanations/closebloodrelatives.html', contextDict) if whichpage == 'moreonbreastca': return render(request, 'Explanations/moreonbreastca.html', contextDict) if whichpage == 'ovca': return render(request, 'Explanations/ovca.html', contextDict ) if whichpage == 'skininbreastca': return render(request, 'Explanations/skininbreastca.html', contextDict) # if none of the above, return to the general explanations page. DebugOut('scrnrexpln: exit') return render(request, 'Explanations/explanations.html', contextDict) def UpdateLast_URL_Next(request, this_page): """Records current page tag. Purpose: enable the "Back" button by recording sequence of visited page tags. Args: request this_page: page shortTag Returns: None. Side effects: modifies request.session['last_url'] Raises: None. """ # DebugOut('UpdateLast_URL_Next: enter') # DebugOut('this_page: %s'%this_page) if 'last_url' in request.session: # DebugOut('Length: %s'%len(request.session['last_url'])) if len(request.session['last_url']) > 0: # detect immediate duplicates if request.session['last_url'][-1] == this_page: request.session['last_url'].pop() # assume the previous page is different from this page request.session['last_url'].append(this_page) # records this url visited. else: request.session['last_url'] = [this_page] request.session.modified = True # save the session changes # DebugOut('UpdateLast_URL_Next: exit') return True def UpdateLast_URL_Back(request, this_page): # records this_page and returns previous page in stack #DebugOut('UpdateLast_URL_Back: enter') #DebugOut('this_page: %s'%this_page) if 'last_url' in request.session: #DebugOut('last_url in session') #DebugOut('print the url list. Length: %s'%len(request.session['last_url'])) for aurl in request.session['last_url']: print 'url: %s' %aurl if len(request.session['last_url']) > 0: # detect immediate duplicates #DebugOut('immediate duplicate') if request.session['last_url'][-1] == this_page: #DebugOut('pop the last page: %s'%this_page) request.session['last_url'].pop() # assume the previous page is different from this page if len(request.session['last_url']) == 0: back_to = '' #DebugOut('back into the void') request.session['last_url'].append(this_page) # records this url visited. else: # List has 1 or more entries back_to = request.session['last_url'][-1] #DebugOut('normal back to: %s'%back_to) else: back_to = '' #DebugOut('back into the void 2') request.session['last_url'] = [this_page] request.session.modified = True # save the session changes #DebugOut('UpdateLast_URL_Back: exit') return back_to def dumpSessionData(request): DebugOut('dumpSessionData: enter') if request.method == 'POST': if 'flushSessionData' in request.POST: request.session.flush() # =========== flush Session data ======================== sessionDataDump = [] for kn, kv in request.session.items(): lineOut = kn+': '+unicode(kv) sessionDataDump.append(lineOut) if sessionDataDump == []: sessionDataDump = False # no session data contextDict = { 'sessionDataDump' : sessionDataDump, 'url_base' : url_base, 'back_to_intro' : 'Return to the Introduction Page', } DebugOut('dumpSessionData: exit') return render(request, 'working_pages/sessionDataView.html',contextDict ) def questionnaireToGo(request, theProject, theQuestionnaire): """Prepare the Session Data for questionnaire execution. Provide the url. Note: see function "removeResponsesFromSessionData" Note: see function "questionnaireEnvironmentPrep" Args: "request" input Returns: pageBaseURL - fully qualified url for prefix to page short tag Session Data: Sets session data: 'pageBaseURL' Raises: None. """ errMsg = [] pageBaseURL = questionnaireEnvironmentPrep( request, theProject, theQuestionnaire) # find the first page of the questionnaire and add to the URL # retrieve the "first page" from Questionnaire. firstPageObj = getStartPageObj(theQuestionnaire) if firstPageObj: firstPageInQuestTag = firstPageObj.shortTag urltogo = pageBaseURL + firstPageInQuestTag else: urltogo = pageBaseURL errMsg.append('Questionnaire "%s" has no defined start page.'%theQuestionnaire.shortTag) return urltogo # next screen url def questionnaireEnvironmentPrep( request, theProject, theQuestionnaire): """Prepare the Session Data for questionnaire execution. Note: see function "removeResponsesFromSessionData" Note: see function "questionnaireToGo" Args: "request" input Returns: pageBaseURL - fully qualified url for prefix to page short tag Session Data: Sets session data: 'pageBaseURL' Raises: None. """ DebugOut('questionnaireEnvironmentPrep: enter') # The following is where pages are identified by record from the url. setSessionQuestionnaireProject(request, theProject, theQuestionnaire) setSessionPageTagToRecord(request, theQuestionnaire) whichQuest = theQuestionnaire.shortTag spObj = getProjectObjForQuestionnaire(theQuestionnaire) if spObj: whichProject = spObj.shortTag else: whichProject = '' # will be an error condition pageBaseURL = settings.WSGI_URL_PREFIX + 'multiquest/' + whichProject+'/'+whichQuest+'/' # save this page as the default page to return to in case of error request.session['pageBaseURL'] = pageBaseURL # Store unchanging page data into Session data constantPageDataDict = { 'barTitle' : theQuestionnaire.barTitle, 'pageTitle' : theQuestionnaire.pageTitle, 'pageSubTitle' : theQuestionnaire.pageSubTitle, 'footerText' : theQuestionnaire.footerText, 'version' : theQuestionnaire.version, 'versionDate' : str(theQuestionnaire.versionDate), 'imageloc' : settings.MEDIA_URL, 'pageBaseURL' : pageBaseURL, 'urlprefix' : settings.WSGI_URL_PREFIX, # backward compatibility! for Explanations 'debugMode' : settings.DEBUG } # refers to DEBUG in settings. # save constant portion of context request.session['constantPageDataDict'] = constantPageDataDict DebugOut('questionnaireEnvironmentPrep: exit') return pageBaseURL def splash(request, whichProject, whichQuest): #Select questionnaire, Check for cookie function. Start session. DebugOut('splash: enter') now = timezone.now() DebugOut('whichProject %s, whichQuest %s' %(whichProject,whichQuest)) # Standard verification w.r.t. project and questionnaire [theProject, theQuestionnaire, errMess] = verifyQuestionnaireProject(request, whichProject, whichQuest) if errMess != []: DebugOut('test %s' %str(errMess)) # last ditch effort. theProject = getProjectObj( whichProject) # query the database theQuestionnaire = getQuestionnaireObjFromTags(whichProject, whichQuest) if not theProject or not theQuestionnaire: return render(request, 'system_error.html', {'syserrmsg': errMess}) else: pass # set up environment pageBaseURL = questionnaireEnvironmentPrep( request, theProject, theQuestionnaire) # continue without error this_page = "splash" # have sufficient information to display the page. # Standard page object retrieval [thePageObj, success] = getPageObj(theQuestionnaire, this_page) if not success: errMsg=['Could not find a page transition for %s'%this_page] return render(request, 'system_error.html', {'syserrmsg': errMess}) prologue = SubstituteWords( thePageObj.prologue ) epilogue = SubstituteWords( thePageObj.epilogue ) explanation = SubstituteWords( thePageObj.explanation ) request.session.set_test_cookie() # Set test cookie to test in next POST pageBaseURL = request.session['pageBaseURL'] constantPageDataDict = request.session['constantPageDataDict'] computerT = computertype(request) # identify computer type dynamicPageDetails = pagePerComputer(computerT) fontSize = dynamicPageDetails['fontSize'] fontSizeTextBox = dynamicPageDetails['fontSizeTextBox'] now = timezone.now() # create context for current page contextDict = {'current_date' : now, 'explanation' : explanation, 'prologue' : prologue, 'epilogue' : epilogue, 'field_style' : '', # no field display at all 'fontSize' : fontSize, 'fontSizeTextBox' : fontSizeTextBox, 'back_not_enabled' : True } if request.method == 'POST': # if not request.session.test_cookie_worked(): # check for cookie function # currentContext = constantPageDataDict.copy() # currentContext.update(contextDict) # currentContext.update({'errmsg': 'Please enable cookies in your browser.'}) # return render(request, 'generic_page.html', currentContext) # add logic for 'Back' button - remove it?? **** UpdateLast_URL_Next(request, this_page) # ignore 'back to' output next_pageObj = pageCalc(request,theQuestionnaire, thePageObj) next_page = next_pageObj.shortTag theNextURL = pageBaseURL +next_page DebugOut('splash: theNextURL %s' %theNextURL) DebugOut('splash: exit to page %s' %next_page) return HttpResponseRedirect(theNextURL) currentContext = constantPageDataDict.copy() currentContext.update(contextDict) DebugOut('splash: exit') return render(request, 'generic_page.html',currentContext )
hr4e/QuestionnaireQx
multiquest/views.py
Python
apache-2.0
250,803
[ "VisIt" ]
d06ad0bd8a5a65eefc427ec959ef8a9d197a0b43769cba2f5426c0cb53057d82
from rdkit import Chem from rdkit.Chem import AllChem import copy import sys from sygma.treenode import TreeNode import logging logger = logging.getLogger('sygma') class Tree(object): """ Class to build and analyse a metabolic tree :param parentmol: An RDKit molecule """ def __init__(self, parentmol=None): self.nodes = {} if parentmol: parentnode = TreeNode(parentmol, parent=None, rule=None, score=1, pathway="") self.nodes[parentnode.ikey] = parentnode self.parentkey = parentnode.ikey def _react(self, reactant, reaction): """Apply reaction to reactant and return products""" ps = reaction.RunReactants([reactant]) products = [] for product in ps: frags = (Chem.GetMolFrags(product[0], asMols=True, sanitizeFrags=False)) for p in frags: q = copy.copy(p) try: Chem.SanitizeMol(q) products.append(q) except: pass # Ignore fragments that cannot be sanitized return products def metabolize_node(self, node, rules): for rule in rules: products = self._react(node.mol, rule.reaction) for x in products: ikey = AllChem.InchiToInchiKey(AllChem.MolToInchi(x))[:14] x.SetProp("_Name", ikey) node.children.append(ikey) if ikey in self.nodes: if node.ikey not in self.nodes[ikey].parents or \ self.nodes[ikey].parents[node.ikey].probability < rule.probability: self.nodes[ikey].parents[node.ikey] = rule else: self.nodes[ikey] = TreeNode(x, parent=node.ikey, rule=rule) def metabolize_all_nodes(self, rules, cycles=1): """ Metabolize all nodes according to [rules], for [cycles] number of cycles :param rules: List of rules :param cycles: Integer indicating the number of subsequent steps to apply the rules """ for i in range(cycles): logger.info('Cycle ' + str(i + 1)) ikeys = list(self.nodes.keys()) for ikey in ikeys: self.metabolize_node(self.nodes[ikey], rules) def add_coordinates(self): """ Add missing atomic coordinates to all metabolites """ for node in self.nodes.values(): node.gen_coords() def calc_scores(self): """ Calculate probability scores for all metabolites """ for key in self.nodes: self.calc_score(self.nodes[key]) def calc_score(self, node): if node.score != None: return else: node.score = -1 # Indicating the score is "waiting" for a result for pkey in node.parents: if self.nodes[pkey].score is None: # No calculation is requested for parents with score -1, self.calc_score(self.nodes[pkey]) # to avoid closed loops .... newscore = self.nodes[pkey].score * float(node.parents[pkey].probability) if node.score < newscore: # This implies that parents with a newscore of -1 are ignored, node.score = newscore # to avoid closed loops ... node.pathway = self.nodes[pkey].pathway + node.parents[pkey].rulename + "; \n" def to_list(self, filter_small_fragments = True, parent_column = 'parent'): """ Generate a list of metabolites :param filter_small_fragments: Boolean to activate filtering all metabolites with less then 15% of original atoms (of the parent) :param parent_column: String containing the name for the column with the parent molecule :return: A list of dictionaries for each metabolites, containing the SyGMa_metabolite (an RDKit Molecule), SyGMa_pathway and SyGMa_score, sorted by decreasing probability. """ def sortkey(rowdict): return rowdict['SyGMa_score'] output_list = [] n_parent_atoms = self.nodes[self.parentkey].mol.GetNumAtoms() for key in self.nodes: if filter_small_fragments and float(self.nodes[key].n_original_atoms) <= 0.15 * n_parent_atoms: continue pathway = "parent;" if key == self.parentkey else self.nodes[key].pathway output_list.append({parent_column: self.nodes[self.parentkey].mol, "SyGMa_pathway": pathway, "SyGMa_metabolite": self.nodes[key].mol, "SyGMa_score": self.nodes[key].score}) output_list.sort(key=sortkey, reverse=True) return output_list def to_smiles(self, filter_small_fragments = True): """ Generate a smiles list of metabolites :param filter_small_fragments: Boolean to activate filtering all metabolites with less then 15% of original atoms (of the parent) :return: A list of metabolites as list ``[[SyGMa_metabolite as smiles, SyGMa_score]]`` sorted by decreasing probability score. """ output_list = self.to_list(filter_small_fragments=filter_small_fragments) smiles_list = [] for entry in output_list: smiles_list.append([Chem.MolToSmiles(entry['SyGMa_metabolite']),entry['SyGMa_score']]) return smiles_list def write_sdf(self, file=sys.stdout, filter_small_fragments = True): """ Generate an SDFile with metabolites including the SyGMa_pathway and the SyGMa score as properties :param file: The SDF file to write to :param filter_small_fragments: Boolean to activate filtering all metabolites with less then 15% of original atoms (of the parent) """ output_list = self.to_list(filter_small_fragments=filter_small_fragments) sdf = Chem.SDWriter(file) for entry in output_list: mol = entry['SyGMa_metabolite'] mol.SetProp("Pathway", entry['SyGMa_pathway'][:-1]) mol.SetProp("Score", str(entry['SyGMa_score'])) sdf.write(mol)
3D-e-Chem/sygma
sygma/tree.py
Python
gpl-3.0
6,343
[ "RDKit" ]
3cd0d66121375dd15a98cd01b0ce7116ca9958c0e39ea69358f7d6edc791a762
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 from __future__ import print_function from MDAnalysis.core.groups import Atom, AtomGroup, Residue, ResidueGroup from abc import ABCMeta, abstractmethod import numpy as np class Observable(object): """ Instantiate an observable. This is a metaclass: it can be used to define observables that will behave "properly" with other classes/function in this module (e.g. by being called from an RDF object). A simple example is: >>> import pytim >>> import MDAnalysis as mda >>> from pytim import observables >>> from pytim.datafiles import WATER_GRO >>> >>> class TotalNumberOfParticles(observables.Observable): ... def compute(self): ... return len(self.u.atoms) >>> >>> u = mda.Universe(WATER_GRO) >>> o = TotalNumberOfParticles(u) >>> print (o.compute()) 12000 """ __metaclass__ = ABCMeta def __init__(self, universe, options=''): self.u = universe self.options = options # TODO: add proper whole-molecule reconstruction def fold_atom_around_first_atom_in_residue(self, atom): """ remove pbcs and puts an atom back close to the first one in the same residue. Does not check connectivity (works only for molecules smaller than box/2 """ # let's take the first atom in the residue as the origin box = self.u.trajectory.ts.dimensions[0:3] pos = atom.position - atom.residue.atoms[0].position pos[pos >= box / 2.] -= box[pos >= box / 2.] pos[pos < -box / 2.] += box[pos < -box / 2.] return pos def fold_around_first_atom_in_residue(self, inp): """ same as fold_atom_around_first_atom_in_residue() but for groups of atoms. """ pos = [] if isinstance(inp, Atom): pos.append(self.fold_atom_around_first_atom_in_residue(inp)) elif isinstance(inp, (AtomGroup, Residue, ResidueGroup)): for atom in inp.atoms: pos.append(self.fold_atom_around_first_atom_in_residue(atom)) else: raise Exception( "input not valid for fold_around_first_atom_in_residue()") return np.array(pos) def select_direction(self, arg): _dirs = {'x': 0, 'y': 1, 'z': 2} def _inarg(string, inp): return np.any([string in e for e in inp]) directions = np.array([True, True, True]) if len(arg) > 0: if not _inarg('x', arg) or not _inarg('y', arg) or not _inarg( 'z', arg): RuntimeError( "this observable accepts as argument a string like" + " 'xy', 'z', ... or a list like ['x','z'], to select components") directions = np.array([False, False, False]) for key in _dirs.keys(): if _inarg(key, arg): directions[_dirs[key]] = True # TODO this is not a mask...should we change the name? self.dirmask = np.where(directions)[0] @staticmethod def _to_atomgroup(inp): if isinstance(inp, Atom): ind = inp.index inp = inp.universe.atoms[ind:ind + 1] return inp @abstractmethod def compute(self, inp=None, kargs=None): kargs = kargs or {} pass @staticmethod def _(): """ This is a collection of basic tests to check that the observables are yelding the expected result. >>> # OBSERVABLES TEST: 1 >>> import MDAnalysis as mda >>> import pytim >>> pytim.observables.Observable._() ; # coverage >>> from pytim import observables >>> from pytim.datafiles import * >>> import numpy as np >>> u = mda.Universe(_TEST_ORIENTATION_GRO) >>> o = observables.Orientation(u,options='molecular') >>> np.set_printoptions(precision=3,threshold=10) >>> print(o.compute(u.atoms).flatten()) [ 1. 0. 0. 0. 1. 0. 0. -0.707 -0.707] >>> np.set_printoptions() >>> # OBSERVABLES TEST: 2 >>> u=mda.Universe(_TEST_PROFILE_GRO) >>> o=observables.Number() >>> p=observables.Profile(direction='x',observable=o) >>> p.sample(u.atoms) >>> low,up,avg = p.get_values(binwidth=1.0) >>> print(low[0:3]) [0. 1. 2.] >>> print(avg[0:3]) [0.01 0.02 0.03] >>> # CORRELATOR TEST >>> from pytim.utilities import correlate >>> a = np.array([1.,0.,1.,0.,1.]) >>> b = np.array([0.,2.,0.,1.,0.]) >>> corr = correlate(b,a) >>> corr[np.abs(corr)<1e-12] = 0.0 >>> ['{:.2f}'.format(i) for i in corr] ['0.00', '0.75', '0.00', '0.75', '0.00'] >>> corr = correlate(b) >>> corr[np.abs(corr)<1e-12] = 0.0 >>> ['{:.2f}'.format(i) for i in corr] ['1.00', '0.00', '0.67', '0.00', '0.00'] >>> # PROFILE EXTENDED TEST: checks trajectory averaging >>> # and consistency in summing up layers contributions >>> import numpy as np >>> import MDAnalysis as mda >>> import pytim >>> from pytim.datafiles import * >>> from pytim.observables import Profile >>> u = mda.Universe(WATER_GRO,WATER_XTC) >>> g=u.select_atoms('name OW') >>> inter = pytim.ITIM(u,group=g,max_layers=4,centered=True, molecular=False) >>> >>> Layers=[] >>> >>> for n in np.arange(0,5): ... Layers.append(Profile()) >>> Val=[] >>> for ts in u.trajectory[:4]: ... for n in range(len(Layers)): ... if n == 0: ... group = g ... else: ... group = u.atoms[u.atoms.layers == n] ... Layers[n].sample(group) >>> for L in Layers: ... Val.append(L.get_values(binwidth=2.0)[2]) >>> >>> print (np.round(np.sum(np.array(Val[0]) * np.prod(u.dimensions[:3])) / len(Val[0]),decimals=0)) 4000.0 >>> # the sum of the layers' contribution is expected to add up only close >>> # to the surface >>> print (not np.sum(np.abs(np.sum(Val[1:],axis=0)[47:] - Val[0][47:])>1e-15)) True """ pass
Marcello-Sega/pytim
pytim/observables/observable.py
Python
gpl-3.0
6,549
[ "MDAnalysis" ]
94cc669f5294cf6185b1d503485fb075c04fb6e8b0b42b4b11314110c899d211
# (c) 2014, Brian Coca, Josh Drake, et al # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. import exceptions class BaseCacheModule(object): def get(self, key): raise exceptions.NotImplementedError def set(self, key, value): raise exceptions.NotImplementedError def keys(self): raise exceptions.NotImplementedError def contains(self, key): raise exceptions.NotImplementedError def delete(self, key): raise exceptions.NotImplementedError def flush(self): raise exceptions.NotImplementedError def copy(self): raise exceptions.NotImplementedError
M0ses/ansible
v2/ansible/plugins/cache/base.py
Python
gpl-3.0
1,241
[ "Brian" ]
2b69061fa7869f374fcd930cff691b7b537b207dfb06a9b8329a1b5bf9c39ba8
from __future__ import division, print_function, unicode_literals # This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "f 10 0.033, s, f 20 0.033, s, f 30 0.033, s, f 30 0.033, s, q" tags = "particles, Fire" import pyglet import cocos from cocos.director import director from cocos.actions import * from cocos.layer import * from cocos.particle_systems import * class L(Layer): def __init__(self): super( L, self).__init__() # p = Fireworks() # p = Explosion() p = Fire() # p = Flower() # p = Sun() # p = Spiral() # p = Meteor() # p = Galaxy() p.position = (320,100) self.add( p ) def main(): director.init( resizable=True ) main_scene = cocos.scene.Scene() main_scene.add( L() ) director.run( main_scene ) if __name__ == '__main__': main()
dangillet/cocos
test/test_particle_fire.py
Python
bsd-3-clause
976
[ "Galaxy" ]
fca8957c2a3a6c8fdb435f751b70444b842c7680f2e1395d25e15b9efd1ddeed
# -*- coding: utf-8 -*- # # Calls tracer after every successful transaction. # Also supplies the 'tracer' command. # # Copyright (C) 2015 Jakub Kadlčík # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties 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, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import import time import dnf.cli import dnfpluginsextras import subprocess _ = dnfpluginsextras._ class Tracer(dnf.Plugin): """DNF plugin for `tracer` command""" name = "tracer" def __init__(self, base, cli): super(Tracer, self).__init__(base, cli) self.timestamp = time.time() self.base = base self.cli = cli if self.cli is not None: self.cli.register_command(TracerCommand) def transaction(self): """ Call after successful transaction See https://rpm-software-management.github.io/dnf/api_transaction.html """ # Don't run tracer when uninstalling it if dnfpluginsextras.is_erasing(self.base.transaction, "tracer"): return # Don't run tracer when preparing chroot for mock if self.base.conf.installroot != "/": return # Don't run tracer when "nothing to do" if not len(self.base.transaction): return installed = set([package.name for package in self.base.transaction.install_set]) erased = set([package.name for package in self.base.transaction.remove_set]) args = ["tracer", "-n"] + list(installed | erased) process = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() _print_output(out, err) if len(out) != 0: print("\n" + _("For more information run:")) print(" sudo tracer -iat " + str(self.timestamp)) class TracerCommand(dnf.cli.Command): """DNF tracer plugin""" aliases = ["tracer"] def run(self, args): """Called after running `dnf tracer ...`""" args = ["tracer"] + args process = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() _print_output(out, err) def _print_output(out, err): if len(err) != 0: print("Tracer:") print(" " + _("Program 'tracer' crashed with following error:") + "\n") print(err) print(_("Please visit ") + "https://github.com/FrostyX/tracer/issues " + "and submit the issue. Thank you") print(_("We apologize for any inconvenience")) return if len(out) == 0: print(_("You should restart:")) print(" " + _("Nothing needs to be restarted")) return # Last value is blank line for line in out.decode("utf8").split("\n")[:-1]: print(line)
esmil/dnf-plugins-extras
plugins/tracer.py
Python
gpl-2.0
3,753
[ "VisIt" ]
f7cc37c484d1ed173e8323a09f0e5f57a88ca8ceb15f6950f3be246cffb48ca3
from PyGMO.problem._problem_space import cassini_1, gtoc_1, gtoc_2, cassini_2, rosetta, messenger_full, tandem, laplace, sagas, mga_1dsm_alpha, mga_1dsm_tof, mga_incipit, mga_incipit_cstrs, mga_part, _gtoc_2_objective # Redefining the constructors of all problems to obtain good documentation # and allowing kwargs def _cassini_1_ctor(self, objectives=1): """ Constructs a Cassini 1 Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm] Its single objective version has a global minimum at 4.9307 [km/s], and it is a deceptive problem with a larger minimum at 5.303 [km/s] USAGE: problem.cassini_1(objectives = 1) * objectives: number of objectives. 1=DV, 2=DV,DT """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(objectives) self._orig_init(*arg_list) cassini_1._orig_init = cassini_1.__init__ cassini_1.__init__ = _cassini_1_ctor def _gtoc_1_ctor(self): """ Constructs a GTOC 1 Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm] Best known global minima is at -1,581,950 USAGE: problem.gtoc_1() """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] self._orig_init(*arg_list) gtoc_1._orig_init = gtoc_1.__init__ gtoc_1.__init__ = _gtoc_1_ctor def _cassini_2_ctor(self): """ Constructs a Cassini 2 Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA-1DSM) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm] It models the same interplanetary trajectory as the cassini_1 problem, but in a more accurate fashion, allowing deep space manouvres Best known global minimum is at 8.383 [km/s] USAGE: problem.cassini_2() """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] self._orig_init(*arg_list) cassini_2._orig_init = cassini_2.__init__ cassini_2.__init__ = _cassini_2_ctor def _rosetta_ctor(self): """ Constructs a Rosetta Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA-1DSM) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm] Best known global minimum is at 1.343 [km/s] USAGE: problem.rosetta() """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] self._orig_init(*arg_list) rosetta._orig_init = rosetta.__init__ rosetta.__init__ = _rosetta_ctor def _messenger_full_ctor(self): """ Constructs a Mesenger Full Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA-1DSM) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm] Best known global minimum is at 2.113 USAGE: problem.messenger_full() """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] self._orig_init(*arg_list) messenger_full._orig_init = messenger_full.__init__ messenger_full.__init__ = _messenger_full_ctor def _tandem_ctor(self, prob_id=7, max_tof=-1): """ Constructs a TandEM Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA-1DSM) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm]. The objective function is -log(m_final). USAGE: problem.tandem(prob_id = 7, max_tof = -1) * prob_id: Selects the problem variant (one of 1..25). All problems differ from the fly-by sequence * max_tof = Activates a constriants on the maximum time of flight allowed (in years) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(prob_id) arg_list.append(max_tof) self._orig_init(*arg_list) tandem._orig_init = tandem.__init__ tandem.__init__ = _tandem_ctor def _laplace_ctor(self, seq=[3, 2, 3, 3, 5]): """ Constructs a EJSM-Laplace Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA-1DSM) is similar to TandEM, but targets Jupiter and the user can specify explicitly the planetary fly-by sequence USAGE: problem.laplace(seq = [3,2,3,3,5]) * seq: The planetary sequence. This is a list of ints that represent the planets to visit 1 - Mercury, 2 - Venus, 3 - Earth, 4 - Mars, 5 - Jupiter, 6 - Saturn. It must start from 3 (Earth) and end with 5 (Jupiter) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) self._orig_init(*arg_list) laplace._orig_init = laplace.__init__ laplace.__init__ = _laplace_ctor def _sagas_ctor(self): """ Constructs a SAGAS Problem (Box-Constrained Continuous Single-Objective) NOTE: This problem (MGA-1DSM) belongs to the GTOP database [http://www.esa.int/gsp/ACT/inf/op/globopt.htm] USAGE: problem.sagas() """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] self._orig_init(*arg_list) sagas._orig_init = sagas.__init__ sagas.__init__ = _sagas_ctor gtoc_2.obj = _gtoc_2_objective def _gtoc_2_ctor(self, ast1=815, ast2=300, ast3=110, ast4=47, n_seg=10, objective=gtoc_2.obj.MASS_TIME): """ Constructs a GTOC 2 Problem (Constrained Continuous Single-Objective) NOTE: This problem is a quite faithful transcription of the problem used during the GTOC2 competition It Transcribe the whole OCP resulting from the low-thrust dynamics into an NLP. As such it is very difficult to find feasible solutions. Note that by default the asteroid sequence is the winning one from Turin University. USAGE: problem.gtoc_2(ast1 = 815, ast2 = 300, ast3 = 110, ast4 = 47, n_seg = 10, objective = gtoc_2.obj.MASS_TIME) * ast1 id of the first asteroid to visit (Group 1: 0 - 95) * ast2 id of the second asteroid to visit (Group 2: 96 - 271) * ast3 id of the third asteroid to visit (Group 3: 272 - 571) * ast4 id of the fourth asteroid to visit (Group 4: 572 - 909) * n_seg number of segments to be used per leg * obj objective function in the enum {MASS,TIME,MASS_TIME} """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(ast1) arg_list.append(ast2) arg_list.append(ast3) arg_list.append(ast4) arg_list.append(n_seg) arg_list.append(objective) self._orig_init(*arg_list) gtoc_2._orig_init = gtoc_2.__init__ gtoc_2.__init__ = _gtoc_2_ctor from PyKEP.core._core import epoch from PyKEP.planet import jpl_lp, gtoc6 def _mga_1dsm_alpha_ctor( self, seq=[jpl_lp('earth'), jpl_lp('venus'), jpl_lp('earth')], t0=[epoch(0), epoch(1000)], tof=[365.25, 5.0 * 365.25], vinf=[0.5, 2.5], multi_objective=False, add_vinf_dep=False, add_vinf_arr=True): """ Constructs an mga_1dsm problem (alpha-encoding) USAGE: problem.mga_1dsm(seq = [jpl_lp('earth'),jpl_lp('venus'),jpl_lp('earth')], t0 = [epoch(0),epoch(1000)], tof = [365.25,5.0 * 365.25], vinf = [0.5, 2.5], multi_objective = False, add_vinf_dep = False, add_vinf_arr = True) * seq: list of PyKEP planets defining the encounter sequence (including the starting planet) * t0: list of two epochs defining the launch window * tof: list of two floats defining the minimum and maximum allowed mission length (days) * vinf: list of two floats defining the minimum and maximum allowed initial hyperbolic velocity at launch (km/sec) * multi_objective: when True constructs a multiobjective problem (dv, T) * add_vinf_dep: when True the computed Dv includes the initial hyperbolic velocity (at launch) * add_vinf_arr: when True the computed Dv includes the final hyperbolic velocity (at arrival) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof[0]) arg_list.append(tof[1]) arg_list.append(vinf[0]) arg_list.append(vinf[1]) arg_list.append(multi_objective) arg_list.append(add_vinf_dep) arg_list.append(add_vinf_arr) self._orig_init(*arg_list) mga_1dsm_alpha._orig_init = mga_1dsm_alpha.__init__ mga_1dsm_alpha.__init__ = _mga_1dsm_alpha_ctor def _mga_1dsm_tof_ctor( self, seq=[ jpl_lp('earth'), jpl_lp('venus'), jpl_lp('earth')], t0=[ epoch(0), epoch(1000)], tof=[ [ 50, 900], [ 50, 900]], vinf=[ 0.5, 2.5], multi_objective=False, add_vinf_dep=False, add_vinf_arr=True): """ Constructs an mga_1dsm problem (tof-encoding) USAGE: problem.mga_1dsm(seq = [jpl_lp('earth'),jpl_lp('venus'),jpl_lp('earth')], t0 = [epoch(0),epoch(1000)], tof = [ [50, 900], [50, 900] ], vinf = [0.5, 2.5], multi_objective = False, add_vinf_dep = False, add_vinf_arr = True) * seq: list of PyKEP planets defining the encounter sequence (including the starting planet) * t0: list of two epochs defining the launch window * tof: list of intervals defining the times of flight (days) * vinf: list of two floats defining the minimum and maximum allowed initial hyperbolic velocity at launch (km/sec) * multi_objective: when True constructs a multiobjective problem (dv, T) * add_vinf_dep: when True the computed Dv includes the initial hyperbolic velocity (at launch) * add_vinf_arr: when True the computed Dv includes the final hyperbolic velocity (at arrival) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof) arg_list.append(vinf[0]) arg_list.append(vinf[1]) arg_list.append(multi_objective) arg_list.append(add_vinf_dep) arg_list.append(add_vinf_arr) self._orig_init(*arg_list) mga_1dsm_tof._orig_init = mga_1dsm_tof.__init__ mga_1dsm_tof.__init__ = _mga_1dsm_tof_ctor def _mga_incipit_ctor( self, seq=[ gtoc6('io'), gtoc6('io'), gtoc6('europa')], t0=[ epoch(7305.0), epoch(11323.0)], tof=[ [ 100, 200], [ 3, 200], [ 4, 100]]): """ USAGE: mga_incipit(seq = [gtoc6('io'),gtoc6('io'),gtoc6('europa')], t0 = [epoch(6905.0),epoch(11323.0)], tof = [[100,200],[3,200],[4,100]]) * seq: list of jupiter moons defining the trajectory incipit * t0: list of two epochs defining the launch window * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof) self._orig_init(*arg_list) mga_incipit._orig_init = mga_incipit.__init__ mga_incipit.__init__ = _mga_incipit_ctor def _mga_incipit_cstrs_ctor( self, seq=[ gtoc6('io'), gtoc6('io'), gtoc6('europa')], t0=[ epoch(7305.0), epoch(11323.0)], tof=[ [ 100, 200], [ 3, 200], [ 4, 100]], Tmax=300.00, Dmin=2.0): """ USAGE: mga_incipit_cstrs(seq = [gtoc6('io'),gtoc6('io'),gtoc6('europa')], t0 = [epoch(6905.0),epoch(11323.0)], tof = [[100,200],[3,200],[4,100]], Tmax = 365.25, Dmin = 0.2) * seq: list of jupiter moons defining the trajectory incipit * t0: list of two epochs defining the launch window * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(t0[0]) arg_list.append(t0[1]) arg_list.append(tof) arg_list.append(Tmax) arg_list.append(Dmin) self._orig_init(*arg_list) mga_incipit_cstrs._orig_init = mga_incipit_cstrs.__init__ mga_incipit_cstrs.__init__ = _mga_incipit_cstrs_ctor def _mga_part_ctor( self, seq=[ gtoc6('europa'), gtoc6('europa'), gtoc6('europa')], tof=[ [ 5, 50], [ 5, 50]], t0=epoch(11000), v_inf_in=[ 1500.0, 350.0, 145.0]): """ USAGE: mga_part(seq = [gtoc6('europa'),gtoc6('europa'),gtoc6('europa')], tof = [[5,50],[5,50]], t0 = epoch(11000), v_inf_in[1500.0,350.0,145.0]) * seq: list of jupiter moons defining the trajectory incipit * tof: list of n lists containing the lower and upper bounds for the legs flight times (days) * t0: starting epoch * v_inf_in: Incoming spacecraft relative velocity """ # We construct the arg list for the original constructor exposed by # boost_python arg_list = [] arg_list.append(seq) arg_list.append(tof) arg_list.append(t0) arg_list.append(v_inf_in) self._orig_init(*arg_list) mga_part._orig_init = mga_part.__init__ mga_part.__init__ = _mga_part_ctor # Plot of the trajectory for an mga_1dsm problem def _mga_1dsm_alpha_plot(self, x): """ Plots the trajectory represented by the decision vector x """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(0, 0, 0, color='y') seq = self.get_sequence() n = (len(seq) - 1) # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = list([0] * (n)) alpha_sum = 0 for i in range(n): T[i] = x[1] * x[6 + 4 * i] alpha_sum += x[6 + 4 * i] for i in range(n): T[i] /= alpha_sum # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (n + 1)) r_P = list([None] * (n + 1)) v_P = list([None] * (n + 1)) DV = list([None] * (n + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(x[0] + sum(T[0:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(ax, planet, t0=t_P[i], color=( 0.8, 0.6, 0.8), legend=True, units = AU) # 3 - We start with the first leg theta = 2 * pi * x[2] phi = acos(2 * x[3] - 1) - pi / 2 Vinfx = x[4] * cos(phi) * cos(theta) Vinfy = x[4] * cos(phi) * sin(theta) Vinfz = x[4] * sin(phi) v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])] r, v = propagate_lagrangian( r_P[0], v0, x[5] * T[0] * DAY2SEC, seq[0].mu_central_body) plot_kepler( ax, r_P[0], v0, x[5] * T[0] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU) # Lambert arc to reach seq[1] dt = (1 - x[5]) * T[0] * DAY2SEC l = lambert_problem(r, r_P[1], dt, seq[0].mu_central_body) plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] # First DSM occuring at time nu1*T1 DV[0] = norm([a - b for a, b in zip(v_beg_l, v)]) # 4 - And we proceed with each successive leg for i in range(1, n): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[8 + (i - 1) * 4] * seq[i].radius, x[7 + (i - 1) * 4], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian( r_P[i], v_out, x[9 + (i - 1) * 4] * T[i] * DAY2SEC, seq[0]. mu_central_body) plot_kepler(ax, r_P[i], v_out, x[9 + (i - 1) * 4] * T[i] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU) # Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1 - x[9 + (i - 1) * 4]) * T[i] * DAY2SEC l = lambert_problem(r, r_P[i + 1], dt, seq[0].mu_central_body) plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] # DSM occurring at time nu2*T2 DV[i] = norm([a - b for a, b in zip(v_beg_l, v)]) return ax mga_1dsm_alpha.plot = _mga_1dsm_alpha_plot # Plot of the trajectory for an mga_1dsm problem def _mga_1dsm_tof_plot_old(self, x): """ Plots the trajectory represented by the decision vector x """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(0, 0, 0, color='y') seq = self.get_sequence() n = (len(seq) - 1) # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = x[5::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (n + 1)) r_P = list([None] * (n + 1)) v_P = list([None] * (n + 1)) DV = list([None] * (n + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(x[0] + sum(T[0:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(ax, planet, t0=t_P[i], color=( 0.8, 0.6, 0.8), legend=True, units = AU) # 3 - We start with the first leg theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 Vinfx = x[3] * cos(phi) * cos(theta) Vinfy = x[3] * cos(phi) * sin(theta) Vinfz = x[3] * sin(phi) v0 = [a + b for a, b in zip(v_P[0], [Vinfx, Vinfy, Vinfz])] r, v = propagate_lagrangian( r_P[0], v0, x[4] * T[0] * DAY2SEC, seq[0].mu_central_body) plot_kepler( ax, r_P[0], v0, x[4] * T[0] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU) # Lambert arc to reach seq[1] dt = (1 - x[4]) * T[0] * DAY2SEC l = lambert_problem(r, r_P[1], dt, seq[0].mu_central_body) plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] # First DSM occuring at time nu1*T1 DV[0] = norm([a - b for a, b in zip(v_beg_l, v)]) # 4 - And we proceed with each successive leg for i in range(1, n): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[7 + (i - 1) * 4] * seq[i].radius, x[6 + (i - 1) * 4], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian( r_P[i], v_out, x[8 + (i - 1) * 4] * T[i] * DAY2SEC, seq[0]. mu_central_body) plot_kepler(ax, r_P[i], v_out, x[8 + (i - 1) * 4] * T[i] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU) # Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1 - x[8 + (i - 1) * 4]) * T[i] * DAY2SEC l = lambert_problem(r, r_P[i + 1], dt, seq[0].mu_central_body) plot_lambert(ax, l, sol=0, color='r', legend=False, units=AU) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] # DSM occurring at time nu2*T2 DV[i] = norm([a - b for a, b in zip(v_beg_l, v)]) return ax mga_1dsm_tof.plot_old = _mga_1dsm_tof_plot_old # Plot of the trajectory of an mga_incipit problem def _mga_incipit_plot_old(self, x, plot_leg_0=False): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d', aspect='equal') ax.scatter(0, 0, 0, color='y') JR = 71492000.0 legs = len(x) // 4 seq = self.get_sequence() common_mu = seq[0].mu_central_body # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = x[3::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * legs) r_P = list([None] * legs) v_P = list([None] * legs) DV = list([None] * legs) for i, planet in enumerate(seq): t_P[i] = epoch(x[0] + sum(T[:i + 1])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(ax, planet, t0=t_P[i], color=( 0.8, 0.6, 0.8), legend=True, units = JR) # 3 - We start with the first leg: a lambert arc theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 # phi close to zero is in the moon orbit plane injection r = [cos(phi) * sin(theta), cos(phi) * cos(theta), sin(phi)] r = [JR * 1000 * d for d in r] l = lambert_problem(r, r_P[0], T[0] * DAY2SEC, common_mu, False, False) if (plot_leg_0): plot_lambert(ax, l, sol=0, color='k', legend=False, units=JR, N=500) # Lambert arc to reach seq[1] v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] # 4 - And we proceed with each successive leg for i in range(1, legs): # Fly-by v_out = fb_prop(v_end_l, v_P[i - 1], x[1 + 4 * i] * seq[i - 1].radius, x[4 * i], seq[i - 1].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian( r_P[i - 1], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) plot_kepler(ax, r_P[i - 1], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu, N=500, color='b', legend=False, units=JR) # Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1 - x[4 * i + 2]) * T[i] * DAY2SEC l = lambert_problem(r, r_P[i], dt, common_mu, False, False) plot_lambert(ax, l, sol=0, color='r', legend=False, units=JR, N=500) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] plt.show() return ax mga_incipit.plot_old = _mga_incipit_plot_old # Plot of the trajectory of an mga_part problem def _mga_part_plot_old(self, x): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d', aspect='equal') ax.scatter(0, 0, 0, color='y') JR = 71492000.0 legs = len(x) // 4 seq = self.get_sequence() common_mu = seq[0].mu_central_body start_mjd2000 = self.t0.mjd2000 # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = x[3::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (legs + 1)) r_P = list([None] * (legs + 1)) v_P = list([None] * (legs + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(start_mjd2000 + sum(T[:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(ax, planet, t0=t_P[i], color=( 0.8, 0.6, 0.8), legend=True, units = JR) v_end_l = [a + b for a, b in zip(v_P[0], self.vinf_in)] # 4 - And we iterate on the legs for i in range(0, legs): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[1 + 4 * i] * seq[i - 1].radius, x[4 * i], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian( r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) plot_kepler(ax, r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu, N=500, color='b', legend=False, units=JR) # Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1 - x[4 * i + 2]) * T[i] * DAY2SEC l = lambert_problem(r, r_P[i + 1], dt, common_mu, False, False) plot_lambert(ax, l, sol=0, color='r', legend=False, units=JR, N=500) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] plt.show() return ax mga_part.plot_old = _mga_part_plot_old # Plot of concatenated fly-by legs def _part_plot(x, units, axis, seq, start_mjd2000, vinf_in): """ Plots the trajectory represented by a decision vector x = [beta,rp,eta,T] * N associated to a sequence seq, a start_mjd2000 and an incoming vinf_in """ from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm legs = len(x) // 4 common_mu = seq[0].mu_central_body # 1 - we 'decode' the chromosome recording the various times of flight # (days) in the list T T = x[3::4] # 2 - We compute the epochs and ephemerides of the planetary encounters t_P = list([None] * (legs + 1)) r_P = list([None] * (legs + 1)) v_P = list([None] * (legs + 1)) for i, planet in enumerate(seq): t_P[i] = epoch(start_mjd2000 + sum(T[:i])) r_P[i], v_P[i] = planet.eph(t_P[i]) plot_planet(planet, t0=t_P[i], color=( 0.8, 0.6, 0.8), legend=True, units = units, ax=axis) v_end_l = [a + b for a, b in zip(v_P[0], vinf_in)] # 4 - And we iterate on the legs for i in range(0, legs): # Fly-by v_out = fb_prop(v_end_l, v_P[i], x[1 + 4 * i] * seq[i].radius, x[4 * i], seq[i].mu_self) # s/c propagation before the DSM r, v = propagate_lagrangian( r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu) plot_kepler(r_P[i], v_out, x[4 * i + 2] * T[i] * DAY2SEC, common_mu, N=500, color='b', legend=False, units=units, ax=axis) # Lambert arc to reach Earth during (1-nu2)*T2 (second segment) dt = (1 - x[4 * i + 2]) * T[i] * DAY2SEC l = lambert_problem(r, r_P[i + 1], dt, common_mu, False, False) plot_lambert( l, sol=0, color='r', legend=False, units=units, N=500, ax=axis) v_end_l = l.get_v2()[0] v_beg_l = l.get_v1()[0] # Plot of the trajectory of an mga_part problem def _mga_part_plot(self, x): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() axis = fig.gca(projection='3d', aspect='equal') # Plots the central 'planet'star axis.scatter(0, 0, 0, color='y') JR = 71492000.0 seq = self.get_sequence() start_mjd2000 = self.t0.mjd2000 _part_plot(x, JR, ax, seq, start_mjd2000, self.vinf_in) return ax mga_part.plot = _mga_part_plot def _mga_incipit_plot(self, x, plot_leg_0=False): """ Plots the trajectory represented by the decision vector x Example:: prob.plot(x) """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d', aspect='equal') ax.scatter(0, 0, 0, color='y') JR = 71492000.0 seq = self.get_sequence() common_mu = seq[0].mu_central_body r_P, v_P = seq[0].eph(epoch(x[0] + x[3])) # 3 - We start with the first leg: a lambert arc theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 # phi close to zero is in the moon orbit plane injection r = [cos(phi) * sin(theta), cos(phi) * cos(theta), sin(phi)] r = [JR * 1000 * d for d in r] l = lambert_problem(r, r_P, x[3] * DAY2SEC, common_mu, False, False) if (plot_leg_0): plot_lambert(ax, l, sol=0, color='k', legend=False, units=JR, N=500) # Lambert arc to reach seq[1] v_end_l = l.get_v2()[0] vinf_in = [a - b for a, b in zip(v_end_l, v_P)] _part_plot(x[4:], JR, ax, seq, x[0] + x[3], vinf_in) return ax mga_incipit.plot = _mga_incipit_plot # Plot of the trajectory for an mga_1dsm problem def _mga_1dsm_tof_plot(self, x): """ Plots the trajectory represented by the decision vector x """ import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from PyKEP.orbit_plots import plot_planet, plot_lambert, plot_kepler from PyKEP import epoch, propagate_lagrangian, lambert_problem, fb_prop, AU, MU_SUN, DAY2SEC from math import pi, acos, cos, sin from scipy.linalg import norm mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() axis = fig.gca(projection='3d') axis.scatter(0, 0, 0, color='y') seq = self.get_sequence() # 2 - We plot the first leg r_P0, v_P0 = seq[0].eph(epoch(x[0])) plot_planet(seq[0], t0=epoch(x[0]), color=( 0.8, 0.6, 0.8), legend=True, units = AU, ax=axis) r_P1, v_P1 = seq[1].eph(epoch(x[0] + x[5])) theta = 2 * pi * x[1] phi = acos(2 * x[2] - 1) - pi / 2 Vinfx = x[3] * cos(phi) * cos(theta) Vinfy = x[3] * cos(phi) * sin(theta) Vinfz = x[3] * sin(phi) v0 = [a + b for a, b in zip(v_P0, [Vinfx, Vinfy, Vinfz])] r, v = propagate_lagrangian( r_P0, v0, x[4] * x[5] * DAY2SEC, seq[0].mu_central_body) plot_kepler( r_P0, v0, x[4] * x[5] * DAY2SEC, seq[0].mu_central_body, N=100, color='b', legend=False, units=AU, ax=axis) # Lambert arc to reach seq[1] dt = (1 - x[4]) * x[5] * DAY2SEC l = lambert_problem(r, r_P1, dt, seq[0].mu_central_body) plot_lambert(l, sol=0, color='r', legend=False, units=AU, ax=axis) v_end_l = l.get_v2()[0] vinf_in = [a - b for a, b in zip(v_end_l, v_P1)] _part_plot(x[6:], AU, axis, seq[1:], x[0] + x[5], vinf_in) return axis mga_1dsm_tof.plot = _mga_1dsm_tof_plot del gtoc6, jpl_lp
kartikkumar/pagmo
PyGMO/problem/_gtop.py
Python
gpl-3.0
32,258
[ "VisIt" ]
e1d9baa1da97b406868cf68911f774ff21042965017024a737cd4436dc49ae15
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2021 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3. # # Psi4 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Psi4; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # import math import itertools import numpy as np from psi4 import core from psi4.driver import p4util from psi4.driver import constants from psi4.driver.p4util.exceptions import * from psi4.driver import driver_nbody_helper ### Math helper functions def nCr(n, r): f = math.factorial return f(n) // f(r) // f(n - r) ### Begin CBS gufunc data def _sum_cluster_ptype_data(ptype, ptype_dict, compute_list, fragment_slice_dict, fragment_size_dict, ret, vmfc=False, n=0): """ Sums gradient and hessian data from compute_list. compute_list comes in as a tuple(frag, basis) """ if len(compute_list) == 0: return sign = 1 # Do ptype if ptype == 'gradient': for fragn, basisn in compute_list: start = 0 grad = np.asarray(ptype_dict[(fragn, basisn)]) if vmfc: sign = ((-1)**(n - len(fragn))) for bas in basisn: end = start + fragment_size_dict[bas] ret[fragment_slice_dict[bas]] += sign * grad[start:end] start += fragment_size_dict[bas] elif ptype == 'hessian': for fragn, basisn in compute_list: hess = np.asarray(ptype_dict[(fragn, basisn)]) if vmfc: sign = ((-1)**(n - len(fragn))) # Build up start and end slices abs_start, rel_start = 0, 0 abs_slices, rel_slices = [], [] for bas in basisn: rel_end = rel_start + 3 * fragment_size_dict[bas] rel_slices.append(slice(rel_start, rel_end)) rel_start += 3 * fragment_size_dict[bas] tmp_slice = fragment_slice_dict[bas] abs_slices.append(slice(tmp_slice.start * 3, tmp_slice.stop * 3)) for abs_sl1, rel_sl1 in zip(abs_slices, rel_slices): for abs_sl2, rel_sl2 in zip(abs_slices, rel_slices): ret[abs_sl1, abs_sl2] += hess[rel_sl1, rel_sl2] else: raise KeyError("ptype can only be gradient or hessian How did you end up here?") def _print_nbody_energy(energy_body_dict, header, embedding=False): core.print_out("""\n ==> N-Body: %s energies <==\n\n""" % header) core.print_out(""" n-Body Total Energy [Eh] I.E. [kcal/mol] Delta [kcal/mol]\n""") previous_e = energy_body_dict[1] nbody_range = list(energy_body_dict) nbody_range.sort() for n in nbody_range: delta_e = (energy_body_dict[n] - previous_e) delta_e_kcal = delta_e * constants.hartree2kcalmol int_e_kcal = ( energy_body_dict[n] - energy_body_dict[1]) * constants.hartree2kcalmol if not embedding else np.nan core.print_out(""" %4s %20.12f %20.12f %20.12f\n""" % (n, energy_body_dict[n], int_e_kcal, delta_e_kcal)) previous_e = energy_body_dict[n] core.print_out("\n") def nbody_gufunc(func, method_string, **kwargs): """ Computes the nbody interaction energy, gradient, or Hessian depending on input. This is a generalized univeral function for computing interaction and total quantities. :returns: *return type of func* |w--w| The data. :returns: (*float*, :py:class:`~psi4.core.Wavefunction`) |w--w| data and wavefunction with energy/gradient/hessian set appropriately when **return_wfn** specified. :type func: function :param func: ``energy`` || etc. Python function that accepts method_string and a molecule. Returns a energy, gradient, or Hessian as requested. :type method_string: string :param method_string: ``'scf'`` || ``'mp2'`` || ``'ci5'`` || etc. First argument, lowercase and usually unlabeled. Indicates the computational method to be passed to func. :type molecule: :ref:`molecule <op_py_molecule>` :param molecule: ``h2o`` || etc. The target molecule, if not the last molecule defined. :type return_wfn: :ref:`boolean <op_py_boolean>` :param return_wfn: ``'on'`` || |dl| ``'off'`` |dr| Indicate to additionally return the :py:class:`~psi4.core.Wavefunction` calculation result as the second element of a tuple. :type bsse_type: string or list :param bsse_type: ``'cp'`` || ``['nocp', 'vmfc']`` || |dl| ``None`` |dr| || etc. Type of BSSE correction to compute: CP, NoCP, or VMFC. The first in this list is returned by this function. By default, this function is not called. :type max_nbody: int :param max_nbody: ``3`` || etc. Maximum n-body to compute, cannot exceed the number of fragments in the moleucle. :type ptype: string :param ptype: ``'energy'`` || ``'gradient'`` || ``'hessian'`` Type of the procedure passed in. :type return_total_data: :ref:`boolean <op_py_boolean>` :param return_total_data: ``'on'`` || |dl| ``'off'`` |dr| If True returns the total data (energy/gradient/etc) of the system, otherwise returns interaction data. :type levels: dict :param levels: ``{1: 'ccsd(t)', 2: 'mp2', 'supersystem': 'scf'}`` || ``{1: 2, 2: 'ccsd(t)', 3: 'mp2'}`` || etc Dictionary of different levels of theory for different levels of expansion Note that method_string is not used in this case. supersystem computes all higher order n-body effects up to nfragments. :type embedding_charges: dict :param embedding_charges: ``{1: [-0.834, 0.417, 0.417], ..}`` Dictionary of atom-centered point charges. keys: 1-based index of fragment, values: list of charges for each fragment. :type charge_method: string :param charge_method: ``scf/6-31g`` || ``b3lyp/6-31g*`` || etc Method to compute point charges for monomers. Overridden by embedding_charges if both are provided. :type charge_type: string :param charge_type: ``MULLIKEN_CHARGES`` || ``LOWDIN_CHARGES`` Default is ``MULLIKEN_CHARGES`` """ # Initialize dictionaries for easy data passing metadata, component_results, nbody_results = {}, {}, {} # Parse some kwargs kwargs = p4util.kwargs_lower(kwargs) if kwargs.get('levels', False): return driver_nbody_helper.multi_level(func, **kwargs) metadata['ptype'] = kwargs.pop('ptype', None) metadata['return_wfn'] = kwargs.pop('return_wfn', False) metadata['return_total_data'] = kwargs.pop('return_total_data', False) metadata['molecule'] = kwargs.pop('molecule', core.get_active_molecule()) metadata['molecule'].update_geometry() metadata['molecule'].fix_com(True) metadata['molecule'].fix_orientation(True) metadata['embedding_charges'] = kwargs.get('embedding_charges', False) metadata['kwargs'] = kwargs core.clean_variables() if metadata['ptype'] not in ['energy', 'gradient', 'hessian']: raise ValidationError("""N-Body driver: The ptype '%s' is not regonized.""" % metadata['ptype']) # Parse bsse_type, raise exception if not provided or unrecognized metadata['bsse_type_list'] = kwargs.pop('bsse_type') if metadata['bsse_type_list'] is None: raise ValidationError("N-Body GUFunc: Must pass a bsse_type") if not isinstance(metadata['bsse_type_list'], list): metadata['bsse_type_list'] = [metadata['bsse_type_list']] for num, btype in enumerate(metadata['bsse_type_list']): metadata['bsse_type_list'][num] = btype.lower() if btype.lower() not in ['cp', 'nocp', 'vmfc']: raise ValidationError("N-Body GUFunc: bsse_type '%s' is not recognized" % btype.lower()) metadata['max_nbody'] = kwargs.get('max_nbody', -1) if metadata['molecule'].nfragments() == 1: raise ValidationError("N-Body requires active molecule to have more than 1 fragment.") metadata['max_frag'] = metadata['molecule'].nfragments() if metadata['max_nbody'] == -1: metadata['max_nbody'] = metadata['molecule'].nfragments() else: metadata['max_nbody'] = min(metadata['max_nbody'], metadata['max_frag']) # Flip this off for now, needs more testing # If we are doing CP lets save them integrals #if 'cp' in bsse_type_list and (len(bsse_type_list) == 1): # # Set to save RI integrals for repeated full-basis computations # ri_ints_io = core.get_global_option('DF_INTS_IO') # # inquire if above at all applies to dfmp2 or just scf # core.set_global_option('DF_INTS_IO', 'SAVE') # psioh = core.IOManager.shared_object() # psioh.set_specific_retention(97, True) bsse_str = metadata['bsse_type_list'][0] if len(metadata['bsse_type_list']) > 1: bsse_str = str(metadata['bsse_type_list']) core.print_out("\n\n") core.print_out(" ===> N-Body Interaction Abacus <===\n") core.print_out(" BSSE Treatment: %s\n" % bsse_str) # Get compute list metadata = build_nbody_compute_list(metadata) # Compute N-Body components component_results = compute_nbody_components(func, method_string, metadata) # Assemble N-Body quantities nbody_results = assemble_nbody_components(metadata, component_results) # Build wfn and bind variables wfn = core.Wavefunction.build(metadata['molecule'], 'def2-svp') dicts = [ 'energies', 'ptype', 'intermediates', 'energy_body_dict', 'gradient_body_dict', 'hessian_body_dict', 'nbody', 'cp_energy_body_dict', 'nocp_energy_body_dict', 'vmfc_energy_body_dict' ] if metadata['ptype'] == 'gradient': wfn.set_gradient(nbody_results['ret_ptype']) nbody_results['gradient_body_dict'] = nbody_results['ptype_body_dict'] elif metadata['ptype'] == 'hessian': nbody_results['hessian_body_dict'] = nbody_results['ptype_body_dict'] wfn.set_hessian(nbody_results['ret_ptype']) component_results_gradient = component_results.copy() component_results_gradient['ptype'] = component_results_gradient['gradients'] metadata['ptype'] = 'gradient' nbody_results_gradient = assemble_nbody_components(metadata, component_results_gradient) wfn.set_gradient(nbody_results_gradient['ret_ptype']) nbody_results['gradient_body_dict'] = nbody_results_gradient['ptype_body_dict'] for r in [component_results, nbody_results]: for d in r: if d in dicts: for var, value in r[d].items(): try: wfn.set_scalar_variable(str(var), value) core.set_scalar_variable(str(var), value) except: wfn.set_array_variable(d.split('_')[0].upper() + ' ' + str(var), core.Matrix.from_array(value)) core.set_variable("CURRENT ENERGY", nbody_results['ret_energy']) wfn.set_variable("CURRENT ENERGY", nbody_results['ret_energy']) if metadata['return_wfn']: return (nbody_results['ret_ptype'], wfn) else: return nbody_results['ret_ptype'] def build_nbody_compute_list(metadata): """Generates the list of N-Body computations to be performed for a given BSSE type. Parameters ---------- metadata : dict of str Dictionary containing N-body metadata. Required ``'key': value`` pairs: ``'bsse_type_list'``: list of str List of requested BSSE treatments. Possible values include lowercase ``'cp'``, ``'nocp'``, and ``'vmfc'``. ``'max_nbody'``: int Maximum number of bodies to include in the N-Body treatment. Possible: `max_nbody` <= `max_frag` Default: `max_nbody` = `max_frag` ``'max_frag'``: int Number of distinct fragments comprising full molecular supersystem. Returns ------- metadata : dict of str Dictionary containing N-body metadata. New ``'key': value`` pair: ``'compute_dict'`` : dict of str: dict Dictionary containing subdicts enumerating compute lists for each possible BSSE treatment. Contents: ``'all'``: dict of int: set Set containing full list of computations required ``'cp'``: dict of int: set Set containing list of computations required for CP procedure ``'nocp'``: dict of int: set Set containing list of computations required for non-CP procedure ``'vmfc_compute'``: dict of int: set Set containing list of computations required for VMFC procedure ``'vmfc_levels'``: dict of int: set Set containing list of levels required for VMFC procedure """ # What levels do we need? nbody_range = range(1, metadata['max_nbody'] + 1) fragment_range = range(1, metadata['max_frag'] + 1) cp_compute_list = {x: set() for x in nbody_range} nocp_compute_list = {x: set() for x in nbody_range} vmfc_compute_list = {x: set() for x in nbody_range} vmfc_level_list = {x: set() for x in nbody_range} # Need to sum something slightly different # Verify proper passing of bsse_type_list bsse_type_remainder = set(metadata['bsse_type_list']) - {'cp', 'nocp', 'vmfc'} if bsse_type_remainder: raise ValidationError("""Unrecognized BSSE type(s): %s Possible values are 'cp', 'nocp', and 'vmfc'.""" % ', '.join(str(i) for i in bsse_type_remainder)) # Build up compute sets if 'cp' in metadata['bsse_type_list']: # Everything is in dimer basis basis_tuple = tuple(fragment_range) for nbody in nbody_range: for x in itertools.combinations(fragment_range, nbody): if metadata['max_nbody'] == 1: break cp_compute_list[nbody].add((x, basis_tuple)) # Add monomers in monomer basis for x in fragment_range: cp_compute_list[1].add(((x, ), (x, ))) if 'nocp' in metadata['bsse_type_list']: # Everything in monomer basis for nbody in nbody_range: for x in itertools.combinations(fragment_range, nbody): nocp_compute_list[nbody].add((x, x)) if 'vmfc' in metadata['bsse_type_list']: # Like a CP for all combinations of pairs or greater for nbody in nbody_range: for cp_combos in itertools.combinations(fragment_range, nbody): basis_tuple = tuple(cp_combos) for interior_nbody in nbody_range: for x in itertools.combinations(cp_combos, interior_nbody): combo_tuple = (x, basis_tuple) vmfc_compute_list[interior_nbody].add(combo_tuple) vmfc_level_list[len(basis_tuple)].add(combo_tuple) # Build a comprehensive compute_range compute_list = {x: set() for x in nbody_range} for n in nbody_range: compute_list[n] |= cp_compute_list[n] compute_list[n] |= nocp_compute_list[n] compute_list[n] |= vmfc_compute_list[n] core.print_out(" Number of %d-body computations: %d\n" % (n, len(compute_list[n]))) metadata['compute_dict'] = { 'all': compute_list, 'cp': cp_compute_list, 'nocp': nocp_compute_list, 'vmfc_compute': vmfc_compute_list, 'vmfc_levels': vmfc_level_list } return metadata def compute_nbody_components(func, method_string, metadata): """Computes requested N-body components. Performs requested computations for psi4::Molecule object `molecule` according to `compute_list` with function `func` at `method_string` level of theory. Parameters ---------- func : {'energy', 'gradient', 'hessian'} Function object to be called within N-Body procedure. method_string : str Indicates level of theory to be passed to function `func`. metadata : dict of str Dictionary of N-body metadata. Required ``'key': value`` pairs: ``'compute_list'``: dict of int: set List of computations to perform. Keys indicate body-levels, e.g,. `compute_list[2]` is the list of all 2-body computations required. ``'kwargs'``: dict Arbitrary keyword arguments to be passed to function `func`. Returns ------- dict of str: dict Dictionary containing computed N-body components. Contents: ``'energies'``: dict of set: float64 Dictionary containing all energy components required for given N-body procedure. ``'ptype'``: dict of set: float64 or dict of set: psi4.Matrix Dictionary of returned quantities from calls of function `func` during N-body computations ``'intermediates'``: dict of str: float64 Dictionary of psivars for intermediate N-body computations to be set at the end of the N-body procedure. """ # Get required metadata kwargs = metadata['kwargs'] molecule = metadata['molecule'] #molecule = core.get_active_molecule() compute_list = metadata['compute_dict']['all'] # Now compute the energies energies_dict = {} gradients_dict = {} ptype_dict = {} intermediates_dict = {} if kwargs.get('charge_method', False) and not metadata['embedding_charges']: metadata['embedding_charges'] = driver_nbody_helper.compute_charges(kwargs['charge_method'], kwargs.get('charge_type', 'MULLIKEN_CHARGES').upper(), molecule) for count, n in enumerate(compute_list.keys()): core.print_out("\n ==> N-Body: Now computing %d-body complexes <==\n\n" % n) total = len(compute_list[n]) for num, pair in enumerate(compute_list[n]): core.print_out( "\n N-Body: Computing complex (%d/%d) with fragments %s in the basis of fragments %s.\n\n" % (num + 1, total, str(pair[0]), str(pair[1]))) ghost = list(set(pair[1]) - set(pair[0])) current_mol = molecule.extract_subsets(list(pair[0]), ghost) current_mol.set_name("%s_%i_%i" % (current_mol.name(), count, num)) if metadata['embedding_charges']: driver_nbody_helper.electrostatic_embedding(metadata, pair=pair) # Save energies info ptype_dict[pair], wfn = func(method_string, molecule=current_mol, return_wfn=True, **kwargs) core.set_global_option_python('EXTERN', None) energies_dict[pair] = core.variable("CURRENT ENERGY") gradients_dict[pair] = wfn.gradient() var_key = "N-BODY (%s)@(%s) TOTAL ENERGY" % (', '.join([str(i) for i in pair[0]]), ', '.join( [str(i) for i in pair[1]])) intermediates_dict[var_key] = core.variable("CURRENT ENERGY") core.print_out("\n N-Body: Complex Energy (fragments = %s, basis = %s: %20.14f)\n" % (str( pair[0]), str(pair[1]), energies_dict[pair])) # Flip this off for now, needs more testing #if 'cp' in bsse_type_list and (len(bsse_type_list) == 1): # core.set_global_option('DF_INTS_IO', 'LOAD') core.clean() return { 'energies': energies_dict, 'gradients': gradients_dict, 'ptype': ptype_dict, 'intermediates': intermediates_dict } def assemble_nbody_components(metadata, component_results): """Assembles N-body components into interaction quantities according to requested BSSE procedure(s). Parameters ----------- metadata : dict of str Dictionary of N-body metadata. Required ``'key': value`` pairs: ``'ptype'``: {'energy', 'gradient', 'hessian'} Procedure which has generated the N-body components to be combined. ``'bsse_type_list'``: list of str List of requested BSSE treatments. Possible values include lowercase ``'cp'``, ``'nocp'``, and ``'vmfc'``. ``'max_nbody'``: int Maximum number of bodies to include in the N-Body treatment. Possible: `max_nbody` <= `max_frag` Default: `max_nbody` = `max_frag` ``'max_frag'``: int Number of distinct fragments comprising full molecular supersystem. ``'energies_dict'``: dict of set: float64 Dictionary containing all energy components required for given N-body procedure. ``'ptype_dict'``: dict of set: float64 or dict of set: psi4.Matrix Dictionary of returned quantities from calls of function `func` during N-body computations ``'compute_dict'``: dict of str: dict Dictionary containing {int: set} subdicts enumerating compute lists for each possible BSSE treatment. ``'kwargs'``: dict Arbitrary keyword arguments. component_results : dict of str: dict Dictionary containing computed N-body components. Required ``'key': value`` pairs: ``'energies'``: dict of set: float64 Dictionary containing all energy components required for given N-body procedure. ``'ptype'``: dict of set: float64 or dict of set: psi4.Matrix Dictionary of returned quantities from calls of function `func` during N-body computations ``'intermediates'``: dict of str: float64 Dictionary of psivars for intermediate N-body computations to be set at the end of the N-body procedure. Returns ------- results : dict of str Dictionary of all N-body results. Contents: ``'ret_energy'``: float64 Interaction data requested. If multiple BSSE types requested in `bsse_type_list`, the interaction data associated with the *first* BSSE type in the list is returned. ``'nbody_dict'``: dict of str: float64 Dictionary of relevant N-body psivars to be set ``'energy_body_dict'``: dict of int: float64 Dictionary of total energies at each N-body level, i.e., ``results['energy_body_dict'][2]`` is the sum of all 2-body total energies for the supersystem. ``'ptype_body_dict'``: dict or dict of int: array_like Empty dictionary if `ptype is ``'energy'``, or dictionary of total ptype arrays at each N-body level; i.e., ``results['ptype_body_dict'][2]`` for `ptype` ``'gradient'``is the total 2-body gradient. """ # Unpack metadata kwargs = metadata['kwargs'] nbody_range = range(1, metadata['max_nbody'] + 1) # Unpack compute list metadata compute_list = metadata['compute_dict']['all'] cp_compute_list = metadata['compute_dict']['cp'] nocp_compute_list = metadata['compute_dict']['nocp'] vmfc_compute_list = metadata['compute_dict']['vmfc_compute'] vmfc_level_list = metadata['compute_dict']['vmfc_levels'] # Build size and slices dictionaries fragment_size_dict = { frag: metadata['molecule'].extract_subsets(frag).natom() for frag in range(1, metadata['max_frag'] + 1) } start = 0 fragment_slice_dict = {} for k, v in fragment_size_dict.items(): fragment_slice_dict[k] = slice(start, start + v) start += v molecule_total_atoms = sum(fragment_size_dict.values()) # Final dictionaries cp_energy_by_level = {n: 0.0 for n in nbody_range} nocp_energy_by_level = {n: 0.0 for n in nbody_range} cp_energy_body_dict = {n: 0.0 for n in nbody_range} nocp_energy_body_dict = {n: 0.0 for n in nbody_range} vmfc_energy_body_dict = {n: 0.0 for n in nbody_range} # Build out ptype dictionaries if needed if metadata['ptype'] != 'energy': if metadata['ptype'] == 'gradient': arr_shape = (molecule_total_atoms, 3) elif metadata['ptype'] == 'hessian': arr_shape = (molecule_total_atoms * 3, molecule_total_atoms * 3) else: raise KeyError("N-Body: ptype '%s' not recognized" % ptype) cp_ptype_by_level = {n: np.zeros(arr_shape) for n in nbody_range} nocp_ptype_by_level = {n: np.zeros(arr_shape) for n in nbody_range} vmfc_ptype_by_level = {n: np.zeros(arr_shape) for n in nbody_range} cp_ptype_body_dict = {n: np.zeros(arr_shape) for n in nbody_range} nocp_ptype_body_dict = {n: np.zeros(arr_shape) for n in nbody_range} vmfc_ptype_body_dict = {n: np.zeros(arr_shape) for n in nbody_range} else: cp_ptype_by_level, cp_ptype_body_dict = {}, {} nocp_ptype_by_level, nocp_ptype_body_dict = {}, {} vmfc_ptype_body_dict = {} # Sum up all of the levels nbody_dict = {} for n in nbody_range: # Energy # Extract energies for monomers in monomer basis for CP total data if n == 1: cp_monomers_in_monomer_basis = [v for v in cp_compute_list[1] if len(v[1]) == 1] cp_monomer_energies = 0.0 cp_monomer_energy_list = [] for i in cp_monomers_in_monomer_basis: cp_monomer_energy_list.append(component_results['energies'][i]) cp_monomer_energies += component_results['energies'][i] cp_compute_list[1].remove(i) cp_energy_by_level[n] = sum(component_results['energies'][v] for v in cp_compute_list[n]) nocp_energy_by_level[n] = sum(component_results['energies'][v] for v in nocp_compute_list[n]) # Special vmfc case if n > 1: vmfc_energy_body_dict[n] = vmfc_energy_body_dict[n - 1] for tup in vmfc_level_list[n]: vmfc_energy_body_dict[n] += ((-1)**(n - len(tup[0]))) * component_results['energies'][tup] # Do ptype if metadata['ptype'] != 'energy': _sum_cluster_ptype_data(metadata['ptype'], component_results['ptype'], cp_compute_list[n], fragment_slice_dict, fragment_size_dict, cp_ptype_by_level[n]) _sum_cluster_ptype_data(metadata['ptype'], component_results['ptype'], nocp_compute_list[n], fragment_slice_dict, fragment_size_dict, nocp_ptype_by_level[n]) _sum_cluster_ptype_data( metadata['ptype'], component_results['ptype'], vmfc_level_list[n], fragment_slice_dict, fragment_size_dict, vmfc_ptype_by_level[n], vmfc=True, n=n) # Add extracted monomers back. for i, j in enumerate(cp_monomers_in_monomer_basis): cp_compute_list[1].add(j) if metadata['ptype'] != 'energy': # Extract ptype data for monomers in monomer basis for CP total data cp_monomer_ptype = np.zeros(arr_shape) _sum_cluster_ptype_data(metadata['ptype'], component_results['ptype'], cp_monomers_in_monomer_basis, fragment_slice_dict, fragment_size_dict, cp_monomer_ptype) # Compute cp energy and ptype if 'cp' in metadata['bsse_type_list']: for n in nbody_range: if n == metadata['max_frag']: cp_energy_body_dict[n] = cp_energy_by_level[n] - bsse if metadata['ptype'] != 'energy': cp_ptype_body_dict[n][:] = cp_ptype_by_level[n] - bsse_ptype continue for k in range(1, n + 1): take_nk = nCr(metadata['max_frag'] - k - 1, n - k) sign = ((-1)**(n - k)) value = cp_energy_by_level[k] cp_energy_body_dict[n] += take_nk * sign * value if metadata['ptype'] != 'energy': value = cp_ptype_by_level[k] cp_ptype_body_dict[n] += take_nk * sign * value if n == 1: bsse = cp_energy_body_dict[n] - cp_monomer_energies cp_energy_body_dict[n] = cp_monomer_energies if metadata['ptype'] != 'energy': bsse_ptype = cp_ptype_body_dict[n] - cp_monomer_ptype cp_ptype_body_dict[n] = cp_monomer_ptype.copy() else: cp_energy_body_dict[n] -= bsse if metadata['ptype'] != 'energy': cp_ptype_body_dict[n] -= bsse_ptype cp_interaction_energy = cp_energy_body_dict[metadata['max_nbody']] - cp_energy_body_dict[1] nbody_dict['Counterpoise Corrected Interaction Energy'] = cp_interaction_energy for n in nbody_range[1:]: var_key = 'CP-CORRECTED %d-BODY INTERACTION ENERGY' % n nbody_dict[var_key] = cp_energy_body_dict[n] - cp_energy_body_dict[1] _print_nbody_energy(cp_energy_body_dict, "Counterpoise Corrected (CP)", metadata['embedding_charges']) cp_interaction_energy = cp_energy_body_dict[metadata['max_nbody']] - cp_energy_body_dict[1] nbody_dict['Counterpoise Corrected Total Energy'] = cp_energy_body_dict[metadata['max_nbody']] nbody_dict['Counterpoise Corrected Interaction Energy'] = cp_interaction_energy # Compute nocp energy and ptype if 'nocp' in metadata['bsse_type_list']: for n in nbody_range: if n == metadata['max_frag']: nocp_energy_body_dict[n] = nocp_energy_by_level[n] if metadata['ptype'] != 'energy': nocp_ptype_body_dict[n][:] = nocp_ptype_by_level[n] continue for k in range(1, n + 1): take_nk = nCr(metadata['max_frag'] - k - 1, n - k) sign = ((-1)**(n - k)) value = nocp_energy_by_level[k] nocp_energy_body_dict[n] += take_nk * sign * value if metadata['ptype'] != 'energy': value = nocp_ptype_by_level[k] nocp_ptype_body_dict[n] += take_nk * sign * value _print_nbody_energy(nocp_energy_body_dict, "Non-Counterpoise Corrected (NoCP)", metadata['embedding_charges']) nocp_interaction_energy = nocp_energy_body_dict[metadata['max_nbody']] - nocp_energy_body_dict[1] nbody_dict['Non-Counterpoise Corrected Total Energy'] = nocp_energy_body_dict[metadata['max_nbody']] nbody_dict['Non-Counterpoise Corrected Interaction Energy'] = nocp_interaction_energy for n in nbody_range[1:]: var_key = 'NOCP-CORRECTED %d-BODY INTERACTION ENERGY' % n nbody_dict[var_key] = nocp_energy_body_dict[n] - nocp_energy_body_dict[1] # Compute vmfc ptype if 'vmfc' in metadata['bsse_type_list']: if metadata['ptype'] != 'energy': for n in nbody_range: if n > 1: vmfc_ptype_body_dict[n] = vmfc_ptype_by_level[n - 1] vmfc_ptype_body_dict[n] += vmfc_ptype_by_level[n] _print_nbody_energy(vmfc_energy_body_dict, "Valiron-Mayer Function Couterpoise (VMFC)", metadata['embedding_charges']) vmfc_interaction_energy = vmfc_energy_body_dict[metadata['max_nbody']] - vmfc_energy_body_dict[1] nbody_dict['Valiron-Mayer Function Couterpoise Total Energy'] = vmfc_energy_body_dict[metadata['max_nbody']] nbody_dict['Valiron-Mayer Function Couterpoise Interaction Energy'] = vmfc_interaction_energy for n in nbody_range[1:]: var_key = 'VMFC-CORRECTED %d-BODY INTERACTION ENERGY' % n nbody_dict[var_key] = vmfc_energy_body_dict[n] - vmfc_energy_body_dict[1] # Returns results = {} results['nbody'] = nbody_dict for b in ['cp', 'nocp', 'vmfc']: results['%s_energy_body_dict' % b] = eval('%s_energy_body_dict' % b) results['%s_energy_body_dict' % b] = {str(i) + b: j for i, j in results['%s_energy_body_dict' % b].items()} # Figure out and build return types return_method = metadata['bsse_type_list'][0] if return_method == 'cp': results['ptype_body_dict'] = cp_ptype_body_dict results['energy_body_dict'] = cp_energy_body_dict elif return_method == 'nocp': results['ptype_body_dict'] = nocp_ptype_body_dict results['energy_body_dict'] = nocp_energy_body_dict elif return_method == 'vmfc': results['ptype_body_dict'] = vmfc_ptype_body_dict results['energy_body_dict'] = vmfc_energy_body_dict else: raise ValidationError( "N-Body Wrapper: Invalid return type. Should never be here, please post this error on github.") if metadata['return_total_data']: results['ret_energy'] = results['energy_body_dict'][metadata['max_nbody']] else: results['ret_energy'] = results['energy_body_dict'][metadata['max_nbody']] results['ret_energy'] -= results['energy_body_dict'][1] if metadata['ptype'] != 'energy': if metadata['return_total_data']: np_final_ptype = results['ptype_body_dict'][metadata['max_nbody']].copy() else: np_final_ptype = results['ptype_body_dict'][metadata['max_nbody']].copy() np_final_ptype -= results['ptype_body_dict'][1] results['ret_ptype'] = core.Matrix.from_array(np_final_ptype) else: results['ret_ptype'] = results['ret_energy'] return results
ashutoshvt/psi4
psi4/driver/driver_nbody.py
Python
lgpl-3.0
34,436
[ "Psi4" ]
3e57d41bde2722598de85e93ec3e776a12d179533093e170e2566d21449d467c
from hercule import Request from config import api_key #This assumes you have an external config file that houses your API key. If you do not, to run this example, delete this line and input your API key when we initialize the Request object def main(): # Initialize your Request class by passing in the api key - visit https://developer.riotgames.com/sign-in in order to register for yours! r = Request(api_key) # Calling a function involves passing in a name whenever a function asks for it - all API calls will have a method that takes a summoner name as a sole argument player_id = r.get_id_from_name('The Rain Man') print player_id # Most functions return a dict or list of dicts. Most functions will take summoner ID's or player names as parameters masteries = r.get_masteries_from_id(player_id) print type(masteries) print type(masteries['pages']) # All summoner-based calls assume NA region. If you want another region, just pass it in after the summoner name current_runes = r.get_current_runes_from_name('Froggen', 'euw') print current_runes['name'] # Asking for any multi-page info (like teams or stats) of a player returns a multi-page json DTO teams = r.get_teams_from_name('Dyrus') print teams[0]['name'] # Asking for ranked stats or a player's stat summary will require a season, defaulted to season 4. As of this writing, season 4 has not started yet, so calling the default stat functions will not return anything particularly useful - pass in 'SEASON3' in order to get the previous season's statistics. stats = r.get_ranked_summary_from_name('TheOddOne','na', 'SEASON3') print stats['champions'][0]['stats'] # Getting all champions doesn't require a player name, but it requires a region and an optional free-to-play argument # Calling get_champions() with no arguments will return all champions with regards to the North American Server champs = r.get_champions(True, 'na') print len(champs['champions']) if __name__ == ('__main__'): main()
Greedoid/Hercule
example.py
Python
mit
2,005
[ "VisIt" ]
7bee984af214b02a25a2a5d28646c6e089f72bd39613a5d9deed19afa8572a3e
from __future__ import division import collections import importlib import networkx as nx import numpy as np PI = np.pi from neurokernel.pattern import Pattern from .geometry.opticaxis import opticaxisFactory, RuleHexArrayMap, OpticAxisRule def divceil(x, y): return (x+y-1)//y class Ommatidium(object): def __init__(self, element): ''' element: ArrayElement object ''' elev, azim = element.dima, element.dimb self._elev = elev self._azim = azim self.element = element # maybe simple dic is sufficient self.neurons = collections.OrderedDict() def add_neuron(self, neuron): if neuron.name not in self.neurons: self.neurons[neuron.name] = neuron def get_neighborid(self, neighbor_dr): return self.element.get_neighborid(neighbor_dr) @property def is_dummy(self): return self.element.is_dummy @property def sphere_pos(self): return self._elev, self._azim @property def gid(self): return self.element.gid @property def photoreceptor_num(self): return sum(n.is_photoreceptor for n in self.neurons.values()) @property def neuron_num(self): return len(self.neurons) class RetinaArray(object): def __init__(self, hex_array, config, gen_graph = True): self.hex_array = hex_array modelname = config['Retina']['model'] #try: # self.model = importlib.import_module('vision_models.{}' # .format(modelname)) #except ImportError: self.model = importlib.import_module('retina.vision_models.{}' .format(modelname)) self.opticaxis = opticaxisFactory('SuperpositionLT')() self.rulemap = RuleHexArrayMap(self.opticaxis, hex_array) self._set_elements() self._update_neurons() # in degrees self.interommatidial_angle = self._get_interommatidial_angle() # in degrees acc_factor = config['Retina']['acceptance_factor'] self.acceptance_angle = self.interommatidial_angle * acc_factor if gen_graph: self._generate_graph() def _set_elements(self): self._ommatidia = [Ommatidium(el) for el in self.hex_array.elements] def _update_neurons(self): for omm in self._ommatidia: for neuron_params in self.model.OMMATIDIA_NEURON_LIST: self._add_photoreceptor(omm, neuron_params) def _add_photoreceptor(self, ommatidium, neuron_params): nid = self.opticaxis.name_to_ind(neuron_params['name']) neighbordr = self.opticaxis.neighbor_for_photor(nid) neighborid = ommatidium.get_neighborid(neighbordr) # position on sphere coincides with the # surface normal and the desired direction direction = self._ommatidia[neighborid].sphere_pos photor = OmmatidiumNeuron(ommatidium, direction, neuron_params) ommatidium.add_neuron(photor) def _add_fb_neuron(self, ommatidium, neuron_params): neuron = OmmatidiumNeuron(ommatidium, None, neuron_params, is_photoreceptor=False) ommatidium.add_neuron(neuron) def _get_interommatidial_angle(self): ''' Returns angle in degrees ''' elev1, azim1 = self._ommatidia[0].sphere_pos try: elev2, azim2 = self._ommatidia[1].sphere_pos except IndexError: # when there is only one element # assume interommatidial angle is 90 return 90 x1 = np.sin(elev1)*np.cos(azim1) y1 = np.sin(elev1)*np.sin(azim1) z1 = np.cos(elev1) x2 = np.sin(elev2)*np.cos(azim2) y2 = np.sin(elev2)*np.sin(azim2) z2 = np.cos(elev2) angle = np.arccos(x1*x2 + y1*y2 + z1*z2) return float(angle*180/np.pi) def get_all_photoreceptors(self): return [photor for ommatidium in self._ommatidia for photor in ommatidium.neurons.values() if photor.name in ['R1', 'R2', 'R3', 'R4', 'R5', 'R6']] def get_angle(self): return self.acceptance_angle def get_all_photoreceptors_dir(self): allphotors = self.get_all_photoreceptors() elevazim = np.array([photor.sphere_pos for photor in allphotors]) dirs = np.array([photor.direction for photor in allphotors]) return elevazim[:, 0], elevazim[:, 1], dirs[:, 0], dirs[:, 1] def get_ommatidia_pos(self): positions = np.array([omm.sphere_pos for omm in self._ommatidia]) return positions[:, 0], positions[:, 1] def generate_neuroarch_gexf(self, G_lamina = None): G_neuroarch = nx.MultiDiGraph() hex_loc = self.hex_array.hex_loc for i, omm in enumerate(self._ommatidia): sphere_pos = omm.sphere_pos hx_loc = hex_loc[i] circuit_name = 'ommatidium_{}'.format(i) G_neuroarch.add_node('circuit_'+ circuit_name, **{'name': 'Ommatidium', 'elev_3d': float(sphere_pos[0]), 'azim_3d': float(sphere_pos[1]), 'x_2d': float(hx_loc[0]), 'y_2d': float(hx_loc[1])}) for name, neuron in omm.neurons.items(): direction = neuron.direction neuron.id = 'neuron_{}_{}'.format(name, i) G_neuroarch.add_node(neuron.id, **neuron.params.copy()) G_neuroarch.node[neuron.id].update( {'name': name, 'elev_3d': float(sphere_pos[0]), 'azim_3d': float(sphere_pos[1]), 'x_2d': float(hx_loc[0]), 'y_2d': float(hx_loc[1]), 'genetic.neurotransmitter': 'histamine', 'optic_axis_elev': float(direction[0]), 'optic_axis_azim': float(direction[1]), 'circuit': circuit_name, 'acceptance_angle': self.get_angle()}) G_neuroarch.add_node( neuron.id+'_port', **{'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'out', 'circuit': circuit_name, 'selector': '/ret/{}/{}'.format(i, name)}) G_neuroarch.add_edge(neuron.id, neuron.id+'_port') G_neuroarch.add_node( neuron.id+'_aggregator_port', **{'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'in', 'circuit': circuit_name, 'selector': '/ret/{}/{}_agg'.format(i,name)}) G_neuroarch.add_edge(neuron.id+'_aggregator_port', neuron.id, variable = 'I') return G_neuroarch def _generate_graph(self): G_master = nx.DiGraph() G_workers = nx.DiGraph() G_workers_nomaster = nx.DiGraph() self.worker_comp_list = [] num_photoreceptors = self.num_photoreceptors num_w1 = 0 # workers no master counter num_w2 = 0 # workers counter num_m = 0 for i, omm in enumerate(self._ommatidia): for name, neuron in omm.neurons.items(): neuron.id = 'neuron_{}_{}'.format(name, i) G_workers_nomaster.add_node(neuron.id, **neuron.params.copy()) G_workers_nomaster.add_node( neuron.id+'_port', **{'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'out', 'selector': '/ret/{}/{}'.format(i, name)}) G_workers_nomaster.add_node( neuron.id+'_photon', **{'class': 'BufferPhoton', 'name': '{}_buf'.format(name) }) G_workers_nomaster.add_edge(neuron.id, neuron.id+'_port') G_workers_nomaster.add_edge(neuron.id+'_photon', neuron.id) G_workers_nomaster.add_node( neuron.id+'_aggregator_port', **{'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'in', 'selector': '/ret/{}/{}_agg'.format(i,name)}) G_workers_nomaster.add_edge(neuron.id+'_aggregator_port', neuron.id, variable = 'I') num_w1 += 1 if OpticAxisRule.is_photor(name): ind = OpticAxisRule.name_to_ind(name) G_workers.add_node(neuron.id, **neuron.params.copy()) self.worker_comp_list.append(neuron.id) G_workers.add_node(neuron.id+'_in', **{ 'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'in', 'selector': '/retina_worker/{}/in_R{}'.format(i, ind) }) G_workers.add_node(neuron.id+'_out', **{ 'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'out', 'selector': '/retina_worker/{}/out_R{}'.format(i, ind) }) G_workers.add_edge(neuron.id+'_in', neuron.id) G_workers.add_edge(neuron.id, neuron.id+'_out') G_workers.add_node(neuron.id+'_aggregator_port', **{ 'class': 'Port', 'name': name, 'port_type': 'gpot', 'port_io': 'in', 'selector': '/retina_worker/{}/agg_R{}'.format(i, ind) }) G_workers.add_edge(neuron.id+'_aggregator_port', neuron.id, variable = 'I') num_w2 += 1 G_master.add_node(neuron.id+'_photon', **{ 'class': 'BufferPhoton', 'name': 'buf{}'.format(ind) }) G_master.add_node(neuron.id+'_buff_in',**{ 'class': 'Port', 'port_type': 'gpot', 'port_io': 'in', 'name': 'collect_{}'.format(name), 'selector': '/retina_master/{}/in_R{}'.format(i, ind) }) G_master.add_node(neuron.id+'_photon_out', **{ 'class': 'Port', 'port_type': 'gpot', 'port_io': 'out', 'name': 'port_buf_{}'.format(name), 'selector': '/retina_master/{}/buf_R{}'.format(i, ind) }) G_master.add_node(neuron.id, **{ 'class': 'BufferVoltage', 'name': 'buf_voltage_{}'.format(name) }) G_master.add_node(neuron.id+'_out', **{ 'class': 'Port', 'port_type': 'gpot', 'port_io': 'out', 'name': name, 'selector': '/ret/{}/R{}'.format(i, ind) }) G_master.add_edge(neuron.id+'_photon', neuron.id+'_photon_out') G_master.add_edge(neuron.id+'_buff_in', neuron.id) G_master.add_edge(neuron.id, neuron.id+'_out') G_master.add_node(neuron.id+'_aggregator_out', **{ 'class': 'Port', 'port_type': 'gpot', 'port_io': 'out', 'name': name, 'selector': '/retina_master/{}/agg_R{}'.format(i, ind) }) G_master.add_node(neuron.id+'_aggregator_in', **{ 'class': 'Port', 'port_type': 'gpot', 'port_io': 'in', 'name': name, 'selector': '/ret/{}/R{}_agg'.format(i, ind) }) G_master.add_node(neuron.id+'_buff_current', **{ 'class': 'BufferCurrent', 'name': 'buff_current_'+name, }) G_master.add_edge(neuron.id+'_aggregator_in', neuron.id+'buff_current', variable = 'I') G_master.add_edge(neuron.id+'_buff_current', neuron.id+'aggregator_out', variable = 'I') num_m += 1 self.G_master = G_master self.G_workers = G_workers self.G_workers_nomaster = G_workers_nomaster def get_worker_nomaster_graph(self, *args): try: return self.G_workers_nomaster.subgraph(self.get_nodes(*args)) except TypeError: return self.G_workers_nomaster def get_worker_graph(self, *args): try: nodes = self.get_worker_nodes_id(*args) nodes += [i + '_in' for i in nodes] nodes += [i + '_aggregator_port' for i in nodes] return self.G_workers.subgraph(nodes) except TypeError: return self.G_workers def get_master_graph(self): return self.G_master def update_pattern_master_worker(self, j, worker_num): indexes = self.get_worker_nodes(j, worker_num) master_selectors = self.get_master_selectors() worker_selectors = self.get_worker_selectors(j, worker_num) from_list = [] to_list = [] for i, ind in enumerate(indexes): col_m = ind // 6 ind_m = 1 + (ind % 6) src = '/retina_master/{}/buf_R{}'.format(col_m, ind_m) dest = '/retina_worker/{}/in_R{}'.format(col_m, ind_m) from_list.append(src) to_list.append(dest) src = '/retina_worker/{}/out_R{}'.format(col_m, ind_m) dest = '/retina_master/{}/in_R{}'.format(col_m, ind_m) from_list.append(src) to_list.append(dest) src = '/retina_master/{}/agg_R{}'.format(col_m, ind_m) dest = '/retina_worker/{}/agg_R{}'.format(col_m, ind_m) from_list.append(src) to_list.append(dest) pattern = Pattern.from_concat(','.join(master_selectors), ','.join(worker_selectors), from_sel = ','.join(from_list), to_sel = ','.join(to_list), gpot_sel = ','.join(from_list+to_list)) return pattern # Neuron representation def get_neurons(self, j, sublpu_num): # numbering starts from 1 ommatidia = self._ommatidia ommatidia_num = len(ommatidia) start = divceil((j-1)*ommatidia_num, sublpu_num) end = divceil(j*ommatidia_num, sublpu_num) neurons = [] # implicit assumption i is the same as # the global id of for i in range(start, end): ommatidium = ommatidia[i] for omm_neuron in ommatidium.neurons.values(): neurons.append((ommatidium.gid, omm_neuron.name, ommatidium.sphere_pos)) return neurons # Numeric order representation def get_interval(self, j, sublpu_num): ''' Returns jth interval out of `sublpu_num`. Numbering starts from 1. Outputs are multiple of neuron_types. End index of last interval might be greater but not less than the number of photoreceptors. Indexes match positions returned by `get_all_photoreceptors` ''' ommatidia_num = self.num_elements start = self.neuron_types*divceil((j-1)*ommatidia_num, sublpu_num) end = self.neuron_types*divceil(j*ommatidia_num, sublpu_num) return start, end def get_worker_interval(self, j, sublpu_num): ''' Returns jth interval out of `sublpu_num`. Numbering starts from 1. Outputs are multiple of photoreceptor_types. End index of last interval might be greater but not less than the number of photoreceptors. Indexes match positions returned by `get_all_photoreceptors` ''' ommatidia_num = self.num_elements start = self.photoreceptor_types*divceil((j-1)*ommatidia_num, sublpu_num) end = self.photoreceptor_types*divceil(j*ommatidia_num, sublpu_num) return start, end # Node key representation def get_nodes(self, j, sublpu_num): # numbering starts from 1 return list(range(*self.get_interval(j, sublpu_num))) def get_worker_nodes(self, j, sublpu_num): # numbering starts from 1 return list(range(*self.get_worker_interval(j, sublpu_num))) def get_worker_nodes_id(self, j, sublpu_num): # numbering starts from 1 return self.worker_comp_list(range(*self.get_worker_interval(j, sublpu_num))) # Selector representation def get_selectors(self, j, sublpu_num): # numbering starts from 1 selectors = [] for n in self.get_neurons(j, sublpu_num): n_id, n_name, _ = n selectors.append('/ret/{}/{}'.format(n_id, n_name)) selectors.append('/ret/{}/{}_agg'.format(n_id, n_name)) return selectors # Selector representation (all) def get_all_selectors(self): # Get interval as if there is 1 LPU # so get all nodes return self.get_selectors(1, 1) def get_master_selectors(self): selectors = [] for i in self.get_worker_nodes(1, 1): col = i // 6 ind = 1 + (i % 6) selectors.append('/retina_master/{}/buf{}'.format(col, ind)) selectors.append('/retina_master/{}/in{}'.format(col, ind)) selectors.append('/ret/{}/R{}'.format(col, ind)) return selectors def get_worker_selectors(self, j, workernum): selectors = [] for i in self.get_worker_nodes(j, workernum): col = i // 6 ind = 1 + (i % 6) selectors.append('/retina_worker/{}/in{}'.format(col, ind)) selectors.append('/retina_worker/{}/out{}'.format(col, ind)) return selectors # A convenient representation of all neuron information def get_neuron_objects(self): return self._ommatidia def get_neighborid(self, oid, neighbor_dr): ''' Get id of neighbor of `oid` ommatidium in a specific direction ''' return self._ommatidia[oid].get_neighborid(neighbor_dr) def index(self, ommid, name): return self._ommatidia[ommid].neurons.keys().index(name) @property def num_neurons(self): return self.neuron_types*self.num_elements @property def num_photoreceptors(self): return self.photoreceptor_types*self.num_elements @property def num_elements(self): return self.hex_array.num_elements @property def neuron_types(self): return self._ommatidia[0].neuron_num @property def photoreceptor_types(self): return self._ommatidia[0].photoreceptor_num @property def radius(self): return self.hex_array.radius class Neuron(object): def __init__(self, params): self.name = params.get('name') self.params = params.copy() self.num = None self.outgoing_synapses = [] self.incoming_synapses = [] def add_outgoing_synapse(self, synapse): self.outgoing_synapses.append(synapse) def add_incoming_synapse(self, synapse): self.incoming_synapses.append(synapse) def remove_outgoing_synapse(self, synapse): self.outgoing_synapses.remove(synapse) def remove_incoming_synapse(self, synapse): self.incoming_synapses.remove(synapse) def __repr__(self): return 'neuron {}: {}'.format(self.params['name'], self.params) def __str__(self): return 'neuron {}'.format(self.params['name']) class OmmatidiumNeuron(Neuron): def __init__(self, ommatidium, direction, params, is_photoreceptor=True): ''' ommatidium: ommatidium object direction: tuple of 2 coordinates (elevation, azimuth) or None direction of photoreceptor optical axis ''' self.parent = ommatidium self.direction = direction self._is_photoreceptor = is_photoreceptor super(OmmatidiumNeuron, self).__init__(params) @property def sphere_pos(self): return self.parent.sphere_pos @property def is_photoreceptor(self): return self._is_photoreceptor class Synapse(object): def __init__(self, params): """ params: a dictionary of neuron parameters. It can be passed as an attribute dictionary parameter for a node in networkx library. """ self._params = params.copy() def link(self, pre_neuron, post_neuron): self.pre_neuron = pre_neuron self.post_neuron = post_neuron self.pre_neuron.add_outgoing_synapse(self) self.post_neuron.add_incoming_synapse(self) def __repr__(self): return 'synapse from {} to {}: {}'.format(self.params['prename'], self.params['postname'], self.params) def __str__(self): return 'synapse from {} to {}'.format(self.params['prename'], self.params['postname']) @property def prenum(self): return self._prenum @prenum.setter def prenum(self, value): self._prenum = value @property def postnum(self): return self._postnum @postnum.setter def postnum(self, value): self._postnum = value @property def params(self): return self._params def process_before_export(self): # assumes all conductances are gpot to gpot self._params.update({'class': 3}) self._params.update({'conductance': True}) if 'cart' in self._params.keys(): del self._params['cart'] if 'scale' in self.params.keys(): self._params['slope'] *= self._params['scale'] self._params['saturation'] *= self._params['scale'] del self._params['scale'] def main(): from retina.screen.map.mapimpl import AlbersProjectionMap import retina.geometry.hexagon as hex from retina.configreader import ConfigReader import retina.retina as ret import networkx as nx config=ConfigReader('retlam_default.cfg','../template_spec.cfg').conf transform = AlbersProjectionMap(config['Retina']['radius'],config['Retina']['eulerangles']).invmap hexarray = hex.HexagonArray(num_rings = 14, radius = config['Retina']['radius'], transform = transform) a = ret.RetinaArray(hexarray, config) G = a.generate_neuroarch_gexf() nx.write_gexf(G, 'retina_neuroarch.gexf.gz') if __name__ == "__main__": main()
neurokernel/retina
retina/retina.py
Python
bsd-3-clause
24,043
[ "NEURON" ]
1923806821b733c5ea936126c46419a0083d0076fb721ecaa2304d40499f4671
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. import sys import re import os import shlex import yaml import copy import optparse import operator from ansible import errors from ansible import __version__ from ansible.utils import template from ansible.utils.display_functions import * from ansible.utils.plugins import * from ansible.callbacks import display import ansible.constants as C import ast import time import StringIO import stat import termios import tty import pipes import random import difflib import warnings import traceback import getpass import sys import json #import vault from vault import VaultLib VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 try: import json except ImportError: import simplejson as json try: from hashlib import md5 as _md5 except ImportError: from md5 import md5 as _md5 PASSLIB_AVAILABLE = False try: import passlib.hash PASSLIB_AVAILABLE = True except: pass KEYCZAR_AVAILABLE=False try: try: # some versions of pycrypto may not have this? from Crypto.pct_warnings import PowmInsecureWarning except ImportError: PowmInsecureWarning = RuntimeWarning with warnings.catch_warnings(record=True) as warning_handler: warnings.simplefilter("error", PowmInsecureWarning) try: import keyczar.errors as key_errors from keyczar.keys import AesKey except PowmInsecureWarning: system_warning( "The version of gmp you have installed has a known issue regarding " + \ "timing vulnerabilities when used with pycrypto. " + \ "If possible, you should update it (ie. yum update gmp)." ) warnings.resetwarnings() warnings.simplefilter("ignore") import keyczar.errors as key_errors from keyczar.keys import AesKey KEYCZAR_AVAILABLE=True except ImportError: pass ############################################################### # Abstractions around keyczar ############################################################### def key_for_hostname(hostname): # fireball mode is an implementation of ansible firing up zeromq via SSH # to use no persistent daemons or key management if not KEYCZAR_AVAILABLE: raise errors.AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes") key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR) if not os.path.exists(key_path): os.makedirs(key_path, mode=0700) os.chmod(key_path, int(C.ACCELERATE_KEYS_DIR_PERMS, 8)) elif not os.path.isdir(key_path): raise errors.AnsibleError('ACCELERATE_KEYS_DIR is not a directory.') if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8): raise errors.AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))) key_path = os.path.join(key_path, hostname) # use new AES keys every 2 hours, which means fireball must not allow running for longer either if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60*60*2): key = AesKey.Generate() fd = os.open(key_path, os.O_WRONLY | os.O_CREAT, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)) fh = os.fdopen(fd, 'w') fh.write(str(key)) fh.close() return key else: if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8): raise errors.AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path)) fh = open(key_path) key = AesKey.Read(fh.read()) fh.close() return key def encrypt(key, msg): return key.Encrypt(msg) def decrypt(key, msg): try: return key.Decrypt(msg) except key_errors.InvalidSignatureError: raise errors.AnsibleError("decryption failed") ############################################################### # UTILITY FUNCTIONS FOR COMMAND LINE TOOLS ############################################################### def err(msg): ''' print an error message to stderr ''' print >> sys.stderr, msg def exit(msg, rc=1): ''' quit with an error to stdout and a failure code ''' err(msg) sys.exit(rc) def jsonify(result, format=False): ''' format JSON output (uncompressed or uncompressed) ''' if result is None: return "{}" result2 = result.copy() for key, value in result2.items(): if type(value) is str: result2[key] = value.decode('utf-8', 'ignore') if format: return json.dumps(result2, sort_keys=True, indent=4) else: return json.dumps(result2, sort_keys=True) def write_tree_file(tree, hostname, buf): ''' write something into treedir/hostname ''' # TODO: might be nice to append playbook runs per host in a similar way # in which case, we'd want append mode. path = os.path.join(tree, hostname) fd = open(path, "w+") fd.write(buf) fd.close() def is_failed(result): ''' is a given JSON result a failed result? ''' return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true'])) def is_changed(result): ''' is a given JSON result a changed result? ''' return (result.get('changed', False) in [ True, 'True', 'true']) def check_conditional(conditional, basedir, inject, fail_on_undefined=False): if conditional is None or conditional == '': return True if isinstance(conditional, list): for x in conditional: if not check_conditional(x, basedir, inject, fail_on_undefined=fail_on_undefined): return False return True if not isinstance(conditional, basestring): return conditional conditional = conditional.replace("jinja2_compare ","") # allow variable names if conditional in inject and '-' not in str(inject[conditional]): conditional = inject[conditional] conditional = template.template(basedir, conditional, inject, fail_on_undefined=fail_on_undefined) original = str(conditional).replace("jinja2_compare ","") # a Jinja2 evaluation that results in something Python can eval! presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional conditional = template.template(basedir, presented, inject) val = conditional.strip() if val == presented: # the templating failed, meaning most likely a # variable was undefined. If we happened to be # looking for an undefined variable, return True, # otherwise fail if "is undefined" in conditional: return True elif "is defined" in conditional: return False else: raise errors.AnsibleError("error while evaluating conditional: %s" % original) elif val == "True": return True elif val == "False": return False else: raise errors.AnsibleError("unable to evaluate conditional: %s" % original) def is_executable(path): '''is the given path executable?''' return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE] or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH & os.stat(path)[stat.ST_MODE]) def unfrackpath(path): ''' returns a path that is free of symlinks, environment variables, relative path traversals and symbols (~) example: '$HOME/../../var/mail' becomes '/var/spool/mail' ''' return os.path.normpath(os.path.realpath(os.path.expandvars(os.path.expanduser(path)))) def prepare_writeable_dir(tree,mode=0777): ''' make sure a directory exists and is writeable ''' # modify the mode to ensure the owner at least # has read/write access to this directory mode |= 0700 # make sure the tree path is always expanded # and normalized and free of symlinks tree = unfrackpath(tree) if not os.path.exists(tree): try: os.makedirs(tree, mode) except (IOError, OSError), e: raise errors.AnsibleError("Could not make dir %s: %s" % (tree, e)) if not os.access(tree, os.W_OK): raise errors.AnsibleError("Cannot write to path %s" % tree) return tree def path_dwim(basedir, given): ''' make relative paths work like folks expect. ''' if given.startswith("/"): return os.path.abspath(given) elif given.startswith("~"): return os.path.abspath(os.path.expanduser(given)) else: if basedir is None: basedir = "." return os.path.abspath(os.path.join(basedir, given)) def path_dwim_relative(original, dirname, source, playbook_base, check=True): ''' find one file in a directory one level up in a dir named dirname relative to current ''' # (used by roles code) basedir = os.path.dirname(original) if os.path.islink(basedir): basedir = unfrackpath(basedir) template2 = os.path.join(basedir, dirname, source) else: template2 = os.path.join(basedir, '..', dirname, source) source2 = path_dwim(basedir, template2) if os.path.exists(source2): return source2 obvious_local_path = path_dwim(playbook_base, source) if os.path.exists(obvious_local_path): return obvious_local_path if check: raise errors.AnsibleError("input file not found at %s or %s" % (source2, obvious_local_path)) return source2 # which does not exist def json_loads(data): ''' parse a JSON string and return a data structure ''' return json.loads(data) def parse_json(raw_data): ''' this version for module return data only ''' orig_data = raw_data # ignore stuff like tcgetattr spewage or other warnings data = filter_leading_non_json_lines(raw_data) try: return json.loads(data) except: # not JSON, but try "Baby JSON" which allows many of our modules to not # require JSON and makes writing modules in bash much simpler results = {} try: tokens = shlex.split(data) except: print "failed to parse json: "+ data raise for t in tokens: if "=" not in t: raise errors.AnsibleError("failed to parse: %s" % orig_data) (key,value) = t.split("=", 1) if key == 'changed' or 'failed': if value.lower() in [ 'true', '1' ]: value = True elif value.lower() in [ 'false', '0' ]: value = False if key == 'rc': value = int(value) results[key] = value if len(results.keys()) == 0: return { "failed" : True, "parsed" : False, "msg" : orig_data } return results def smush_braces(data): ''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed weird by key=value code ''' while '{{ ' in data: data = data.replace('{{ ', '{{') while ' }}' in data: data = data.replace(' }}', '}}') return data def smush_ds(data): # things like key={{ foo }} are not handled by shlex.split well, so preprocess any YAML we load # so we do not have to call smush elsewhere if type(data) == list: return [ smush_ds(x) for x in data ] elif type(data) == dict: for (k,v) in data.items(): data[k] = smush_ds(v) return data elif isinstance(data, basestring): return smush_braces(data) else: return data def parse_yaml(data, path_hint=None): ''' convert a yaml string to a data structure. Also supports JSON, ssssssh!!!''' stripped_data = data.lstrip() loaded = None if stripped_data.startswith("{") or stripped_data.startswith("["): # since the line starts with { or [ we can infer this is a JSON document. try: loaded = json.loads(data) except ValueError, ve: if path_hint: raise errors.AnsibleError(path_hint + ": " + str(ve)) else: raise errors.AnsibleError(str(ve)) else: # else this is pretty sure to be a YAML document loaded = yaml.safe_load(data) return smush_ds(loaded) def process_common_errors(msg, probline, column): replaced = probline.replace(" ","") if ":{{" in replaced and "}}" in replaced: msg = msg + """ This one looks easy to fix. YAML thought it was looking for the start of a hash/dictionary and was confused to see a second "{". Most likely this was meant to be an ansible template evaluation instead, so we have to give the parser a small hint that we wanted a string instead. The solution here is to just quote the entire value. For instance, if the original line was: app_path: {{ base_path }}/foo It should be written as: app_path: "{{ base_path }}/foo" """ return msg elif len(probline) and len(probline) > 1 and len(probline) > column and probline[column] == ":" and probline.count(':') > 1: msg = msg + """ This one looks easy to fix. There seems to be an extra unquoted colon in the line and this is confusing the parser. It was only expecting to find one free colon. The solution is just add some quotes around the colon, or quote the entire line after the first colon. For instance, if the original line was: copy: src=file.txt dest=/path/filename:with_colon.txt It can be written as: copy: src=file.txt dest='/path/filename:with_colon.txt' Or: copy: 'src=file.txt dest=/path/filename:with_colon.txt' """ return msg else: parts = probline.split(":") if len(parts) > 1: middle = parts[1].strip() match = False unbalanced = False if middle.startswith("'") and not middle.endswith("'"): match = True elif middle.startswith('"') and not middle.endswith('"'): match = True if len(middle) > 0 and middle[0] in [ '"', "'" ] and middle[-1] in [ '"', "'" ] and probline.count("'") > 2 or probline.count('"') > 2: unbalanced = True if match: msg = msg + """ This one looks easy to fix. It seems that there is a value started with a quote, and the YAML parser is expecting to see the line ended with the same kind of quote. For instance: when: "ok" in result.stdout Could be written as: when: '"ok" in result.stdout' or equivalently: when: "'ok' in result.stdout" """ return msg if unbalanced: msg = msg + """ We could be wrong, but this one looks like it might be an issue with unbalanced quotes. If starting a value with a quote, make sure the line ends with the same set of quotes. For instance this arbitrary example: foo: "bad" "wolf" Could be written as: foo: '"bad" "wolf"' """ return msg return msg def process_yaml_error(exc, data, path=None, show_content=True): if hasattr(exc, 'problem_mark'): mark = exc.problem_mark if show_content: if mark.line -1 >= 0: before_probline = data.split("\n")[mark.line-1] else: before_probline = '' probline = data.split("\n")[mark.line] arrow = " " * mark.column + "^" msg = """Syntax Error while loading YAML script, %s Note: The error may actually appear before this position: line %s, column %s %s %s %s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow) unquoted_var = None if '{{' in probline and '}}' in probline: if '"{{' not in probline or "'{{" not in probline: unquoted_var = True msg = process_common_errors(msg, probline, mark.column) if not unquoted_var: msg = process_common_errors(msg, probline, mark.column) else: msg = msg + """ We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" """ msg = process_common_errors(msg, probline, mark.column) else: # most likely displaying a file with sensitive content, # so don't show any of the actual lines of yaml just the # line number itself msg = """Syntax error while loading YAML script, %s The error appears to have been on line %s, column %s, but may actually be before there depending on the exact syntax problem. """ % (path, mark.line + 1, mark.column + 1) else: # No problem markers means we have to throw a generic # "stuff messed up" type message. Sry bud. if path: msg = "Could not parse YAML. Check over %s again." % path else: msg = "Could not parse YAML." raise errors.AnsibleYAMLValidationFailed(msg) def parse_yaml_from_file(path, vault_password=None): ''' convert a yaml file to a data structure ''' data = None show_content = True try: data = open(path).read() except IOError: raise errors.AnsibleError("file could not read: %s" % path) vault = VaultLib(password=vault_password) if vault.is_encrypted(data): data = vault.decrypt(data) show_content = False try: return parse_yaml(data, path_hint=path) except yaml.YAMLError, exc: process_yaml_error(exc, data, path, show_content) def parse_kv(args): ''' convert a string of key/value items to a dict ''' options = {} if args is not None: # attempting to split a unicode here does bad things args = args.encode('utf-8') try: vargs = shlex.split(args, posix=True) except ValueError, ve: if 'no closing quotation' in str(ve).lower(): raise errors.AnsibleError("error parsing argument string, try quoting the entire line.") else: raise vargs = [x.decode('utf-8') for x in vargs] for x in vargs: if "=" in x: k, v = x.split("=",1) options[k]=v return options def merge_hash(a, b): ''' recursively merges hash b into a keys from b take precedence over keys from a ''' result = copy.deepcopy(a) # next, iterate over b keys and values for k, v in b.iteritems(): # if there's already such key in a # and that key contains dict if k in result and isinstance(result[k], dict): # merge those dicts recursively result[k] = merge_hash(a[k], v) else: # otherwise, just copy a value from b to a result[k] = v return result def md5s(data): ''' Return MD5 hex digest of data. ''' digest = _md5() try: digest.update(data) except UnicodeEncodeError: digest.update(data.encode('utf-8')) return digest.hexdigest() def md5(filename): ''' Return MD5 hex digest of local file, or None if file is not present. ''' if not os.path.exists(filename): return None digest = _md5() blocksize = 64 * 1024 try: infile = open(filename, 'rb') block = infile.read(blocksize) while block: digest.update(block) block = infile.read(blocksize) infile.close() except IOError, e: raise errors.AnsibleError("error while accessing the file %s, error was: %s" % (filename, e)) return digest.hexdigest() def default(value, function): ''' syntactic sugar around lazy evaluation of defaults ''' if value is None: return function() return value def _gitinfo(): ''' returns a string containing git branch, commit id and commit date ''' result = None repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git') if os.path.exists(repo_path): # Check if the .git is a file. If it is a file, it means that we are in a submodule structure. if os.path.isfile(repo_path): try: gitdir = yaml.safe_load(open(repo_path)).get('gitdir') # There is a posibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path.split('.git')[0], gitdir) except (IOError, AttributeError): return '' f = open(os.path.join(repo_path, "HEAD")) branch = f.readline().split('/')[-1].rstrip("\n") f.close() branch_path = os.path.join(repo_path, "refs", "heads", branch) if os.path.exists(branch_path): f = open(branch_path) commit = f.readline()[:10] f.close() date = time.localtime(os.stat(branch_path).st_mtime) if time.daylight == 0: offset = time.timezone else: offset = time.altzone result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit, time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36) else: result = '' return result def version(prog): result = "{0} {1}".format(prog, __version__) gitinfo = _gitinfo() if gitinfo: result = result + " {0}".format(gitinfo) return result def getch(): ''' read in a single character ''' fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch def sanitize_output(str): ''' strips private info out of a string ''' private_keys = ['password', 'login_password'] filter_re = [ # filter out things like user:pass@foo/whatever # and http://username:pass@wherever/foo re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'), ] parts = str.split() output = '' for part in parts: try: (k,v) = part.split('=', 1) if k in private_keys: output += " %s=VALUE_HIDDEN" % k else: found = False for filter in filter_re: m = filter.match(v) if m: d = m.groupdict() output += " %s=%s" % (k, d['before'] + "********" + d['after']) found = True break if not found: output += " %s" % part except: output += " %s" % part return output.strip() #################################################################### # option handling code for /usr/bin/ansible and ansible-playbook # below this line class SortedOptParser(optparse.OptionParser): '''Optparser which sorts the options by opt before outputting --help''' def format_help(self, formatter=None): self.option_list.sort(key=operator.methodcaller('get_opt_string')) return optparse.OptionParser.format_help(self, formatter=None) def increment_debug(option, opt, value, parser): global VERBOSITY VERBOSITY += 1 def base_parser(constants=C, usage="", output_opts=False, runas_opts=False, async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False): ''' create an options parser for any ansible script ''' parser = SortedOptParser(usage, version=version("%prog")) parser.add_option('-v','--verbose', default=False, action="callback", callback=increment_debug, help="verbose mode (-vvv for more, -vvvv to enable connection debugging)") parser.add_option('-f','--forks', dest='forks', default=constants.DEFAULT_FORKS, type='int', help="specify number of parallel processes to use (default=%s)" % constants.DEFAULT_FORKS) parser.add_option('-i', '--inventory-file', dest='inventory', help="specify inventory host file (default=%s)" % constants.DEFAULT_HOST_LIST, default=constants.DEFAULT_HOST_LIST) parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true', help='ask for SSH password') parser.add_option('--private-key', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file', help='use this file to authenticate the connection') parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true', help='ask for sudo password') parser.add_option('--ask-su-pass', default=False, dest='ask_su_pass', action='store_true', help='ask for su password') parser.add_option('--ask-vault-pass', default=False, dest='ask_vault_pass', action='store_true', help='ask for vault password') parser.add_option('--vault-password-file', default=None, dest='vault_password_file', help="vault password file") parser.add_option('--list-hosts', dest='listhosts', action='store_true', help='outputs a list of matching hosts; does not execute anything else') parser.add_option('-M', '--module-path', dest='module_path', help="specify path(s) to module library (default=%s)" % constants.DEFAULT_MODULE_PATH, default=None) if subset_opts: parser.add_option('-l', '--limit', default=constants.DEFAULT_SUBSET, dest='subset', help='further limit selected hosts to an additional pattern') parser.add_option('-T', '--timeout', default=constants.DEFAULT_TIMEOUT, type='int', dest='timeout', help="override the SSH timeout in seconds (default=%s)" % constants.DEFAULT_TIMEOUT) if output_opts: parser.add_option('-o', '--one-line', dest='one_line', action='store_true', help='condense output') parser.add_option('-t', '--tree', dest='tree', default=None, help='log output to this directory') if runas_opts: parser.add_option("-s", "--sudo", default=constants.DEFAULT_SUDO, action="store_true", dest='sudo', help="run operations with sudo (nopasswd)") parser.add_option('-U', '--sudo-user', dest='sudo_user', default=None, help='desired sudo user (default=root)') # Can't default to root because we need to detect when this option was given parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER, dest='remote_user', help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER) parser.add_option('-S', '--su', default=constants.DEFAULT_SU, action='store_true', help='run operations with su') parser.add_option('-R', '--su-user', help='run operations with su as this ' 'user (default=%s)' % constants.DEFAULT_SU_USER) if connect_opts: parser.add_option('-c', '--connection', dest='connection', default=C.DEFAULT_TRANSPORT, help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT) if async_opts: parser.add_option('-P', '--poll', default=constants.DEFAULT_POLL_INTERVAL, type='int', dest='poll_interval', help="set the poll interval if using -B (default=%s)" % constants.DEFAULT_POLL_INTERVAL) parser.add_option('-B', '--background', dest='seconds', type='int', default=0, help='run asynchronously, failing after X seconds (default=N/A)') if check_opts: parser.add_option("-C", "--check", default=False, dest='check', action='store_true', help="don't make any changes; instead, try to predict some of the changes that may occur" ) if diff_opts: parser.add_option("-D", "--diff", default=False, dest='diff', action='store_true', help="when changing (small) files and templates, show the differences in those files; works great with --check" ) return parser def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False): vault_pass = None new_vault_pass = None if ask_vault_pass: vault_pass = getpass.getpass(prompt="Vault password: ") if ask_vault_pass and confirm_vault: vault_pass2 = getpass.getpass(prompt="Confirm Vault password: ") if vault_pass != vault_pass2: raise errors.AnsibleError("Passwords do not match") if ask_new_vault_pass: new_vault_pass = getpass.getpass(prompt="New Vault password: ") if ask_new_vault_pass and confirm_new: new_vault_pass2 = getpass.getpass(prompt="Confirm New Vault password: ") if new_vault_pass != new_vault_pass2: raise errors.AnsibleError("Passwords do not match") # enforce no newline chars at the end of passwords if vault_pass: vault_pass = vault_pass.strip() if new_vault_pass: new_vault_pass = new_vault_pass.strip() return vault_pass, new_vault_pass def ask_passwords(ask_pass=False, ask_sudo_pass=False, ask_su_pass=False, ask_vault_pass=False): sshpass = None sudopass = None su_pass = None vault_pass = None sudo_prompt = "sudo password: " su_prompt = "su password: " if ask_pass: sshpass = getpass.getpass(prompt="SSH password: ") sudo_prompt = "sudo password [defaults to SSH password]: " if ask_sudo_pass: sudopass = getpass.getpass(prompt=sudo_prompt) if ask_pass and sudopass == '': sudopass = sshpass if ask_su_pass: su_pass = getpass.getpass(prompt=su_prompt) if ask_vault_pass: vault_pass = getpass.getpass(prompt="Vault password: ") return (sshpass, sudopass, su_pass, vault_pass) def do_encrypt(result, encrypt, salt_size=None, salt=None): if PASSLIB_AVAILABLE: try: crypt = getattr(passlib.hash, encrypt) except: raise errors.AnsibleError("passlib does not support '%s' algorithm" % encrypt) if salt_size: result = crypt.encrypt(result, salt_size=salt_size) elif salt: result = crypt.encrypt(result, salt=salt) else: result = crypt.encrypt(result) else: raise errors.AnsibleError("passlib must be installed to encrypt vars_prompt values") return result def last_non_blank_line(buf): all_lines = buf.splitlines() all_lines.reverse() for line in all_lines: if (len(line) > 0): return line # shouldn't occur unless there's no output return "" def filter_leading_non_json_lines(buf): ''' used to avoid random output from SSH at the top of JSON output, like messages from tcagetattr, or where dropbear spews MOTD on every single command (which is nuts). need to filter anything which starts not with '{', '[', ', '=' or is an empty line. filter only leading lines since multiline JSON is valid. ''' kv_regex = re.compile(r'.*\w+=\w+.*') filtered_lines = StringIO.StringIO() stop_filtering = False for line in buf.splitlines(): if stop_filtering or kv_regex.match(line) or line.startswith('{') or line.startswith('['): stop_filtering = True filtered_lines.write(line + '\n') return filtered_lines.getvalue() def boolean(value): val = str(value) if val.lower() in [ "true", "t", "y", "1", "yes" ]: return True else: return False def make_sudo_cmd(sudo_user, executable, cmd): """ helper function for connection plugins to create sudo commands """ # Rather than detect if sudo wants a password this time, -k makes # sudo always ask for a password if one is required. # Passing a quoted compound command to sudo (or sudo -s) # directly doesn't work, so we shellquote it with pipes.quote() # and pass the quoted string to the user's shell. We loop reading # output until we see the randomly-generated sudo prompt set with # the -p option. randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32)) prompt = '[sudo via ansible, key=%s] password: ' % randbits success_key = 'SUDO-SUCCESS-%s' % randbits sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % ( C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS, prompt, sudo_user, executable or '$SHELL', pipes.quote('echo %s; %s' % (success_key, cmd))) return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key) def make_su_cmd(su_user, executable, cmd): """ Helper function for connection plugins to create direct su commands """ # TODO: work on this function randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32)) prompt = 'assword: ' success_key = 'SUDO-SUCCESS-%s' % randbits sudocmd = '%s %s %s %s -c %s' % ( C.DEFAULT_SU_EXE, C.DEFAULT_SU_FLAGS, su_user, executable or '$SHELL', pipes.quote('echo %s; %s' % (success_key, cmd)) ) return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key) _TO_UNICODE_TYPES = (unicode, type(None)) def to_unicode(value): if isinstance(value, _TO_UNICODE_TYPES): return value return value.decode("utf-8") def get_diff(diff): # called by --diff usage in playbook and runner via callbacks # include names in diffs 'before' and 'after' and do diff -U 10 try: with warnings.catch_warnings(): warnings.simplefilter('ignore') ret = [] if 'dst_binary' in diff: ret.append("diff skipped: destination file appears to be binary\n") if 'src_binary' in diff: ret.append("diff skipped: source file appears to be binary\n") if 'dst_larger' in diff: ret.append("diff skipped: destination file size is greater than %d\n" % diff['dst_larger']) if 'src_larger' in diff: ret.append("diff skipped: source file size is greater than %d\n" % diff['src_larger']) if 'before' in diff and 'after' in diff: if 'before_header' in diff: before_header = "before: %s" % diff['before_header'] else: before_header = 'before' if 'after_header' in diff: after_header = "after: %s" % diff['after_header'] else: after_header = 'after' differ = difflib.unified_diff(to_unicode(diff['before']).splitlines(True), to_unicode(diff['after']).splitlines(True), before_header, after_header, '', '', 10) for line in list(differ): ret.append(line) return u"".join(ret) except UnicodeDecodeError: return ">> the files are different, but the diff library cannot compare unicode strings" def is_list_of_strings(items): for x in items: if not isinstance(x, basestring): return False return True def list_union(a, b): result = [] for x in a: if x not in result: result.append(x) for x in b: if x not in result: result.append(x) return result def list_intersection(a, b): result = [] for x in a: if x in b and x not in result: result.append(x) return result def safe_eval(expr, locals={}, include_exceptions=False): ''' this is intended for allowing things like: with_items: a_list_variable where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained) Based on: http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe ''' # this is the whitelist of AST nodes we are going to # allow in the evaluation. Any node type other than # those listed here will raise an exception in our custom # visitor class defined below. SAFE_NODES = set( ( ast.Expression, ast.Compare, ast.Str, ast.List, ast.Tuple, ast.Dict, ast.Call, ast.Load, ast.BinOp, ast.UnaryOp, ast.Num, ast.Name, ast.Add, ast.Sub, ast.Mult, ast.Div, ) ) # AST node types were expanded after 2.6 if not sys.version.startswith('2.6'): SAFE_NODES.union( set( (ast.Set,) ) ) # builtin functions that are not safe to call INVALID_CALLS = ( 'classmethod', 'compile', 'delattr', 'eval', 'execfile', 'file', 'filter', 'help', 'input', 'object', 'open', 'raw_input', 'reduce', 'reload', 'repr', 'setattr', 'staticmethod', 'super', 'type', ) class CleansingNodeVisitor(ast.NodeVisitor): def generic_visit(self, node): if type(node) not in SAFE_NODES: #raise Exception("invalid expression (%s) type=%s" % (expr, type(node))) raise Exception("invalid expression (%s)" % expr) super(CleansingNodeVisitor, self).generic_visit(node) def visit_Call(self, call): if call.func.id in INVALID_CALLS: raise Exception("invalid function: %s" % call.func.id) if not isinstance(expr, basestring): # already templated to a datastructure, perhaps? if include_exceptions: return (expr, None) return expr try: parsed_tree = ast.parse(expr, mode='eval') cnv = CleansingNodeVisitor() cnv.visit(parsed_tree) compiled = compile(parsed_tree, expr, 'eval') result = eval(compiled, {}, locals) if include_exceptions: return (result, None) else: return result except SyntaxError, e: # special handling for syntax errors, we just return # the expression string back as-is if include_exceptions: return (expr, None) return expr except Exception, e: if include_exceptions: return (expr, e) return expr def listify_lookup_plugin_terms(terms, basedir, inject): if isinstance(terms, basestring): # someone did: # with_items: alist # OR # with_items: {{ alist }} stripped = terms.strip() if not (stripped.startswith('{') or stripped.startswith('[')) and not stripped.startswith("/") and not stripped.startswith('set(['): # if not already a list, get ready to evaluate with Jinja2 # not sure why the "/" is in above code :) try: new_terms = template.template(basedir, "{{ %s }}" % terms, inject) if isinstance(new_terms, basestring) and "{{" in new_terms: pass else: terms = new_terms except: pass if '{' in terms or '[' in terms: # Jinja2 already evaluated a variable to a list. # Jinja2-ified list needs to be converted back to a real type # TODO: something a bit less heavy than eval return safe_eval(terms) if isinstance(terms, basestring): terms = [ terms ] return terms def combine_vars(a, b): if C.DEFAULT_HASH_BEHAVIOUR == "merge": return merge_hash(a, b) else: return dict(a.items() + b.items()) def random_password(length=20, chars=C.DEFAULT_PASSWORD_CHARS): '''Return a random password string of length containing only chars.''' password = [] while len(password) < length: new_char = os.urandom(1) if new_char in chars: password.append(new_char) return ''.join(password) def before_comment(msg): ''' what's the part of a string before a comment? ''' msg = msg.replace("\#","**NOT_A_COMMENT**") msg = msg.split("#")[0] msg = msg.replace("**NOT_A_COMMENT**","#") return msg
hlieberman/debian-ansible
lib/ansible/utils/__init__.py
Python
gpl-3.0
41,324
[ "VisIt" ]
2892de42246acab4e7603cc410282e18bece06e4b68d1dfd3009f770ba571a6e
# -*- coding: utf-8 -*- """ End-to-end tests for survey feature """ import bok_choy.browser from ...fixtures.course import CourseFixture, XBlockFixtureDesc from ...pages.lms.auto_auth import AutoAuthPage from ...pages.lms.courseware import CoursewarePage from ...pages.lms.course_nav import CourseNavPage from ...pages.lms.ga_survey import SurveyPage from ..ga_helpers import GaccoTestMixin from ..helpers import UniqueCourseTest, load_data_str class SurveyTest(UniqueCourseTest, GaccoTestMixin): """ Tests that the survey functionality works """ def setUp(self): """ Initiailizes the page object and create a test user """ super(SurveyTest, self).setUp() course_fix = CourseFixture( self.course_info['org'], self.course_info['number'], self.course_info['run'], self.course_info['display_name'] ) course_fix.add_children( XBlockFixtureDesc('chapter', 'Test Section').add_children( XBlockFixtureDesc('sequential', 'Test Subsection').add_children( XBlockFixtureDesc('vertical', 'Test Unit').add_children( XBlockFixtureDesc('html', 'Test HTML', data=load_data_str('ga_survey.html')) ) ) ) ).install() # Auto-auth register for the course AutoAuthPage(self.browser, course_id=self.course_id).visit() # Set window size self.setup_window_size_for_pc() def _visit_survey_page(self): """ Visits survey page """ CoursewarePage(self.browser, self.course_id).visit() self.course_nav = CourseNavPage(self.browser) self.course_nav.go_to_section('Test Section', 'Test Subsection') self.survey_page = SurveyPage(self.browser).wait_for_page() def test_survey_success(self): """ Tests that submitting with valid values is successful """ # Visit survey page self._visit_survey_page() bok_choy.browser.save_screenshot(self.browser, 'test_survey_success__1') self.assertTrue(self.survey_page.is_submit_button_enabled()) # Submit self.survey_page.fill_item('Q1', '1') self.survey_page.fill_item('Q2', '2') self.survey_page.fill_item('Q3', 'yes') self.survey_page.fill_item('Q4', u'あああ') bok_choy.browser.save_screenshot(self.browser, 'test_survey_success__2') self.survey_page.submit() # Verify message bok_choy.browser.save_screenshot(self.browser, 'test_survey_success__3') self.assertIn(u"ご回答ありがとうございました。", self.survey_page.wait_for_messages()) self.assertFalse(self.survey_page.is_submit_button_enabled()) # Visit again self._visit_survey_page() bok_choy.browser.save_screenshot(self.browser, 'test_survey_success__4') self.assertIn(u"このアンケートは既に回答済みです。", self.survey_page.wait_for_messages()) self.assertFalse(self.survey_page.is_submit_button_enabled()) def test_survey_with_empty_item(self): """ Tests that submitting with empty item is not successful """ # Visit survey page self._visit_survey_page() bok_choy.browser.save_screenshot(self.browser, 'test_survey_with_empty_item__1') self.assertTrue(self.survey_page.is_submit_button_enabled()) # Submit self.survey_page.fill_item('Q1', '1') self.survey_page.fill_item('Q2', '2') self.survey_page.fill_item('Q3', 'yes') bok_choy.browser.save_screenshot(self.browser, 'test_survey_with_empty_item__2') self.survey_page.submit() # Verify message bok_choy.browser.save_screenshot(self.browser, 'test_survey_with_empty_item__3') self.assertIn(u"問4 は必須入力です。", self.survey_page.wait_for_messages()) self.assertTrue(self.survey_page.is_submit_button_enabled()) def test_survey_with_over_maxlength_item(self): """ Tests that submitting with over maxlength item is not successful """ # Visit survey page self._visit_survey_page() bok_choy.browser.save_screenshot(self.browser, 'test_survey_with_over_maxlength_item__1') self.assertTrue(self.survey_page.is_submit_button_enabled()) # Submit self.survey_page.fill_item('Q1', '1') self.survey_page.fill_item('Q2', '2') self.survey_page.fill_item('Q3', 'yes') self.survey_page.fill_item('Q4', u'あ' * 1001) bok_choy.browser.save_screenshot(self.browser, 'test_survey_with_over_maxlength_item__2') self.survey_page.submit() # Verify message bok_choy.browser.save_screenshot(self.browser, 'test_survey_with_over_maxlength_item__3') self.assertIn(u"問4 は1000字以下で入力してください。", self.survey_page.wait_for_messages()) self.assertTrue(self.survey_page.is_submit_button_enabled())
nttks/edx-platform
common/test/acceptance/tests/lms/test_ga_survey.py
Python
agpl-3.0
5,069
[ "VisIt" ]
8f2b6ebb24369e936ac9e5b6e764330e5683fba7b16a8cae6e620b1b3f934538
""" This is the StorageElement class. """ import re # # custom duty import time import datetime import copy import errno import threading import sys # # from DIRAC from DIRAC import gLogger, gConfig, siteName from DIRAC.Core.Utilities import DErrno from DIRAC.Core.Utilities.ReturnValues import S_OK, S_ERROR, returnSingleResult from DIRAC.Resources.Storage.StorageFactory import StorageFactory from DIRAC.Core.Utilities.Pfn import pfnparse from DIRAC.Core.Utilities.SiteSEMapping import getSEsForSite from DIRAC.Core.Security.ProxyInfo import getVOfromProxyGroup from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.Core.Utilities.DictCache import DictCache from DIRAC.Resources.Storage.Utilities import checkArgumentFormat from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation from DIRAC.AccountingSystem.Client.DataStoreClient import gDataStoreClient from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers __RCSID__ = "$Id$" class StorageElementCache( object ): def __init__( self ): self.seCache = DictCache() def __call__( self, name, plugins = None, vo = None, hideExceptions = False ): self.seCache.purgeExpired( expiredInSeconds = 60 ) tId = threading.current_thread().ident if not vo: result = getVOfromProxyGroup() if not result['OK']: return vo = result['Value'] argTuple = ( tId, name, plugins, vo ) seObj = self.seCache.get( argTuple ) if not seObj: seObj = StorageElementItem( name, plugins, vo, hideExceptions = hideExceptions ) # Add the StorageElement to the cache for 1/2 hour self.seCache.add( argTuple, 1800, seObj ) return seObj class StorageElementItem( object ): """ .. class:: StorageElement common interface to the grid storage element self.name is the resolved name of the StorageElement i.e CERN-tape self.options is dictionary containing the general options defined in the CS e.g. self.options['Backend] = 'Castor2' self.storages is a list of the stub objects created by StorageFactory for the protocols found in the CS. self.localPlugins is a list of the local protocols that were created by StorageFactory self.remotePlugins is a list of the remote protocols that were created by StorageFactory self.protocolOptions is a list of dictionaries containing the options found in the CS. (should be removed) dynamic method : retransferOnlineFile( lfn ) exists( lfn ) isFile( lfn ) getFile( lfn, localPath = False ) putFile( lfnLocal, sourceSize = 0 ) : {lfn:local} replicateFile( lfn, sourceSize = 0 ) getFileMetadata( lfn ) getFileSize( lfn ) removeFile( lfn ) prestageFile( lfn, lifetime = 86400 ) prestageFileStatus( lfn ) pinFile( lfn, lifetime = 60 * 60 * 24 ) releaseFile( lfn ) isDirectory( lfn ) getDirectoryMetadata( lfn ) getDirectorySize( lfn ) listDirectory( lfn ) removeDirectory( lfn, recursive = False ) createDirectory( lfn ) putDirectory( lfn ) getDirectory( lfn, localPath = False ) """ __deprecatedArguments = ["singleFile", "singleDirectory"] # Arguments that are now useless # Some methods have a different name in the StorageElement and the plugins... # We could avoid this static list in the __getattr__ by checking the storage plugin and so on # but fine... let's not be too smart, otherwise it becomes unreadable :-) __equivalentMethodNames = { "exists" : "exists", "isFile" : "isFile", "getFile" : "getFile", "putFile" : "putFile", "replicateFile" : "putFile", "getFileMetadata" : "getFileMetadata", "getFileSize" : "getFileSize", "removeFile" : "removeFile", "prestageFile" : "prestageFile", "prestageFileStatus" : "prestageFileStatus", "pinFile" : "pinFile", "releaseFile" : "releaseFile", "isDirectory" : "isDirectory", "getDirectoryMetadata" : "getDirectoryMetadata", "getDirectorySize" : "getDirectorySize", "listDirectory" : "listDirectory", "removeDirectory" : "removeDirectory", "createDirectory" : "createDirectory", "putDirectory" : "putDirectory", "getDirectory" : "getDirectory", } # We can set default argument in the __executeFunction which impacts all plugins __defaultsArguments = {"putFile" : {"sourceSize" : 0 }, "getFile": { "localPath": False }, "prestageFile" : { "lifetime" : 86400 }, "pinFile" : { "lifetime" : 60 * 60 * 24 }, "removeDirectory" : { "recursive" : False }, "getDirectory" : { "localPath" : False }, } def __init__( self, name, plugins = None, vo = None, hideExceptions = False ): """ c'tor :param str name: SE name :param list plugins: requested storage plugins :param: vo """ self.methodName = None if vo: self.vo = vo else: result = getVOfromProxyGroup() if not result['OK']: return self.vo = result['Value'] self.opHelper = Operations( vo = self.vo ) # These things will soon have to go as well. 'AccessProtocol.1' is all but flexible. proxiedProtocols = gConfig.getValue( '/LocalSite/StorageElements/ProxyProtocols', "" ).split( ',' ) self.useProxy = ( gConfig.getValue( "/Resources/StorageElements/%s/AccessProtocol.1/Protocol" % name, "UnknownProtocol" ) in proxiedProtocols ) if not self.useProxy: self.useProxy = gConfig.getValue( '/LocalSite/StorageElements/%s/UseProxy' % name, False ) if not self.useProxy: self.useProxy = self.opHelper.getValue( '/Services/StorageElements/%s/UseProxy' % name, False ) self.valid = True if plugins == None: res = StorageFactory( useProxy = self.useProxy, vo = self.vo ).getStorages( name, pluginList = [], hideExceptions = hideExceptions ) else: res = StorageFactory( useProxy = self.useProxy, vo = self.vo ).getStorages( name, pluginList = plugins, hideExceptions = hideExceptions ) if not res['OK']: self.valid = False self.name = name self.errorReason = res['Message'] else: factoryDict = res['Value'] self.name = factoryDict['StorageName'] self.options = factoryDict['StorageOptions'] self.localPlugins = factoryDict['LocalPlugins'] self.remotePlugins = factoryDict['RemotePlugins'] self.storages = factoryDict['StorageObjects'] self.protocolOptions = factoryDict['ProtocolOptions'] self.turlProtocols = factoryDict['TurlProtocols'] for storage in self.storages: storage.setStorageElement( self ) self.log = gLogger.getSubLogger( "SE[%s]" % self.name ) if self.valid: self.useCatalogURL = gConfig.getValue( '/Resources/StorageElements/%s/UseCatalogURL' % self.name, False ) self.log.debug( "useCatalogURL: %s" % self.useCatalogURL ) self.__dmsHelper = DMSHelpers( vo = vo ) # Allow SE to overwrite general operation config accessProto = self.options.get( 'AccessProtocols' ) self.localAccessProtocolList = accessProto if accessProto else self.__dmsHelper.getAccessProtocols() self.log.debug( "localAccessProtocolList %s" % self.localAccessProtocolList ) writeProto = self.options.get( 'WriteProtocols' ) self.localWriteProtocolList = writeProto if writeProto else self.__dmsHelper.getWriteProtocols() self.log.debug( "localWriteProtocolList %s" % self.localWriteProtocolList ) # 'getTransportURL', self.readMethods = [ 'getFile', 'prestageFile', 'prestageFileStatus', 'getDirectory'] self.writeMethods = [ 'retransferOnlineFile', 'putFile', 'replicateFile', 'pinFile', 'releaseFile', 'createDirectory', 'putDirectory' ] self.removeMethods = [ 'removeFile', 'removeDirectory' ] self.checkMethods = [ 'exists', 'getDirectoryMetadata', 'getDirectorySize', 'getFileSize', 'getFileMetadata', 'listDirectory', 'isDirectory', 'isFile', ] self.okMethods = [ 'getLocalProtocols', 'getProtocols', 'getRemoteProtocols', 'storageElementName', 'getStorageParameters', 'getTransportURL', 'isLocalSE' ] self.__fileCatalog = None def dump( self ): """ Dump to the logger a summary of the StorageElement items. """ log = self.log.getSubLogger( 'dump', True ) log.verbose( "Preparing dump for StorageElement %s." % self.name ) if not self.valid: log.debug( "Failed to create StorageElement plugins.", self.errorReason ) return i = 1 outStr = "\n\n============ Options ============\n" for key in sorted( self.options ): outStr = "%s%s: %s\n" % ( outStr, key.ljust( 15 ), self.options[key] ) for storage in self.storages: outStr = "%s============Protocol %s ============\n" % ( outStr, i ) storageParameters = storage.getParameters() for key in sorted( storageParameters ): outStr = "%s%s: %s\n" % ( outStr, key.ljust( 15 ), storageParameters[key] ) i = i + 1 log.verbose( outStr ) ################################################################################################# # # These are the basic get functions for storage configuration # def getStorageElementName( self ): """ SE name getter for backward compatibility """ return S_OK( self.storageElementName() ) def storageElementName( self ): """ SE name getter """ self.log.getSubLogger( 'storageElementName' ).verbose( "The Storage Element name is %s." % self.name ) return self.name def getChecksumType( self ): """ Checksum type getter for backward compatibility """ return S_OK( self.checksumType() ) def checksumType( self ): """ get specific /Resources/StorageElements/<SEName>/ChecksumType option if defined, otherwise global /Resources/StorageElements/ChecksumType """ self.log.getSubLogger( 'checksumType' ).verbose( "get checksum type for %s." % self.name ) return self.options["ChecksumType"].upper() \ if "ChecksumType" in self.options else gConfig.getValue( "/Resources/StorageElements/ChecksumType", "ADLER32" ).upper() def getStatus( self ): """ Return Status of the SE only if the SE is valid It returns an S_OK/S_ERROR structure """ valid = self.isValid() if not valid['OK']: return valid return S_OK( self.status() ) def status( self ): """ Return Status of the SE, a dictionary with: * Read: True (is allowed), False (it is not allowed) * Write: True (is allowed), False (it is not allowed) * Remove: True (is allowed), False (it is not allowed) * Check: True (is allowed), False (it is not allowed). .. note:: Check is always allowed IF Read is allowed (regardless of what set in the Check option of the configuration) * DiskSE: True if TXDY with Y > 0 (defaults to True) * TapeSE: True if TXDY with X > 0 (defaults to False) * TotalCapacityTB: float (-1 if not defined) * DiskCacheTB: float (-1 if not defined) It returns directly the dictionary """ self.log.getSubLogger( 'getStatus' ).verbose( "determining status of %s." % self.name ) retDict = {} if not self.valid: retDict['Read'] = False retDict['Write'] = False retDict['Remove'] = False retDict['Check'] = False retDict['DiskSE'] = False retDict['TapeSE'] = False retDict['TotalCapacityTB'] = -1 retDict['DiskCacheTB'] = -1 return retDict # If nothing is defined in the CS Access is allowed # If something is defined, then it must be set to Active retDict['Read'] = not ( 'ReadAccess' in self.options and self.options['ReadAccess'] not in ( 'Active', 'Degraded' ) ) retDict['Write'] = not ( 'WriteAccess' in self.options and self.options['WriteAccess'] not in ( 'Active', 'Degraded' ) ) retDict['Remove'] = not ( 'RemoveAccess' in self.options and self.options['RemoveAccess'] not in ( 'Active', 'Degraded' ) ) if retDict['Read']: retDict['Check'] = True else: retDict['Check'] = not ( 'CheckAccess' in self.options and self.options['CheckAccess'] not in ( 'Active', 'Degraded' ) ) diskSE = True tapeSE = False if 'SEType' in self.options: # Type should follow the convention TXDY seType = self.options['SEType'] diskSE = re.search( 'D[1-9]', seType ) != None tapeSE = re.search( 'T[1-9]', seType ) != None retDict['DiskSE'] = diskSE retDict['TapeSE'] = tapeSE try: retDict['TotalCapacityTB'] = float( self.options['TotalCapacityTB'] ) except Exception: retDict['TotalCapacityTB'] = -1 try: retDict['DiskCacheTB'] = float( self.options['DiskCacheTB'] ) except Exception: retDict['DiskCacheTB'] = -1 return retDict def isValid( self, operation = None ): """ check CS/RSS statuses for :operation: :param str operation: operation name """ log = self.log.getSubLogger( 'isValid', True ) log.verbose( "Determining if the StorageElement %s is valid for VO %s" % ( self.name, self.vo ) ) if not self.valid: log.debug( "Failed to create StorageElement plugins.", self.errorReason ) return S_ERROR( "SE.isValid: Failed to create StorageElement plugins: %s" % self.errorReason ) # Check if the Storage Element is eligible for the user's VO if 'VO' in self.options and not self.vo in self.options['VO']: log.debug( "StorageElement is not allowed for VO", self.vo ) return S_ERROR( errno.EACCES, "StorageElement.isValid: StorageElement is not allowed for VO" ) log.verbose( "Determining if the StorageElement %s is valid for operation '%s'" % ( self.name, operation ) ) if ( not operation ) or ( operation in self.okMethods ): return S_OK() # Determine whether the StorageElement is valid for checking, reading, writing status = self.status() checking = status[ 'Check' ] reading = status[ 'Read' ] writing = status[ 'Write' ] removing = status[ 'Remove' ] # Determine whether the requested operation can be fulfilled if ( not operation ) and ( not reading ) and ( not writing ) and ( not checking ): log.debug( "Read, write and check access not permitted." ) return S_ERROR( errno.EACCES, "SE.isValid: Read, write and check access not permitted." ) # The supplied operation can be 'Read','Write' or any of the possible StorageElement methods. if ( operation in self.readMethods ) or ( operation.lower() in ( 'read', 'readaccess' ) ): operation = 'ReadAccess' elif operation in self.writeMethods or ( operation.lower() in ( 'write', 'writeaccess' ) ): operation = 'WriteAccess' elif operation in self.removeMethods or ( operation.lower() in ( 'remove', 'removeaccess' ) ): operation = 'RemoveAccess' elif operation in self.checkMethods or ( operation.lower() in ( 'check', 'checkaccess' ) ): operation = 'CheckAccess' else: log.debug( "The supplied operation is not known.", operation ) return S_ERROR( DErrno.ENOMETH , "SE.isValid: The supplied operation is not known." ) log.debug( "check the operation: %s " % operation ) # Check if the operation is valid if operation == 'CheckAccess': if not reading: if not checking: log.debug( "Check access not currently permitted." ) return S_ERROR( errno.EACCES, "SE.isValid: Check access not currently permitted." ) if operation == 'ReadAccess': if not reading: log.debug( "Read access not currently permitted." ) return S_ERROR( errno.EACCES, "SE.isValid: Read access not currently permitted." ) if operation == 'WriteAccess': if not writing: log.debug( "Write access not currently permitted." ) return S_ERROR( errno.EACCES, "SE.isValid: Write access not currently permitted." ) if operation == 'RemoveAccess': if not removing: log.debug( "Remove access not currently permitted." ) return S_ERROR( errno.EACCES, "SE.isValid: Remove access not currently permitted." ) return S_OK() def getPlugins( self ): """ Get the list of all the plugins defined for this Storage Element """ self.log.getSubLogger( 'getPlugins' ).verbose( "Obtaining all plugins of %s." % self.name ) if not self.valid: return S_ERROR( self.errorReason ) allPlugins = self.localPlugins + self.remotePlugins return S_OK( allPlugins ) def getRemotePlugins( self ): """ Get the list of all the remote access protocols defined for this Storage Element """ self.log.getSubLogger( 'getRemotePlugins' ).verbose( "Obtaining remote protocols for %s." % self.name ) if not self.valid: return S_ERROR( self.errorReason ) return S_OK( self.remotePlugins ) def getLocalPlugins( self ): """ Get the list of all the local access protocols defined for this Storage Element """ self.log.getSubLogger( 'getLocalPlugins' ).verbose( "Obtaining local protocols for %s." % self.name ) if not self.valid: return S_ERROR( self.errorReason ) return S_OK( self.localPlugins ) def getStorageParameters( self, plugin = None, protocol = None ): """ Get plugin specific options :param plugin : plugin we are interested in :param protocol: protocol we are interested in Either plugin or protocol can be defined, not both, but at least one of them """ # both set if plugin and protocol: return S_ERROR( errno.EINVAL, "plugin and protocol cannot be set together." ) # both None elif not ( plugin or protocol ): return S_ERROR( errno.EINVAL, "plugin and protocol cannot be None together." ) log = self.log.getSubLogger( 'getStorageParameters' ) reqStr = "plugin %s" % plugin if plugin else "protocol %s" % protocol log.verbose( "Obtaining storage parameters for %s for %s." % ( self.name, reqStr ) ) for storage in self.storages: storageParameters = storage.getParameters() if plugin and storageParameters['PluginName'] == plugin: return S_OK( storageParameters ) elif protocol and storageParameters['Protocol'] == protocol: return S_OK( storageParameters ) errStr = "Requested plugin or protocol not available." log.debug( errStr, "%s for %s" % ( reqStr, self.name ) ) return S_ERROR( errStr ) def __getAllProtocols( self, protoType ): """ Returns the list of all protocols for Input or Output :param proto = InputProtocols or OutputProtocols """ return set( reduce( lambda x, y:x + y, [plugin.protocolParameters[protoType] for plugin in self.storages ] ) ) def _getAllInputProtocols( self ): """ Returns all the protocols supported by the SE for Input """ return self.__getAllProtocols( 'InputProtocols' ) def _getAllOutputProtocols( self ): """ Returns all the protocols supported by the SE for Output """ return self.__getAllProtocols( 'OutputProtocols' ) def generateTransferURLsBetweenSEs(self, lfns, sourceSE, protocols = None): """ This negociate the URLs to be used for third party copy. This is mostly useful for FTS. If protocols is given, it restricts the list of plugins to use :param lfns: list/dict of lfns to generate the URLs :param sourceSE: storageElement instance of the sourceSE :param protocols: ordered protocol restriction list :return:dictionnary Successful/Failed with pair (src, dest) urls """ log = self.log.getSubLogger( 'generateTransferURLsBetweenSEs' ) result = checkArgumentFormat( lfns ) if result['OK']: lfns = result['Value'] else: errStr = "Supplied urls must be string, list of strings or a dictionary." log.debug( errStr ) return S_ERROR( errno.EINVAL, errStr ) # First, find common protocols to use res = self.negociateProtocolWithOtherSE(sourceSE, protocols = protocols) if not res['OK']: return res commonProtocols = res['Value'] # Taking each protocol at the time, we try to generate src and dest URLs for proto in commonProtocols: srcPlugin = None destPlugin = None log.debug("Trying to find plugins for protocol %s"%proto) # Finding the source storage plugin for storagePlugin in sourceSE.storages: log.debug("Testing %s as source plugin" % storagePlugin.pluginName) storageParameters = storagePlugin.getParameters() nativeProtocol = storageParameters['Protocol'] # If the native protocol of the plugin is allowed for read if nativeProtocol in sourceSE.localAccessProtocolList: # If the plugin can generate the protocol we are interested in if proto in storageParameters['OutputProtocols']: log.debug("Selecting it") srcPlugin = storagePlugin break # If we did not find a source plugin, continue if srcPlugin is None : log.debug("Could not find a source plugin for protocol %s"%proto) continue # Finding the destination storage plugin for storagePlugin in self.storages: log.debug("Testing %s as destination plugin" % storagePlugin.pluginName) storageParameters = storagePlugin.getParameters() nativeProtocol = storageParameters['Protocol'] # If the native protocol of the plugin is allowed for write if nativeProtocol in self.localWriteProtocolList: # If the plugin can accept the protocol we are interested in if proto in storageParameters['InputProtocols']: log.debug("Selecting it") destPlugin = storagePlugin break # If we found both a source and destination plugin, we are happy, # otherwise we continue with the next protocol if destPlugin is None: log.debug("Could not find a destination plugin for protocol %s"%proto) srcPlugin = None continue failed = {} successful = {} # Generate the URLs for lfn in lfns: # Source URL first res = srcPlugin.constructURLFromLFN( lfn, withWSUrl = True ) if not res['OK']: errMsg = "Error generating source url: %s"%res['Message'] gLogger.debug("Error generating source url",errMsg) failed[lfn] = errMsg continue srcURL = res['Value'] # Destination URL res = destPlugin.constructURLFromLFN( lfn, withWSUrl = True ) if not res['OK']: errMsg = "Error generating destination url: %s"%res['Message'] gLogger.debug("Error generating destination url",errMsg) failed[lfn] = errMsg continue destURL = res['Value'] successful[lfn] = (srcURL, destURL) return S_OK({'Successful':successful, 'Failed':failed}) return S_ERROR(errno.ENOPROTOOPT, "Could not find a protocol ") def negociateProtocolWithOtherSE( self, sourceSE, protocols = None ): """ Negotiate what protocol could be used for a third party transfer between the sourceSE and ourselves. If protocols is given, the chosen protocol has to be among those :param sourceSE : storageElement instance of the sourceSE :param protocols: ordered protocol restriction list :return: a list protocols that fits the needs, or None """ # No common protocols if this is a proxy storage if self.useProxy: return S_OK( [] ) log = self.log.getSubLogger( 'negociateProtocolWithOtherSE', child = True ) log.debug( "Negociating protocols between %s and %s (protocols %s)" % ( sourceSE.name, self.name, protocols ) ) # Take all the protocols the destination can accept as input destProtocols = self._getAllInputProtocols() log.debug( "Destination input protocols %s" % destProtocols ) # Take all the protocols the source can provide sourceProtocols = sourceSE._getAllOutputProtocols() log.debug( "Source output protocols %s" % sourceProtocols ) commonProtocols = destProtocols & sourceProtocols # If a restriction list is defined # take the intersection, and sort the commonProtocols # based on the protocolList order if protocols: protocolList = list( protocols ) commonProtocols = sorted( commonProtocols & set( protocolList ), key = lambda x : self.__getIndexInList( x, protocolList ) ) log.debug( "Common protocols %s" % commonProtocols ) return S_OK( list( commonProtocols ) ) ################################################################################################# # # These are the basic get functions for lfn manipulation # def __getURLPath( self, url ): """ Get the part of the URL path below the basic storage path. This path must coincide with the LFN of the file in order to be compliant with the DIRAC conventions. """ log = self.log.getSubLogger( '__getURLPath' ) log.verbose( "Getting path from url in %s." % self.name ) if not self.valid: return S_ERROR( self.errorReason ) res = pfnparse( url ) if not res['OK']: return res fullURLPath = '%s/%s' % ( res['Value']['Path'], res['Value']['FileName'] ) # Check all available storages and check whether the url is for that protocol urlPath = '' for storage in self.storages: res = storage.isNativeURL( url ) if res['OK']: if res['Value']: parameters = storage.getParameters() saPath = parameters['Path'] if not saPath: # If the sa path doesn't exist then the url path is the entire string urlPath = fullURLPath else: if re.search( saPath, fullURLPath ): # Remove the sa path from the fullURLPath urlPath = fullURLPath.replace( saPath, '' ) if urlPath: return S_OK( urlPath ) # This should never happen. DANGER!! errStr = "Failed to get the url path for any of the protocols!!" log.debug( errStr ) return S_ERROR( errStr ) def getLFNFromURL( self, urls ): """ Get the LFN from the PFNS . :param lfn : input lfn or lfns (list/dict) """ result = checkArgumentFormat( urls ) if result['OK']: urlDict = result['Value'] else: errStr = "Supplied urls must be string, list of strings or a dictionary." self.log.getSubLogger( 'getLFNFromURL' ).debug( errStr ) return S_ERROR( errno.EINVAL, errStr ) retDict = { "Successful" : {}, "Failed" : {} } for url in urlDict: res = self.__getURLPath( url ) if res["OK"]: retDict["Successful"][url] = res["Value"] else: retDict["Failed"][url] = res["Message"] return S_OK( retDict ) ########################################################################################### # # This is the generic wrapper for file operations # def getURL( self, lfn, protocol = False, replicaDict = None ): """ execute 'getTransportURL' operation. :param str lfn: string, list or dictionary of lfns :param protocol: if no protocol is specified, we will request self.turlProtocols :param replicaDict: optional results from the File Catalog replica query """ self.log.getSubLogger( 'getURL' ).verbose( "Getting accessUrl %s for lfn in %s." % ( "(%s)" % protocol if protocol else "", self.name ) ) if not protocol: # This turlProtocols seems totally useless. # Get ride of it when gfal2 is totally ready # and replace it with the localAccessProtocol list protocols = self.turlProtocols elif isinstance( protocol, list ): protocols = protocol elif isinstance( protocol, basestring ): protocols = [protocol] self.methodName = "getTransportURL" result = self.__executeMethod( lfn, protocols = protocols ) return result def __isLocalSE( self ): """ Test if the Storage Element is local in the current context """ self.log.getSubLogger( 'LocalSE' ).verbose( "Determining whether %s is a local SE." % self.name ) import DIRAC localSEs = getSEsForSite( DIRAC.siteName() )['Value'] if self.name in localSEs: return S_OK( True ) else: return S_OK( False ) def __getFileCatalog( self ): if not self.__fileCatalog: self.__fileCatalog = FileCatalog( vo = self.vo ) return self.__fileCatalog def __generateURLDict( self, lfns, storage, replicaDict = None ): """ Generates a dictionary (url : lfn ), where the url are constructed from the lfn using the constructURLFromLFN method of the storage plugins. :param: lfns : dictionary {lfn:whatever} :returns dictionary {constructed url : lfn} """ log = self.log.getSubLogger( "__generateURLDict" ) log.verbose( "generating url dict for %s lfn in %s." % ( len( lfns ), self.name ) ) if not replicaDict: replicaDict = {} urlDict = {} # url : lfn failed = {} # lfn : string with errors for lfn in lfns: if self.useCatalogURL: # Is this self.name alias proof? url = replicaDict.get( lfn, {} ).get( self.name, '' ) if url: urlDict[url] = lfn continue else: fc = self.__getFileCatalog() result = fc.getReplicas() if not result['OK']: failed[lfn] = result['Message'] url = result['Value']['Successful'].get( lfn, {} ).get( self.name, '' ) if not url: failed[lfn] = 'Failed to get catalog replica' else: # Update the URL according to the current SE description result = returnSingleResult( storage.updateURL( url ) ) if not result['OK']: failed[lfn] = result['Message'] else: urlDict[result['Value']] = lfn else: result = storage.constructURLFromLFN( lfn, withWSUrl = True ) if not result['OK']: errStr = result['Message'] log.debug( errStr, 'for %s' % ( lfn ) ) failed[lfn] = "%s %s" % ( failed[lfn], errStr ) if lfn in failed else errStr else: urlDict[result['Value']] = lfn res = S_OK( {'Successful': urlDict, 'Failed' : failed} ) # res['Failed'] = failed return res @staticmethod def __getIndexInList( x, l ): """ Return the index of the element x in the list l or sys.maxint if it does not exist :param x: element to look for :param l: list to look int :return: the index or sys.maxint """ try: return l.index( x ) except ValueError: return sys.maxint def __filterPlugins( self, methodName, protocols = None, inputProtocol = None ): """ Determine the list of plugins that can be used for a particular action Args: method(str): method to execute protocols(list): specific protocols might be requested inputProtocol(str): in case the method is putFile, this specifies the protocol given as source Returns: list: list of storage plugins """ log = self.log.getSubLogger( '__filterPlugins', child = True ) log.debug( "Filtering plugins for %s (protocol = %s ; inputProtocol = %s)" % ( methodName, protocols, inputProtocol ) ) if isinstance( protocols, basestring ): protocols = [protocols] pluginsToUse = [] potentialProtocols = [] allowedProtocols = [] if methodName in self.readMethods + self.checkMethods: allowedProtocols = self.localAccessProtocolList elif methodName in self.removeMethods + self.writeMethods : allowedProtocols = self.localWriteProtocolList else: # OK methods # If a protocol or protocol list is specified, we only use the plugins that # can generate such protocol # otherwise we return them all if protocols: setProtocol = set( protocols ) for plugin in self.storages: if set( plugin.protocolParameters.get( "OutputProtocols", [] ) ) & setProtocol: log.debug( "Plugin %s can generate compatible protocol" % plugin.pluginName ) pluginsToUse.append( plugin ) else: pluginsToUse = self.storages # The closest list for "OK" methods is the AccessProtocol preference, so we sort based on that pluginsToUse.sort( key = lambda x: self.__getIndexInList( x.protocolParameters['Protocol'] , self.localAccessProtocolList ) ) log.debug( "Plugins to be used for %s: %s" % ( methodName, [p.pluginName for p in pluginsToUse] ) ) return pluginsToUse log.debug( "Allowed protocol: %s" % allowedProtocols ) # if a list of protocol is specified, take it into account if protocols: potentialProtocols = list( set( allowedProtocols ) & set( protocols ) ) else: potentialProtocols = allowedProtocols log.debug( 'Potential protocols %s' % potentialProtocols ) localSE = self.__isLocalSE()['Value'] for plugin in self.storages: # Determine whether to use this storage object pluginParameters = plugin.getParameters() pluginName = pluginParameters.get( 'PluginName' ) if not pluginParameters: log.debug( "Failed to get storage parameters.", "%s %s" % ( self.name, pluginName ) ) continue if not ( pluginName in self.remotePlugins ) and not localSE and not pluginName == "Proxy": # If the SE is not local then we can't use local protocols log.debug( "Local protocol not appropriate for remote use: %s." % pluginName ) continue if pluginParameters['Protocol'] not in potentialProtocols: log.debug( "Plugin %s not allowed for %s." % ( pluginName, methodName ) ) continue # If we are attempting a putFile and we know the inputProtocol if methodName == 'putFile' and inputProtocol: if inputProtocol not in pluginParameters['InputProtocols']: log.debug( "Plugin %s not appropriate for %s protocol as input." % ( pluginName, inputProtocol ) ) continue pluginsToUse.append( plugin ) # sort the plugins according to the lists in the CS pluginsToUse.sort( key = lambda x: self.__getIndexInList( x.protocolParameters['Protocol'] , allowedProtocols ) ) log.debug( "Plugins to be used for %s: %s" % ( methodName, [p.pluginName for p in pluginsToUse] ) ) return pluginsToUse def __executeMethod( self, lfn, *args, **kwargs ): """ Forward the call to each storage in turn until one works. The method to be executed is stored in self.methodName :param lfn : string, list or dictionary :param *args : variable amount of non-keyword arguments. SHOULD BE EMPTY :param **kwargs : keyword arguments :returns S_OK( { 'Failed': {lfn : reason} , 'Successful': {lfn : value} } ) The Failed dict contains the lfn only if the operation failed on all the storages The Successful dict contains the value returned by the successful storages. A special kwargs is 'inputProtocol', which can be specified for putFile. It describes the protocol used as source protocol, since there is in principle only one. """ removedArgs = {} log = self.log.getSubLogger( '__executeMethod' ) log.verbose( "preparing the execution of %s" % ( self.methodName ) ) # args should normaly be empty to avoid problem... if len( args ): log.verbose( "args should be empty!%s" % args ) # because there is normally only one kw argument, I can move it from args to kwargs methDefaultArgs = StorageElementItem.__defaultsArguments.get( self.methodName, {} ).keys() if len( methDefaultArgs ): kwargs[methDefaultArgs[0] ] = args[0] args = args[1:] log.verbose( "put it in kwargs, but dirty and might be dangerous!args %s kwargs %s" % ( args, kwargs ) ) # We check the deprecated arguments for depArg in StorageElementItem.__deprecatedArguments: if depArg in kwargs: log.verbose( "%s is not an allowed argument anymore. Please change your code!" % depArg ) removedArgs[depArg] = kwargs[depArg] del kwargs[depArg] # Set default argument if any methDefaultArgs = StorageElementItem.__defaultsArguments.get( self.methodName, {} ) for argName in methDefaultArgs: if argName not in kwargs: log.debug( "default argument %s for %s not present.\ Setting value %s." % ( argName, self.methodName, methDefaultArgs[argName] ) ) kwargs[argName] = methDefaultArgs[argName] res = checkArgumentFormat( lfn ) if not res['OK']: errStr = "Supplied lfns must be string, list of strings or a dictionary." log.debug( errStr ) return res lfnDict = res['Value'] log.verbose( "Attempting to perform '%s' operation with %s lfns." % ( self.methodName, len( lfnDict ) ) ) res = self.isValid( operation = self.methodName ) if not res['OK']: return res else: if not self.valid: return S_ERROR( self.errorReason ) # In case executing putFile, we can assume that all the source urls # are from the same protocol. This optional parameter, if defined # can be used to ignore some storage plugins and thus save time # and avoid fake failures showing in the accounting inputProtocol = kwargs.pop( 'inputProtocol', None ) successful = {} failed = {} filteredPlugins = self.__filterPlugins( self.methodName, kwargs.get( 'protocols' ), inputProtocol ) if not filteredPlugins: return S_ERROR( errno.EPROTONOSUPPORT, "No storage plugins matching the requirements\ (operation %s protocols %s inputProtocol %s)"\ % ( self.methodName, kwargs.get( 'protocols' ), inputProtocol ) ) # Try all of the storages one by one for storage in filteredPlugins: # Determine whether to use this storage object storageParameters = storage.getParameters() pluginName = storageParameters['PluginName'] if not lfnDict: log.debug( "No lfns to be attempted for %s protocol." % pluginName ) continue log.verbose( "Generating %s protocol URLs for %s." % ( len( lfnDict ), pluginName ) ) replicaDict = kwargs.pop( 'replicaDict', {} ) if storage.pluginName != "Proxy": res = self.__generateURLDict( lfnDict, storage, replicaDict = replicaDict ) urlDict = res['Value']['Successful'] # url : lfn failed.update( res['Value']['Failed'] ) else: urlDict = dict( [ ( lfn, lfn ) for lfn in lfnDict ] ) if not len( urlDict ): log.verbose( "__executeMethod No urls generated for protocol %s." % pluginName ) else: log.verbose( "Attempting to perform '%s' for %s physical files" % ( self.methodName, len( urlDict ) ) ) fcn = None if hasattr( storage, self.methodName ) and callable( getattr( storage, self.methodName ) ): fcn = getattr( storage, self.methodName ) if not fcn: return S_ERROR( DErrno.ENOMETH, "SE.__executeMethod: unable to invoke %s, it isn't a member function of storage" ) urlsToUse = {} # url : the value of the lfn dictionary for the lfn of this url for url in urlDict: urlsToUse[url] = lfnDict[urlDict[url]] startDate = datetime.datetime.utcnow() startTime = time.time() res = fcn( urlsToUse, *args, **kwargs ) elapsedTime = time.time() - startTime self.addAccountingOperation( urlsToUse, startDate, elapsedTime, storageParameters, res ) if not res['OK']: errStr = "Completely failed to perform %s." % self.methodName log.debug( errStr, 'with plugin %s: %s' % ( pluginName, res['Message'] ) ) for lfn in urlDict.values(): if lfn not in failed: failed[lfn] = '' failed[lfn] = "%s %s" % ( failed[lfn], res['Message'] ) if failed[lfn] else res['Message'] else: for url, lfn in urlDict.items(): if url not in res['Value']['Successful']: if lfn not in failed: failed[lfn] = '' if url in res['Value']['Failed']: self.log.debug( res['Value']['Failed'][url] ) failed[lfn] = "%s %s" % ( failed[lfn], res['Value']['Failed'][url] ) if failed[lfn] else res['Value']['Failed'][url] else: errStr = 'No error returned from plug-in' failed[lfn] = "%s %s" % ( failed[lfn], errStr ) if failed[lfn] else errStr else: successful[lfn] = res['Value']['Successful'][url] if lfn in failed: failed.pop( lfn ) lfnDict.pop( lfn ) gDataStoreClient.commit() return S_OK( { 'Failed': failed, 'Successful': successful } ) def __getattr__( self, name ): """ Forwards the equivalent Storage calls to __executeMethod""" # We take either the equivalent name, or the name itself self.methodName = StorageElementItem.__equivalentMethodNames.get( name, None ) if self.methodName: return self.__executeMethod raise AttributeError( "StorageElement does not have a method '%s'" % name ) def addAccountingOperation( self, lfns, startDate, elapsedTime, storageParameters, callRes ): """ Generates a DataOperation accounting if needs to be, and adds it to the DataStore client cache :param lfns : list of lfns on which we attempted the operation :param startDate : datetime, start of the operation :param elapsedTime : time (seconds) the operation took :param storageParameters : the parameters of the plugins used to perform the operation :param callRes : the return of the method call, S_OK or S_ERROR The operation is generated with the OperationType "se.methodName" The TransferSize and TransferTotal for directory methods actually take into account the files inside the directory, and not the amount of directory given as parameter """ if self.methodName not in ( self.readMethods + self.writeMethods + self.removeMethods ): return baseAccountingDict = {} baseAccountingDict['OperationType'] = 'se.%s' % self.methodName baseAccountingDict['User'] = getProxyInfo().get( 'Value', {} ).get( 'username', 'unknown' ) baseAccountingDict['RegistrationTime'] = 0.0 baseAccountingDict['RegistrationOK'] = 0 baseAccountingDict['RegistrationTotal'] = 0 # if it is a get method, then source and destination of the transfer should be inverted if self.methodName == 'getFile': baseAccountingDict['Destination'] = siteName() baseAccountingDict[ 'Source'] = self.name else: baseAccountingDict['Destination'] = self.name baseAccountingDict['Source'] = siteName() baseAccountingDict['TransferTotal'] = 0 baseAccountingDict['TransferOK'] = 0 baseAccountingDict['TransferSize'] = 0 baseAccountingDict['TransferTime'] = 0.0 baseAccountingDict['FinalStatus'] = 'Successful' oDataOperation = DataOperation() oDataOperation.setValuesFromDict( baseAccountingDict ) oDataOperation.setStartTime( startDate ) oDataOperation.setEndTime( startDate + datetime.timedelta( seconds = elapsedTime ) ) oDataOperation.setValueByKey( 'TransferTime', elapsedTime ) oDataOperation.setValueByKey( 'Protocol', storageParameters.get( 'Protocol', 'unknown' ) ) if not callRes['OK']: # Everything failed oDataOperation.setValueByKey( 'TransferTotal', len( lfns ) ) oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) else: succ = callRes.get( 'Value', {} ).get( 'Successful', {} ) failed = callRes.get( 'Value', {} ).get( 'Failed', {} ) totalSize = 0 # We don't take len(lfns) in order to make two # separate entries in case of few failures totalSucc = len( succ ) if self.methodName in ( 'putFile', 'getFile' ): # putFile and getFile return for each entry # in the successful dir the size of the corresponding file totalSize = sum( succ.values() ) elif self.methodName in ( 'putDirectory', 'getDirectory' ): # putDirectory and getDirectory return for each dir name # a dictionnary with the keys 'Files' and 'Size' totalSize = sum( val.get( 'Size', 0 ) for val in succ.values() if isinstance( val, dict ) ) totalSucc = sum( val.get( 'Files', 0 ) for val in succ.values() if isinstance( val, dict ) ) oDataOperation.setValueByKey( 'TransferOK', len( succ ) ) oDataOperation.setValueByKey( 'TransferSize', totalSize ) oDataOperation.setValueByKey( 'TransferTotal', totalSucc ) oDataOperation.setValueByKey( 'TransferOK', totalSucc ) if callRes['Value']['Failed']: oDataOperationFailed = copy.deepcopy( oDataOperation ) oDataOperationFailed.setValueByKey( 'TransferTotal', len( failed ) ) oDataOperationFailed.setValueByKey( 'TransferOK', 0 ) oDataOperationFailed.setValueByKey( 'TransferSize', 0 ) oDataOperationFailed.setValueByKey( 'FinalStatus', 'Failed' ) accRes = gDataStoreClient.addRegister( oDataOperationFailed ) if not accRes['OK']: self.log.error( "Could not send failed accounting report", accRes['Message'] ) accRes = gDataStoreClient.addRegister( oDataOperation ) if not accRes['OK']: self.log.error( "Could not send accounting report", accRes['Message'] ) StorageElement = StorageElementCache()
Andrew-McNab-UK/DIRAC
Resources/Storage/StorageElement.py
Python
gpl-3.0
46,988
[ "DIRAC" ]
48d65861d10179ca3995cccd9aecc40adcb5a4528baab9858f9f828afb4984de
#----------------------------------- # MAL Bot Configuration #----------------------------------- VERSION = '0.7' USER_AGENT = 'myanimelist_bot v' + VERSION + ' by /u/linkian209' USERNAME = '' PASSWORD = '' MAL_UN = b'' MAL_PW = b'' MIN_ACCEPTABLE_CLOSENESS = .8 FOOTER = '^^^This ^^^comment ^^^was ^^^automatically ^^^created ^^^by ^^^myanimelist_bot ^^^v' + VERSION + '. ^^^Do ^^^not ^^^reply, ^^^I ^^^am ^^^a ^^^bot. ^^^For ^^^feedback ^^^and ^^^bug ^^^reports, ^^^visit ^^^/r/myanimelist_bot. ^^^どうもありがとございます!'
linkian209/MAL-Bot
mal_bot_skel.py
Python
mit
541
[ "VisIt" ]
14653628cf05bf4de13ddbbec3760c6f245e557a13a0aec1cbae28e28401cc18
# -*- coding: utf-8 -*- { '# selected': '# được lựa chọn', "'Cancel' will indicate an asset log entry did not occur": "'Hủy' sẽ chỉ dẫn một lệnh nhập không thực hiện được", "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": "Một địa điểm chứa các đặc tính địa lý cho vùng đó. Đó có thể là một địa điểm theo đơn vị hành chính hay 'địa điểm nhóm' hay một địa điểm có đường ranh giới cho vùng đó.", "A volunteer is defined as active if they've participated in an average of 8 or more hours of Program work or Trainings per month in the last year": 'Tình nguyện viên hoạt động tích cực là những người tham gia trung bình từ 8 tiếng hoặc hơn vào các hoạt động của chương trình hay tập huấn một tháng trong năm trước.', "Acronym of the organization's name, eg. IFRC.": 'Từ viết tắt của tên tổ chức, vd IFRC.', "Add Person's Details": 'Thêm thông tin cá nhân', "Address of an image to use for this Layer in the Legend. This allows use of a controlled static image rather than querying the server automatically for what it provides (which won't work through GeoWebCache anyway).": 'Địa chỉ của hình ảnh sử dụng cho Lớp này nằm trong phần ghi chú. Việc này giúp việc sử dụng hình ảnh ổn định được kiểm soát tránh báo cáo tự động gửi tới máy chủ yêu cầu giải thích về nội dung cung cấp (chức năng này không hoạt động thông qua GeoWebCach).', "Authenticate system's Twitter account": 'Xác thực tài khoản Twitter thuộc hệ thống', "Can't import tweepy": 'Không thể nhập khẩu tweepy', "Cancel' will indicate an asset log entry did not occur": "Hủy' có nghĩa là ghi chép nhật ký tài sản không được lưu", "Caution: doesn't respect the framework rules!": 'Cảnh báo: Không tôn trọng các qui đinh khung chương trình', "Children's Education": 'Giáo dục Trẻ em', "Click 'Start' to synchronize with this repository now:": "Bấm nút 'Bắt đầu' để đồng bộ hóa kho dữ liệu bầy giờ", "Click on questions below to select them, then click 'Display Selected Questions' button to view the selected questions for all Completed Assessment Forms": "Bấm vào các câu hỏi phía dưới để chọn, sau đó bấm nút 'Hiển thị các câu hỏi đã chọn' để xem các câu hỏi đã chọn cho tất cả các mẫu Đánh giá hoàn chỉnh", "Don't Know": 'Không biết', "Edit Person's Details": 'Chỉnh sửa thông tin cá nhân', "Enter a name to search for. You may use % as wildcard. Press 'Search' without input to list all items.": "Nhập tên để tìm kiếm. Bạn có thể sử dụng % như là ký tự đặc biệt. Ấn 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả mặt hàng", "Error No Job ID's provided": 'Lỗi mã nhận dạng công việc không được cung cấp', "Framework added, awaiting administrator's approval": 'Khung chương trình đã được thêm mới, đang chờ phê duyệt của quản trị viên', "Go to %(url)s, sign up & then register your application. You can put any URL in & you only need to select the 'modify the map' permission.": "Đến trang %(url)s, đăng ký & sau đó đăng ký ứng dụng của bạn. Bạn có thể dùng bất cứ đường dẫn URL & chỉ cần chọn 'chức năng cho phép sửa bản đồ'.", "If selected, then this Asset's Location will be updated whenever the Person's Location is updated.": 'Nếu chọn, thì sau đó vị trí tài sản sẽ được cập nhật ngay khi vị trí của người đó được cập nhật.', "If this configuration is displayed on the GIS config menu, give it a name to use in the menu. The name for a personal map configuration will be set to the user's name.": 'Nếu cấu hình này được thể hiện trên danh mục cấu hình GIS, đặt tên cho cấu hình để sử dụng trên danh mục. Tên cấu hình bản đồ của cá nhân sẽ được gắn với tên người sử dụng.', "If this field is populated then a user who specifies this Organization when signing up will be assigned as a Staff of this Organization unless their domain doesn't match the domain field.": 'Nếu trường này đã nhiều người khi đó người dùng sẽ chi tiết tổ chức lúc đó việc đăng ký sẽ được phân bổ như là Cán bộ của tổ chức trừ phi chức năng đó không phù hợp.', "If you don't see the Cluster in the list, you can add a new one by clicking link 'Create Cluster'.": "Nếu bạn không tìm thấy tên Nhóm trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm nhóm'", "If you don't see the Organization in the list, you can add a new one by clicking link 'Create Organization'.": "Nếu bạn không tìm thấy tên Tổ chức trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm tổ chức'", "If you don't see the Sector in the list, you can add a new one by clicking link 'Create Sector'.": "Nếu bạn không tìm thấy Lĩnh vực trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm lĩnh vực'", "If you don't see the Type in the list, you can add a new one by clicking link 'Create Office Type'.": "Nếu bạn không tìm thấy Loại hình văn phòng trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm loại hình văn phòng'", "If you don't see the Type in the list, you can add a new one by clicking link 'Create Organization Type'.": "Nếu bạn không tìm thấy tên Loại hình tổ chức trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm loại hình tổ chức'", "If you don't see the activity in the list, you can add a new one by clicking link 'Create Activity'.": "Nếu bạn không tìm thấy hoạt động trong danh sách, bạn có thể thêm một bằng cách ấn nút 'Thêm hoạt động'", "If you don't see the asset in the list, you can add a new one by clicking link 'Create Asset'.": "Nếu bạn không tìm thấy tài sản trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm tài sản'", "If you don't see the beneficiary in the list, you can add a new one by clicking link 'Add Beneficiaries'.": "Nếu bạn không tìm thấy tên người hưởng lợi trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm người hưởng lợi'", "If you don't see the community in the list, you can add a new one by clicking link 'Create Community'.": "Nếu bạn không thấy Cộng đồng trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm cộng đồng'", "If you don't see the location in the list, you can add a new one by clicking link 'Create Location'.": "Nếu bạn không thấy Địa điểm trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm địa điểm'", "If you don't see the project in the list, you can add a new one by clicking link 'Create Project'.": "Nếu bạn không thấy dự án trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm dự án'", "If you don't see the type in the list, you can add a new one by clicking link 'Create Activity Type'.": "Nếu bạn không thấy loại hình hoạt động trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm loại hình hoạt động'", "If you don't see the vehicle in the list, you can add a new one by clicking link 'Add Vehicle'.": "Nếu bạn không thấy phương tiện vận chuyển trong danh sách, bạn có thể thêm mới bằng cách ấn nút 'Thêm phương tiện vận chuyển'", "If you enter a foldername then the layer will appear in this folder in the Map's layer switcher.": 'Nếu bạn nhập tên thư mục sau đó lớp đó sẽ hiện ra trong thư mục trong nút chuyển lớp Bản đồ.', "Last Week's Work": 'Công việc của tuấn trước', "Level is higher than parent's": 'Cấp độ cao hơn cấp độ gốc', "List Persons' Details": 'Liệt kê thông tin cá nhân', "Need a 'url' argument!": "Cần đối số cho 'url'!", "No UTC offset found. Please set UTC offset in your 'User Profile' details. Example: UTC+0530": "Không có thời gian bù UTC được tìm thấy. Cài đặt thời gian bù UTC trong thông tin 'Hồ sơ người sử dụng' của bạn. Ví dụ: UTC+0530", "Only Categories of type 'Vehicle' will be seen in the dropdown.": "Chỉ những hạng mục thuộc 'Xe cộ' được thể hiện trong danh sách thả xuống", "Optional. The name of the geometry column. In PostGIS this defaults to 'the_geom'.": "Tùy chọn. Tên của cột hình dạng. Trong PostGIS tên này được mặc định là 'the_geom'.", "Parent level should be higher than this record's level. Parent level is": 'Mức độ cấp trên phải cao hơn mức độ của bản lưu này. Mức độ cấp trên là', "Password fields don't match": 'Trường mật khẩu không tương thích', "Person's Details added": 'Thông tin được thêm vào của cá nhân', "Person's Details deleted": 'Thông tin đã xóa của cá nhân', "Person's Details updated": 'Thông tin được cập nhật của cá nhân', "Person's Details": 'Thông tin cá nhân', "Persons' Details": 'Thông tin cá nhân', "Phone number to donate to this organization's relief efforts.": 'Số điện thoại để ủng hộ cho những nỗ lực cứu trợ của tổ chức này', "Please come back after sometime if that doesn't help.": 'Xin vui lòng quay trở lại sau nếu điều đó không giúp ích bạn.', "Please provide as much detail as you can, including the URL(s) where the bug occurs or you'd like the new feature to go.": 'Xin vui lòng cung cấp thông tin chi tiết nhất có thể, bao gồm những đường dẫn URL chứa các lỗi kỹ thuật hay bạn muốn thực hiện chức năng mới.', "Post graduate (Doctor's)": 'Tiến sỹ', "Post graduate (Master's)": 'Thạc sỹ', "Quantity in %s's Warehouse": 'Số lượng trong %s Nhà kho', "Search Person's Details": 'Tìm kiếm thông tin cá nhân', "Select a Facility Type from the list or click 'Create Facility Type'": "Chọn loại hình bộ phận từ danh sách hoặc bấm 'Thêm loại hình bộ phận'", "Select a Room from the list or click 'Create Room'": "Chọn một Phòng từ danh sách hay bấm 'Thêm Phòng'", "Select this if all specific locations need a parent at the deepest level of the location hierarchy. For example, if 'district' is the smallest division in the hierarchy, then all specific locations would be required to have a district as a parent.": "Chọn nó nếu tất cả các điểm cụ thể cần lớp cao nhất trong hệ thống hành chính các địa điểm. Ví dụ, nếu 'là lớp huyện' là phân chia nhỏ nhất trong hệ thống, do vậy các địa điểm cụ thể sẽ yêu cầu có lớp huyện là lớp trên.", "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area.": 'Chọn nó nếu tất cả các điểm cụ thể cần lớp trên trong hệ thống hành chính các địa điểm. Nó có thể giúp lập nên một vùng diện cho một vùng bị ảnh hưởng. ', "Sorry, things didn't get done on time.": 'Xin lỗi, công việc đã không được làm đúng lúc.', "Sorry, we couldn't find that page.": 'Xin lỗi, chúng tôi không thể tìm thấy trang đó', "Status 'assigned' requires the %(fieldname)s to not be blank": "Tình trạng 'được bổ nhiệm' đòi hỏi %(fieldname)s không được bỏ trống", "System's Twitter account updated": 'Tài khoản Twitter của Hệ thống được cập nhật', "The Project module can be used to record Project Information and generate Who's Doing What Where reports.": 'Mô đun Dự án có thể được sử dụng để ghi lại Thông tin Dự án và cho ra các báo cáo Ai Đang làm Điều gì Ở đâu.', "The URL of the image file. If you don't upload an image file, then you must specify its location here.": 'Đường dẫn URL của tệp tin hình ảnh. Nếu bạn không tải tệp tin hình ảnh lên, thì bạn phải đưa đường dẫn tới vị trí của tệp tin đó tại đây.', "The person's manager within this Office/Project.": 'Quản lý của một cá nhân trong Văn phòng/Dự án', "The staff member's official job title": 'Chức vụ chính thức của cán bộ', "The volunteer's role": 'Vai trò của tình nguyện viên', "There are no details for this person yet. Add Person's Details.": 'Chưa có thông tin về người này. Hãy thêm Thông tin.', "To search for a hospital, enter any part of the name or ID. You may use % as wildcard. Press 'Search' without input to list all hospitals.": 'Để tìm kiếm một bệnh viện, nhập một phần tên hoặc ID. Có thể sử dụng % như một ký tự thay thế cho một nhóm ký tự. Nhấn "Tìm kiếm" mà không nhập thông tin, sẽ hiển thị toàn bộ các bệnh viện.', "To search for a location, enter the name. You may use % as wildcard. Press 'Search' without input to list all locations.": "Dể tìm kiếm địa điểm, nhập tên của địa điểm đó. Bản có thể sử dụng ký tự % như là ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập tên địa điểm để liệt kê toàn bộ địa điểm.", "To search for a member, enter any portion of the name of the person or group. You may use % as wildcard. Press 'Search' without input to list all members": "Để tìm thành viên, nhập tên của thành viên hoặc nhóm. Bạn có thể sử dụng % như là ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập tên để liệt toàn bộ thành viên", "To search for a person, enter any of the first, middle or last names and/or an ID number of a person, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Để tìm kiếm người, nhập bất kỳ tên, tên đệm hoặc tên họ và/ hoặc số nhận dạng cá nhân của người đó, tách nhau bởi dấu cách. Ấn nút 'Tìm kiếm' mà không nhập tên người để liệt kê toàn bộ người.", "Type the first few characters of one of the Participant's names.": 'Nhập những ký tự đầu tiên trong tên của một Người tham dự.', "Type the first few characters of one of the Person's names.": 'Nhập những ký tự đầu tiên trong tên của một Người.', "Type the name of an existing catalog item OR Click 'Create Item' to add an item which is not in the catalog.": "Nhập tên của một mặt hàng trong danh mục đang tồn tại HOẶC Nhấn 'Thêm mặt hàng mới' để thêm một mặt hàng chưa có trong danh mục.", "Upload an image file here. If you don't upload an image file, then you must specify its location in the URL field.": 'Tải lên file hình ảnh tại đây. Nếu bạn không đăng tải được file hình ảnh, bạn phải chỉ đường dẫn chính xác tới vị trí của file trong trường URL.', "Uploaded file(s) are not Image(s). Supported image formats are '.png', '.jpg', '.bmp', '.gif'.": "File được tải không phải là hình ảnh. Định dạng hình ảnh hỗ trợ là '.png', '.jpg', '.bmp', '.gif'", "View and/or update details of the person's record": 'Xem và/hoặc cập nhật chi tiết mục ghi cá nhân', """Welcome to %(system_name)s - You can start using %(system_name)s at: %(url)s - To edit your profile go to: %(url)s%(profile)s Thank you""": """Chào mừng anh/chị truy cập %(system_name)s Anh/chị có thể bắt đầu sử dụng %(system_name)s tại %(url)s Để chỉnh sửa hồ sơ của anh/chị, xin vui lòng truy cập %(url)s%(profile)s Cảm ơn""", "Yes, No, Don't Know": 'Có, Không, Không biết', "You can search by asset number, item description or comments. You may use % as wildcard. Press 'Search' without input to list all assets.": "Bạn có thể tìm kiếm theo mã số tài sản, mô tả mặt hàng hoặc các bình luận. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả tài sản.", "You can search by course name, venue name or event comments. You may use % as wildcard. Press 'Search' without input to list all events.": "Bạn có thể tìm kiếm theo tên khóa học, tên địa điểm tổ chức hoặc bình luận về khóa học. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả khóa học.", "You can search by description. You may use % as wildcard. Press 'Search' without input to list all incidents.": "Bạn có thể tìm kiếm theo mô tả. Bạn có thể sử dụng % làm ký tự đại diện. Không nhập thông tin và nhấn 'Tìm kiếm' để liệt kê tất cả các sự kiện.", "You can search by job title or person name - enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Bạn có thể tìm kiếm theo chức vụ nghề nghiệp hoặc theo tên đối tượng - nhập bất kỳ tên nào trong tên chính, tên đệm hay họ, tách nhau bởi dấu cách. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả đối tượng.", "You can search by person name - enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons.": "Bạn có thể tìm kiếm theo tên người - nhập bất kỳ tên, tên đệm hay tên họ, tách nhau bởi dấu cách. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả số người.", "You can search by trainee name, course name or comments. You may use % as wildcard. Press 'Search' without input to list all trainees.": "Bạn có thể tìm kiếm bằng tên người được tập huấn, tên khóa học hoặc các bình luận. Bạn có thể sử dụng % làm ký tự đặc trưng. Ấn nút 'Tìm kiếm' mà không nhập giá trị để liệt kê tất cả người được tập huấn.", "You have personalised settings, so changes made here won't be visible to you. To change your personalised settings, click ": 'Bạn đã thiết lập các cài đặt cá nhân, vì vậy bạn không xem được các thay đổi ở đây.Để thiết lập lại, nhấp chuột vào', "You have unsaved changes. Click Cancel now, then 'Save' to save them. Click OK now to discard them.": "Bạn chưa lưu các thay đổi. Ấn 'Hủy bỏ' bây giờ, sau đó ấn 'Lưu' để lưu lại. Ấn OK bây giờ để bỏ các thay đổi", "communications systems, health facilities, 'lifelines', power and energy, emergency evacuation shelters, financial infrastructure, schools, transportation, waste disposal, water supp": 'hệ thống thông tin liên lạc, cơ sở CSSK, hệ thống bảo hộ, năng lượng, các địa điểm sơ tán trong tình huống khẩn cấp, hạ tầng tài chính, trường học, giao thông, bãi rác thải, hệ thống cấp nước', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"cập nhật" là một lựa chọn như "Thực địa1=\'giá trị mới\'". Bạn không thể cập nhật hay xóa các kết quả của một NHÓM', '# of Houses Damaged': 'Số nóc nhà bị phá hủy', '# of Houses Destroyed': 'Số căn nhà bị phá hủy', '# of International Staff': 'số lượng cán bộ quốc tế', '# of National Staff': 'số lượng cán bộ trong nước', '# of People Affected': 'Số người bị ảnh hưởng', '# of People Injured': 'Số lượng người bị thương', '%(GRN)s Number': '%(GRN)s Số', '%(GRN)s Status': '%(GRN)s Tình trạng', '%(PO)s Number': '%(PO)s Số', '%(REQ)s Number': '%(REQ)s Số', '%(app)s not installed. Ask the Server Administrator to install on Server.': '%(app)s dụng chưa được cài. Liên hệ với ban quản trị máy chủ để cài ứng dụng trên máy chủ', '%(count)s Entries Found': '%(count)s Hồ sơ được tìm thấy', '%(count)s Roles of the user removed': '%(count)s Đã gỡ bỏ chức năng của người sử dụng', '%(count)s Users removed from Role': '%(count)s Đã xóa người sử dụng khỏi chức năng', '%(count_of)d translations have been imported to the %(language)s language file': '%(count_of)d bản dịch được nhập liệu trong %(language)s file ngôn ngữ', '%(item)s requested from %(site)s': '%(item)s đề nghị từ %(site)s', '%(module)s not installed': '%(module)s chưa được cài đặt', '%(pe)s in %(location)s': '%(pe)s tại %(location)s', '%(quantity)s in stock': '%(quantity)s hàng lưu kho', '%(system_name)s has sent an email to %(email)s to verify your email address.\nPlease check your email to verify this address. If you do not receive this email please check you junk email or spam filters.': '%(system_name)s đã gửi email đến %(email)s để kiểm tra địa chỉ email của bạn.\nĐề nghị kiểm tra email để xác nhận. Nếu bạn không nhận được hãy kiểm tra hộp thư rác hay bộ lọc thư rác.', '%s items are attached to this shipment': '%s hàng hóa được chuyển trong đợt xuất hàng này', '& then click on the map below to adjust the Lat/Lon fields': '& sau đó chọn trên bản đồ để chính sửa số kinh/vĩ độ', '(filtered from _MAX_ total entries)': '(lọc từ _MAX_ toàn bộ hồ sơ)', '* Required Fields': '* Bắt buộc phải điền', '...or add a new bin': '…hoặc thêm một ngăn mới', '1 Assessment': '1 Đánh giá', '1 location, shorter time, can contain multiple Tasks': '1 địa điểm, thời gian ngắn hơn, có thể bao gồm nhiều nhiệm vụ khác nhau', '1. Fill the necessary fields in BLOCK CAPITAL letters.': '1. Điền nội dung vào các ô cần thiết bằng CHỮ IN HOA.', '2. Always use one box per letter and leave one box space to separate words.': '2. Luôn sử dụng một ô cho một chữ cái và để một ô trống để cách giữa các từ', '3. Fill in the circles completely.': '3. Điền đầy đủ vào các ô tròn', '3W Report': 'Báo cáo 3W', 'A Marker assigned to an individual Location is set if there is a need to override the Marker assigned to the Feature Class.': 'Một đánh dấu cho một vị trí đơn lẻ nếu cần thiết để thay thế một Đánh dấu theo chức năng.', 'A brief description of the group (optional)': 'Mô tả ngắn gọn nhóm đánh giá (không bắt buộc)', 'A catalog of different Assessment Templates including summary information': 'Danh mục các biểu mẫu đánh giá khác nhau bao gồm cả thông tin tóm tắt', 'A file in GPX format taken from a GPS.': 'file định dạng GPX từ máy định vị GPS.', 'A place within a Site like a Shelf, room, bin number etc.': 'Một nơi trên site như số ngăn ,số phòng,số thùng v.v', 'A project milestone marks a significant date in the calendar which shows that progress towards the overall objective is being made.': 'Một mốc quan trọng của dự án đánh dấu ngày quan trọng trong lịch để chỉ ra tiến độ đạt được mục tổng quát của dự án.', 'A snapshot of the location or additional documents that contain supplementary information about the Site can be uploaded here.': 'Upload ảnh chụp vị trí hoặc tài liệu bổ sung chứa thông tin bổ sung về trang web tại đây', 'A staff member may have multiple roles in addition to their formal job title.': 'Một cán bộ có thể có nhiều chức năng nhiệm vụ bổ sung thêm vào chức năng nhiệm vụ chính.', 'A strict location hierarchy cannot have gaps.': 'Thứ tự vi trí đúng không thể có khoảng cách.', 'A survey series with id %s does not exist. Please go back and create one.': 'Chuỗi khảo sát số %s không tồn tai.Vui lòng quay lại và tạo mới', 'A task is a piece of work that an individual or team can do in 1-2 days.': 'Nhiệm vụ là công việc mà một cá nhân hoặc nhóm có thể thực hiện trong 1-2 ngày.', 'A volunteer may have multiple roles in addition to their formal job title.': 'Một tình nguyện viên có thể có nhiều chức năng nhiệm vụ bổ sung thêm vào chức năng nhiệm vụ chính.', 'ABOUT CALCULATIONS': 'TẠM TÍNH', 'ABOUT THIS MODULE': 'Giới thiệu Module này', 'ABSOLUTE%(br)sDEVIATION': 'HOÀN TOÀN%(br)sCHỆCH HƯỚNG', 'ACTION REQUIRED': 'HÀNH ĐỘNG ĐƯỢC YÊU CẦU', 'ALL REPORTS': 'TẤT CẢ BÁO CÁO', 'ALL': 'Tất cả', 'ANY': 'BẤT KỲ', 'API is documented here': 'API được lưu trữ ở đây', 'APPROVE REPORTS': 'PHÊ DUYỆT BÁO CÁO', 'AUTH TOKEN': 'THẺ XÁC THỰC', 'Abbreviation': 'Từ viết tắt', 'Ability to customize the list of human resource tracked at a Shelter': 'Khả năng tùy chỉnh danh sách nguồn nhân lực theo dõi tại nơi cư trú', 'Ability to customize the list of important facilities needed at a Shelter': 'Khả năng tùy chỉnh danh sách các điều kiện quan trọng cần thiết tại một cơ sở cư trú', 'Able to Respond?': 'Có khả năng ứng phó không?', 'About Us': 'Giới thiệu', 'About': 'Khoảng', 'Accept Push': 'Chấp nhận Đẩy', 'Accept unsolicited data transmissions from the repository.': 'Chấp nhận truyền các dữ liệu chưa tổng hợp từ kho dữ liệu.', 'Access denied': 'Từ chối truy cập', 'Account Name': 'Tên tài khoản', 'Account Registered - Please Check Your Email': 'Tài khoản đã được đăng ký- Kiểm tra email của bạn', 'Achieved': 'Thành công', 'Acronym': 'Từ viết tắt', 'Action': 'Hành động', 'Actioning officer': 'Cán bộ hành động', 'Actions taken as a result of this request.': 'Hành động được thực hiện như là kết quả của yêu cầu này.', 'Actions': 'Hành động', 'Activate': 'Kích hoạt', 'Active Problems': 'Có vấn đề kích hoạt', 'Active': 'Đang hoạt động', 'Active?': 'Đang hoạt động?', 'Activities matching Assessments': 'Hoạt động phù hợp với Đánh giá', 'Activities': 'Hoạt động', 'Activity Added': 'Hoạt động đã được thêm mới', 'Activity Deleted': 'Hoạt động đã được xóa', 'Activity Details': 'Chi tiết hoạt động', 'Activity Report': 'Báo cáo hoạt động', 'Activity Type Added': 'Loại hình hoạt động đã được thêm mới', 'Activity Type Deleted': 'Loại hình hoạt động đã được xóa', 'Activity Type Sectors': 'Lĩnh vực của loại hình hoạt động', 'Activity Type Updated': 'Loại hình hoạt động đã được cập nhật', 'Activity Type': 'Hoạt động', 'Activity Types': 'Hoạt động', 'Activity Updated': 'Hoạt động đã được cập nhật', 'Activity': 'Hoạt động', 'Add Activity Type': 'Thêm loại hình hoạt động', 'Add Address': 'Thêm địa chỉ', 'Add Affiliation': 'Thêm liên kết', 'Add Aid Request': 'Thêm yêu cầu cứu trợ', 'Add Alternative Item': 'Thêm mặt hàng thay thế', 'Add Annual Budget': 'Thêm ngân sách năm', 'Add Assessment Answer': 'Thêm câu trả lời đánh giá', 'Add Assessment Templates': 'Thêm biểu mẫu đánh giá', 'Add Assessment': 'Thêm đợt đánh giá', 'Add Award': 'Thêm mới', 'Add Beneficiaries': 'Thêm người hưởng lợi', 'Add Branch Organization': 'Thêm tổ chức cấp tỉnh/ huyện/ xã', 'Add Certificate for Course': 'Thêm chứng nhận khóa tập huấn', 'Add Certification': 'Thêm bằng cấp', 'Add Contact Information': 'Thêm thông tin liên hệ', 'Add Contact': 'Thêm liên lạc', 'Add Credential': 'Thêm thư ủy nhiệm', 'Add Data to Theme Layer': 'Thêm dữ liệu vào lớp chủ đề', 'Add Demographic Data': 'Thêm số liệu dân số', 'Add Demographic Source': 'Thêm nguồn thông tin dân số', 'Add Demographic': 'Thêm dữ liệu nhân khẩu', 'Add Disciplinary Action': 'Thêm mới', 'Add Disciplinary Action Type': 'Thêm hình thức kỷ luật', 'Add Distribution': 'Thêm thông tin hàng hóa đóng góp', 'Add Donor': 'Thêm tên người quyên góp vào danh sách', 'Add Education': 'Thêm trình độ học vấn', 'Add Email Settings': 'Thêm cài đặt email', 'Add Employment': 'Thêm mới', 'Add Experience': 'Thêm Kinh nghiệm', 'Add Framework': 'Thêm khung chương trình', 'Add Group Member': 'Thêm thành viên nhóm', 'Add Hours': 'Thêm thời gian hoạt động', 'Add Identity': 'Thêm nhận dạng', 'Add Image': 'Thêm hình ảnh', 'Add Item Catalog': 'Thêm danh mục hàng hóa', 'Add Item to Catalog': 'Thêm hàng hóa vào danh mục', 'Add Item to Commitment': 'Thêm hàng hóa vào cam kết', 'Add Item to Request': 'Thêm hàng hóa mới để yêu cầu', 'Add Item to Shipment': 'Thêm hàng hóa vào lô hàng chuyển đi', 'Add Item to Stock': 'Thêm mặt hàng lưu kho', 'Add Item': 'Thêm hàng hóa', 'Add Job Role': 'Thêm chức năng công việc', 'Add Key': 'Thêm từ khóa', 'Add Kit': 'Thêm Kit', 'Add Layer from Catalog': 'Thêm lớp từ danh mục', 'Add Layer to this Profile': 'Thêm lớp vào hồ sơ này', 'Add Line': 'Thêm dòng', 'Add Location': 'Thêm địa điểm', 'Add Locations': 'Thêm địa điểm mới', 'Add Log Entry': 'Thêm ghi chép nhật ký', 'Add Member': 'Thêm hội viên', 'Add Membership': 'Thêm nhóm hội viên', 'Add Message': 'Thêm tin nhắn', 'Add New Aid Request': 'Thêm yêu cầu cứu trợ mới', 'Add New Beneficiaries': 'Thêm người hưởng lợi mới', 'Add New Beneficiary Type': 'Thêm loại người hưởng lợi mới', 'Add New Branch': 'Thêm chi nhánh mới', 'Add New Cluster': 'Thêm nhóm mới', 'Add New Commitment Item': 'Thêm hàng hóa cam kết mới', 'Add New Community': 'Thêm cộng đồng mới', 'Add New Config': 'Thêm cấu hình mới', 'Add New Demographic Data': 'Thêm số liệu dân số mới', 'Add New Demographic Source': 'Thêm nguồn số liệu dân số mới', 'Add New Demographic': 'Thêm dữ liệu nhân khẩu mới', 'Add New Document': 'Thêm tài liệu mới', 'Add New Donor': 'Thêm nhà tài trợ mới', 'Add New Entry': 'Thêm hồ sơ mới', 'Add New Flood Report': 'Thêm báo cáo lũ lụt mới', 'Add New Framework': 'Thêm khung chương trình mới', 'Add New Image': 'Thêm hình ảnh mới', 'Add New Item to Stock': 'Thêm hàng hóa mới để lưu trữ', 'Add New Job Role': 'Thêm chức năng công việc mới', 'Add New Key': 'Thêm Key mới', 'Add New Layer to Symbology': 'Thêm lớp mới vào các mẫu biểu tượng', 'Add New Mailing List': 'Thêm danh sách gửi thư mới', 'Add New Member': 'Thêm hội viên mới', 'Add New Membership Type': 'Thêm loại nhóm hội viên mới', 'Add New Membership': 'Thêm nhóm hội viên mới', 'Add New Organization Domain': 'Thêm lĩnh vực hoạt động mới của tổ chức', 'Add New Output': 'Thêm kết quả đầu ra mới', 'Add New Participant': 'Thêm người tham dự mới', 'Add New Problem': 'Thêm vấn đề mới', 'Add New Profile Configuration': 'Thêm định dạng hồ sơ tiểu sử mới', 'Add New Record': 'Thêm hồ sơ mới', 'Add New Request Item': 'Thêm yêu cầu hàng hóa mới', 'Add New Request': 'Thêm yêu cầu mới', 'Add New Response': 'Thêm phản hồi mới', 'Add New Role to User': 'Gán vai trò mới cho người dùng', 'Add New Shipment Item': 'Thêm mặt hàng mới được vận chuyển', 'Add New Site': 'Thêm trang web mới', 'Add New Solution': 'Thêm giải pháp mới', 'Add New Staff Assignment': 'Thêm nhiệm vụ mới cho cán bộ', 'Add New Staff': 'Thêm bộ phận nhân viên', 'Add New Storage Location': 'Thêm Vị trí kho lưu trữ mới', 'Add New Survey Template': 'Thêm mẫu khảo sát mới', 'Add New Team Member': 'Thêm thành viên mới', 'Add New Team': 'Thêm Đội/Nhóm mới', 'Add New Unit': 'Thêm đơn vị mới', 'Add New Vehicle Assignment': 'Thêm phân công mới cho phương tiện vận chuyển', 'Add New Vulnerability Aggregated Indicator': 'Thêm chỉ số gộp mới đánh giá tình trạng dễ bị tổn thương', 'Add New Vulnerability Data': 'Thêm dữ liệu mới về tình trạng dễ bị tổn thương', 'Add New Vulnerability Indicator Sources': 'Thêm nguồn chỉ số mới đánh giá tình trạng dễ bị tổn thương', 'Add New Vulnerability Indicator': 'Thêm chỉ số mới đánh giá tình trạng dễ bị tổn thương', 'Add Order': 'Thêm đơn đặt hàng', 'Add Organization Domain': 'Thêm lĩnh vực hoạt động của tổ chức', 'Add Organization to Project': 'Thêm tổ chức tham gia dự án', 'Add Parser Settings': 'Thêm cài đặt cú pháp', 'Add Participant': 'Thêm người tham dự', 'Add Person to Commitment': 'Thêm đối tượng cam kết', 'Add Person': 'Thêm họ tên', 'Add Photo': 'Thêm ảnh', 'Add Point': 'Thêm điểm', 'Add Polygon': 'Thêm đường chuyền', 'Add Professional Experience': 'Thêm kinh nghiệm nghề nghiệp', 'Add Profile Configuration for this Layer': 'Thêm định dạng hồ sơ tiểu sử cho lớp này', 'Add Profile Configuration': 'Thêm hồ sơ tiểu sử', 'Add Program Hours': 'Thêm thời gian tham gia chương trình', 'Add Recipient': 'Thêm người nhận viện trợ', 'Add Record': 'Thêm hồ sơ', 'Add Reference Document': 'Thêm tài liệu tham chiếu', 'Add Request Detail': 'thêm chi tiết yêu cầu', 'Add Request Item': 'Thêm yêu cầu hàng hóa', 'Add Request': 'Thêm yêu cầu', 'Add Salary': 'Thêm mới', 'Add Salary Grade': 'Thêm bậc lương', 'Add Sender Organization': 'Thêm tổ chức gửi', 'Add Setting': 'Thêm cài đặt', 'Add Site': 'Thêm site', 'Add Skill': 'Thêm kỹ năng', 'Add Skill Equivalence': 'Thêm kỹ năng tương đương', 'Add Skill Types': 'Thêm loại kỹ năng', 'Add Skill to Request': 'Thêm kỹ năng để yêu cầu', 'Add Staff Assignment': 'Thêm nhiệm vụ cho cán bộ', 'Add Staff Level': 'Thêm ngạch công chức', 'Add Staff Member to Project': 'Thêm cán bộ thực hiện dự án', 'Add Stock to Warehouse': 'Thêm hàng vào kho', 'Add Storage Location ': 'Thêm vị trí lưu trữ', 'Add Storage Location': 'Thêm vị trí lưu trữ', 'Add Sub-Category': 'Thêm danh mục cấp dưới', 'Add Survey Answer': 'Thêm trả lời khảo sát', 'Add Survey Question': 'Thêm câu hỏi khảo sát', 'Add Survey Section': 'Thêm phần Khảo sát', 'Add Survey Series': 'Thêm chuỗi khảo sát', 'Add Survey Template': 'Thêm mẫu khảo sát', 'Add Symbology to Layer': 'Thêm biểu tượng cho lớp', 'Add Team Member': 'Thêm thành viên Đội/Nhóm', 'Add Team': 'Thêm Đội/Nhóm', 'Add Template Section': 'Thêm nội dung vào biểu mẫu', 'Add Training': 'Thêm tập huấn', 'Add Translation Language': 'Thêm ngôn ngữ biên dịch mới', 'Add Twilio Settings': 'Thêm cài đặt Twilio', 'Add Unit': 'Thêm đơn vị', 'Add Vehicle Assignment': 'Thêm phân công cho phương tiện vận chuyển', 'Add Vehicle': 'Thêm phương tiện vận chuyển', 'Add Volunteer Registration': 'Thêm Đăng ký tình nguyện viên', 'Add Volunteer to Project': 'Thêm tình nguyện viên hoạt động trong dự án', 'Add Vulnerability Aggregated Indicator': 'Thêm chỉ số gộp đánh giá tình trạng dễ bị tổn thương', 'Add Vulnerability Data': 'Thêm dữ liệu về tình trạng dễ bị tổn thương', 'Add Vulnerability Indicator Source': 'Thêm nguồn chỉ số đánh giá tình trạng dễ bị tổn thương', 'Add Vulnerability Indicator': 'Thêm chỉ số đánh giá tình trạng dễ bị tổn thương', 'Add a description': 'Thêm miêu tả', 'Add a new Assessment Answer': 'Thêm câu trả lời mới trong mẫu đánh giá', 'Add a new Assessment Question': 'Thêm câu hỏi mới trong mẫu đánh giá', 'Add a new Assessment Template': 'Thêm biểu mẫu đánh giá mới', 'Add a new Completed Assessment Form': 'Thêm mẫu đánh giá được hoàn thiện mới', 'Add a new Disaster Assessment': 'Thêm báo cáo đánh giá thảm họa mới', 'Add a new Site from where the Item is being sent.': 'Thêm Site nơi gửi hàng hóa đến ', 'Add a new Template Section': 'Thêm nội dung mới vào biểu mẫu', 'Add a new certificate to the catalog.': 'Thêm chứng chỉ mới vào danh mục', 'Add a new competency rating to the catalog.': 'Thêm xếp loại năng lực mới vào danh mục', 'Add a new membership type to the catalog.': 'Thêm loại hình nhóm hội viên mới vào danh mục', 'Add a new programme to the catalog.': 'Thêm chương trình mới vào danh mục', 'Add a new skill type to the catalog.': 'Thêm loại kỹ năng mới vào danh mục', 'Add all organizations which are involved in different roles in this project': 'Thêm tất cả tổ chức đang tham gia vào dự án với vai trò khác nhau', 'Add all': 'Thêm tất cả', 'Add new Group': 'Thêm nhóm mới', 'Add new Question Meta-Data': 'Thêm siêu dữ liệu câu hỏi mới', 'Add new and manage existing members.': 'Thêm mới và quản lý hội viên.', 'Add new and manage existing staff.': 'Thêm mới và quản lý cán bộ.', 'Add new and manage existing volunteers.': 'Thêm mới và quản lý tình nguyện viên.', 'Add new position.': 'Thêm địa điểm mới', 'Add new project.': 'Thêm dự án mới', 'Add new staff role.': 'Thêm vai trò nhân viên mới', 'Add saved search': 'Thêm tìm kiếm đã lưu', 'Add strings manually through a text file': 'Thêm chuỗi ký tự thủ công bằng file văn bản', 'Add strings manually': 'Thêm chuỗi ký tự thủ công', 'Add the Storage Location where this this Bin belongs to.': 'Thêm vị trí kho lưu trữ chứa Bin này', 'Add the main Warehouse/Site information where this Item is to be added.': 'Thêm thông tin Nhà kho/Site chứa hàng hóa đã được nhập thông tin', 'Add this entry': 'Thêm hồ sơ này', 'Add to Bin': 'Thêm vào thùng', 'Add': 'Thêm', 'Add...': 'Thêm…', 'Add/Edit/Remove Layers': 'Thêm/Sửa/Xóa các lớp', 'Added to Group': 'Nhóm hội viên đã được thêm', 'Added to Team': 'Nhóm hội viên đã được thêm', 'Address Details': 'Chi tiết địa chỉ', 'Address Type': 'Loại địa chỉ', 'Address added': 'Địa chỉ đã được thêm', 'Address deleted': 'Địa chỉ đã được xóa', 'Address updated': 'Địa chỉ đã được cập nhật', 'Address': 'Địa chỉ', 'Addresses': 'Địa chỉ', 'Adjust Item Quantity': 'Chỉnh sửa số lượng mặt hàng', 'Adjust Stock Item': 'Chỉnh sửa mặt hàng lưu kho', 'Adjust Stock Levels': 'Điều chỉnh cấp độ hàng lưu kho', 'Adjust Stock': 'Chỉnh sửa hàng lưu kho', 'Adjustment created': 'Chỉnh sửa đã được tạo', 'Adjustment deleted': 'Chỉnh sửa đã đươc xóa', 'Adjustment modified': 'Chỉnh sửa đã được thay đổi', 'Admin Email': 'Email của quản trị viên', 'Admin Name': 'Tên quản trị viên', 'Admin Tel': 'Số điện thoại của Quản trị viên', 'Admin': 'Quản trị', 'Administration': 'Quản trị', 'Administrator': 'Quản trị viên', 'Adolescent (12-20)': 'Vị thành niên (12-20)', 'Adult (21-50)': 'Người trưởng thành (21-50)', 'Adult Psychiatric': 'Bệnh nhân tâm thần', 'Adult female': 'Nữ giới', 'Adult male': 'Đối tượng người lớn là nam ', 'Advance': 'Cao cấp', 'Advanced Catalog Search': 'Tìm kiếm danh mục nâng cao', 'Advanced Category Search': 'Tìm kiếm danh mục nâng cao', 'Advanced Location Search': 'Tìm kiếm vị trí nâng cao', 'Advanced Search': 'Tìm kiếm nâng cao', 'Advanced Site Search': 'Tìm kiếm website nâng cao', 'Advocacy': 'Vận động chính sách', 'Affected Persons': 'Người bị ảnh hưởng', 'Affiliation Details': 'Chi tiết liên kết', 'Affiliation added': 'Liên kết đã được thêm', 'Affiliation deleted': 'Liên kết đã được xóa', 'Affiliation updated': 'Liên kết đã được cập nhật', 'Affiliations': 'Liên kết', 'Age Group (Count)': 'Nhóm tuổi (Số lượng)', 'Age Group': 'Nhóm tuổi', 'Age group does not match actual age.': 'Nhóm tuổi không phù hợp với tuổi hiện tại', 'Aid Request Details': 'Chi tiết yêu cầu cứu trợ', 'Aid Request added': 'Đã thêm yêu cầu viện trợ', 'Aid Request deleted': 'Đã xóa yêu cầu cứu trợ', 'Aid Request updated': 'Đã cập nhật Yêu cầu cứu trợ', 'Aid Request': 'Yêu cầu cứu trợ', 'Aid Requests': 'yêu cầu cứu trợ', 'Aircraft Crash': 'Tại nạn máy bay', 'Aircraft Hijacking': 'Bắt cóc máy bay', 'Airport Closure': 'Đóng cửa sân bay', 'Airport': 'Sân bay', 'Airports': 'Sân bay', 'Airspace Closure': 'Đóng cửa trạm không gian', 'Alcohol': 'Chất cồn', 'Alerts': 'Cảnh báo', 'All Entities': 'Tất cả đối tượng', 'All Inbound & Outbound Messages are stored here': 'Tất cả tin nhắn gửi và nhận được lưu ở đây', 'All Open Tasks': 'Tất cả nhiệm vụ công khai', 'All Records': 'Tất cả hồ sơ', 'All Requested Items': 'Hàng hóa được yêu cầu', 'All Resources': 'Tất cả nguồn lực', 'All Tasks': 'Tất cả nhiệm vụ', 'All reports': 'Tất cả báo cáo', 'All selected': 'Tất cả', 'All': 'Tất cả', 'Allowance': 'Phụ cấp', 'Allowed to push': 'Cho phép bấm nút', 'Allows authorized users to control which layers are available to the situation map.': 'Cho phép người dùng đã đăng nhập kiểm soát layer nào phù hợp với bản đồ tình huống', 'Alternative Item Details': 'Chi tiết mặt hàng thay thế', 'Alternative Item added': 'Mặt hàng thay thế đã được thêm', 'Alternative Item deleted': 'Mặt hàng thay thế đã được xóa', 'Alternative Item updated': 'Mặt hàng thay thế đã được cập nhật', 'Alternative Items': 'Mặt hàng thay thế', 'Ambulance Service': 'Dịch vụ xe cứu thương', 'Amount': 'Tổng ngân sách', 'An Assessment Template can be selected to create a Disaster Assessment. Within a Disaster Assessment, responses can be collected and results can analyzed as tables, charts and maps': 'Mẫu đánh giá có thể được chọn để tạo ra một Đánh giá tình hình Thảm họa. Trong Đánh giá tình hình Thảm họa, các hoạt động ứng phó có thể được tổng hợp và kết quả có thể được phân tích dưới dạng bảng, biểu đồ và bản đồ', 'An Item Category must have a Code OR a Name.': 'Danh mục hàng hóa phải có Mã hay Tên.', 'Analysis': 'Phân tích', 'Animal Die Off': 'Động vật tuyệt chủng', 'Animal Feed': 'Thức ăn động vật', 'Annual Budget deleted': 'Ngân sách năm đã được xóa', 'Annual Budget updated': 'Ngân sách năm đã được cập nhật', 'Annual Budget': 'Ngân sách năm', 'Annual Budgets': 'Ngân sách năm', 'Anonymous': 'Ẩn danh', 'Answer Choices (One Per Line)': 'Chọn câu trả lời', 'Any available Metadata in the files will be read automatically, such as Timestamp, Author, Latitude & Longitude.': 'Thông tin có sẵn trong file như Timestamp,Tác giả, Kinh độ, Vĩ độ sẽ được đọc tự động', 'Any': 'Bất cứ', 'Applicable to projects in Pacific countries only': 'Chỉ áp dụng cho dự án trong các nước thuộc khu vực Châu Á - Thái Bình Dương', 'Application Permissions': 'Chấp nhận đơn đăng ký', 'Application': 'Đơn đăng ký', 'Apply changes': 'Lưu thay đổi', 'Approval pending': 'Đang chờ phê duyệt', 'Approval request submitted': 'Yêu cầu phê duyệt đã được gửi', 'Approve': 'Phê duyệt', 'Approved By': 'Được phê duyệt bởi', 'Approved by %(first_initial)s.%(last_initial)s': 'Được phê duyệt bởi %(first_initial)s.%(last_initial)s', 'Approved': 'Đã phê duyệt', 'Approver': 'Người phê duyệt', 'ArcGIS REST Layer': 'Lớp ArcGIS REST', 'Archive not Delete': 'Bản lưu không xóa', 'Arctic Outflow': 'Dòng chảy từ Bắc Cực', 'Are you sure you want to delete this record?': 'Bạn có chắc bạn muốn xóa hồ sơ này?', 'Arrived': 'Đã đến', 'As of yet, no sections have been added to this template.': 'Chưa hoàn thành, không mục nào được thêm vào mẫu này', 'Assessment Answer Details': 'Nội dung câu trả lời trong mẫu đánh giá', 'Assessment Answer added': 'Câu trả lời trong mẫu đánh giá đã được thêm', 'Assessment Answer deleted': 'Câu trả lời trong mẫu đánh giá đã được xóa', 'Assessment Answer updated': 'Câu trả lời trong mẫu đánh giá đã được cập nhật', 'Assessment Answers': 'Câu trả lời trong mẫu đánh', 'Assessment Question Details': 'Nội dung câu trả hỏi trong mẫu đánh giá', 'Assessment Question added': 'Câu trả hỏi trong mẫu đánh giá đã được thêm', 'Assessment Question deleted': 'Câu trả hỏi trong mẫu đánh giá đã được xóa', 'Assessment Question updated': 'Câu trả hỏi trong mẫu đánh giá đã được cập nhật', 'Assessment Questions': 'Câu trả hỏi trong mẫu đánh', 'Assessment Template Details': 'Nội dung biểu mẫu đánh giá', 'Assessment Template added': 'Biểu mẫu đánh giá đã được thêm', 'Assessment Template deleted': 'Biểu mẫu đánh giá đã được xóa', 'Assessment Template updated': 'Biểu mẫu đánh giá đã được cập nhật', 'Assessment Templates': 'Biểu mẫu đánh giá', 'Assessment admin level': 'Cấp quản lý đánh giá', 'Assessment and Community/ Beneficiary Identification': 'Đánh giá và xác định đối tượng/ cộng đồng hưởng lợi', 'Assessment timeline': 'Khung thời gian đánh giá', 'Assessment updated': 'Đã cập nhật Trị giá tính thuế', 'Assessment': 'Đánh giá', 'Assessments': 'Đánh giá', 'Asset Details': 'Thông tin tài sản', 'Asset Log Details': 'Chi tiết nhật ký tài sản', 'Asset Log Empty': 'Xóa nhật ký tài sản', 'Asset Log Entry deleted': 'Ghi chép nhật ký tài sản đã được xóa', 'Asset Log Entry updated': 'Ghi chép nhật ký tài sản đã được cập nhật', 'Asset Log': 'Nhật ký tài sản', 'Asset Number': 'Số tài sản', 'Asset added': 'Tài sản đã được thêm', 'Asset deleted': 'Tài sản đã được xóa', 'Asset updated': 'Tài sản đã được cập nhật', 'Asset': 'Tài sản', 'Assets are resources which are not consumable but are expected back, so they need tracking.': 'Tài sản là các nguồn lực không tiêu hao và có thể được hoàn trả nên cần theo dõi tài sản', 'Assets': 'Tài sản', 'Assign Asset': 'Giao tài sản', 'Assign Human Resource': 'Phân chia nguồn nhân lực', 'Assign New Human Resource': 'Phân chia nguồn nhân lực mới', 'Assign Role to a User': 'Phân công vai trò cho người sử dụng', 'Assign Roles': 'Phân công vai trò', 'Assign Staff': 'Phân công cán bộ', 'Assign Vehicle': 'Phân công phương tiện vận chuyển', 'Assign another Role': 'Phân công vai trò khác', 'Assign to Facility/Site': 'Phân công tới Bộ phân/ Địa bàn', 'Assign to Organization': 'Phân công tới Tổ chức', 'Assign to Person': 'Phân công tới đối tượng', 'Assign': 'Phân công', 'Assigned By': 'Được phân công bởi', 'Assigned Roles': 'Vai trò được phân công', 'Assigned To': 'Được phân công tới', 'Assigned to Facility/Site': 'Được phân công tới Bộ phân/ Địa bàn', 'Assigned to Organization': 'Được phân công tới Tổ chức', 'Assigned to Person': 'Được phân công tới đối tượng', 'Assigned to': 'Được phân công tới', 'Assigned': 'Được phân công', 'Association': 'Liên hiệp', 'At or below %s': 'Tại đây hoặc phí dưới %s', 'At/Visited Location (not virtual)': 'Địa điêm ở/đã đến (không ảo)', 'Attachments': 'Đính kèm', 'Attribution': 'Quyền hạn', 'Australian Dollars': 'Đô la Úc', 'Authentication Required': 'Xác thực được yêu cầu', 'Author': 'Tác giả', 'Auxiliary Role': 'Vai trò bổ trợ', 'Availability': 'Thời gian có thể tham gia', 'Available Alternative Inventories': 'Hàng tồn kho thay thế sẵn có', 'Available Forms': 'Các mẫu có sẵn', 'Available Inventories': 'Hàng tồn kho sẵn có', 'Available databases and tables': 'Cơ sở dữ liệu và bảng biểu sẵn có', 'Available in Viewer?': 'Sẵn có để xem', 'Available until': 'Sẵn sàng cho đến khi', 'Avalanche': 'Tuyết lở', 'Average': 'Trung bình', 'Award Type': 'Hình thức khen thưởng', 'Award': 'Khen thưởng', 'Awarding Body': 'Cấp khen thưởng', 'Awards': 'Khen thưởng', 'Awareness Raising': 'Nâng cao nhận thức', 'BACK TO %(system_name_short)s': 'TRỞ LẠI %(system_name_short)s', 'BACK TO MAP VIEW': 'TRỞ LẠI XEM BẢN ĐỒ', 'BROWSE OTHER REGIONS': 'LỰA CHỌN CÁC VÙNG KHÁC', 'Baby And Child Care': 'Chăm sóc trẻ em', 'Bachelor': 'Cửa nhân', "Bachelor's Degree": 'Trung cấp, cao đẳng, đại học', 'Back to Roles List': 'Quay trở lại danh sách vai trò', 'Back to Users List': 'Quay trở lại danh sách người sử dụng', 'Back to the main screen': 'Trở lại màn hình chính', 'Back': 'Trở lại', 'Background Color': 'Màu nền', 'Baldness': 'Cây trụi lá', 'Bank/micro finance': 'Tài chính Ngân hàng', 'Base %(facility)s Set': 'Tập hợp %(facility)s nền tảng', 'Base Facility/Site Set': 'Tập hợp Bộ phận/ Địa bàn nền tảng', 'Base Layer?': 'Lớp bản đồ cơ sở?', 'Base Layers': 'Lớp bản đồ cơ sở', 'Base Location': 'Địa điểm nền tảng', 'Base URL of the remote Sahana Eden instance including application path, e.g. http://www.example.org/eden': 'Đường dẫn Cơ bản của Hệ thống Sahana Eden từ xa bao gồm đường dẫn ứng dụng như http://www.example.org/eden', 'Base Unit': 'Đơn vị cơ sở', 'Basic Details': 'Chi tiết cơ bản', 'Basic information on the requests and donations, such as category, the units, contact details and the status.': 'Thông tin cơ bản về các yêu cầu và quyên góp như thể loại, tên đơn vị, chi tiết liên lạc và tình trạng', 'Basic reports on the Shelter and drill-down by region': 'Báo cáo cơ bản về nơi cư trú và báo cáo chi tiết theo vùng', 'Baud rate to use for your modem - The default is safe for most cases': 'Tốc độ truyền sử dụng cho mô đem của bạn - Chế độ mặc định là an toàn trong hầu hết các trường hợp', 'Bed Type': 'Loại Giường', 'Behaviour Change Communication': 'Truyền thông thay đổi hành vi', 'Beneficiaries Added': 'Người hưởng lợi đã được thêm', 'Beneficiaries Deleted': 'Người hưởng lợi đã được xóa', 'Beneficiaries Details': 'Thông tin của người hưởng lợi', 'Beneficiaries Updated': 'Người hưởng lợi đã được cập nhật', 'Beneficiaries': 'Người hưởng lợi', 'Beneficiary Report': 'Báo cáo người hưởng lợi', 'Beneficiary Type Added': 'Loại người hưởng lợi đã được thêm', 'Beneficiary Type Deleted': 'Loại người hưởng lợi đã được xóa', 'Beneficiary Type Updated': 'Loại người hưởng lợi đã được cập nhật', 'Beneficiary Type': 'Đối tượng hưởng lợi', 'Beneficiary Types': 'Đối tượng hưởng lợi', 'Beneficiary of preferential treatment policy': 'Là đối tượng chính sách', 'Beneficiary': 'Người Hưởng lợi', 'Better Programming Initiative Guidance': 'Hướng dẫn sử dụng tài liệu BPI', 'Bin': 'Thẻ kho', 'Bing Layer': 'Lớp thừa', 'Biological Hazard': 'Hiểm họa sinh học', 'Biscuits': 'Bánh quy', 'Blizzard': 'Bão tuyết', 'Blocked': 'Bị chặn', 'Blood Donation and Services': 'Hiến máu và Dịch vụ về máu', 'Blood Type (AB0)': 'Nhóm máu (ABO)', 'Blowing Snow': 'Tuyết lở', 'Body Recovery Requests': 'Yêu cầu phục hồi cơ thể', 'Body Recovery': 'Phục hồi thân thể', 'Body': 'Thân thể', 'Bomb Explosion': 'Nổ bom', 'Bomb Threat': 'Nguy cơ nổ bom', 'Bomb': 'Bom', 'Border Color for Text blocks': 'Màu viền cho khối văn bản', 'Both': 'Cả hai', 'Branch Capacity Development': 'Phát triển năng lực cho Tỉnh/ thành Hội', 'Branch Organization Details': 'Thông tin tổ chức cơ sở', 'Branch Organization added': 'Tổ chức cơ sở đã được thêm', 'Branch Organization deleted': 'Tổ chức cơ sở đã được xóa', 'Branch Organization updated': 'Tổ chức cơ sở đã được cập nhật', 'Branch Organizations': 'Tổ chức cơ sở', 'Branch': 'Cơ sở', 'Branches': 'Cơ sở', 'Brand Details': 'Thông tin nhãn hiệu', 'Brand added': 'Nhãn hiệu đã được thêm', 'Brand deleted': 'Nhãn hiệu đã được xóa', 'Brand updated': 'Nhãn hiệu đã được cập nhật', 'Brand': 'Nhãn hiệu', 'Brands': 'Nhãn hiệu', 'Breakdown': 'Chi tiết theo', 'Bridge Closed': 'Cầu đã bị đóng', 'Buddhist': 'Tín đồ Phật giáo', 'Budget Updated': 'Cập nhât ngân sách', 'Budget deleted': 'Đã xóa ngân sách', 'Budget': 'Ngân sách', 'Budgets': 'Ngân sách', 'Buffer': 'Đệm', 'Bug': 'Lỗi', 'Building Collapsed': 'Nhà bị sập', 'Building Name': 'Tên tòa nhà', 'Bulk Uploader': 'Công cụ đê tải lên số lượng lớn thông tin', 'Bundle Updated': 'Cập nhật Bundle', 'Bundles': 'Bó', 'By Warehouse': 'Bằng Kho hàng', 'By Warehouse/Facility/Office': 'Bằng Kho hàng/ Bộ phận/ Văn phòng', 'By selecting this you agree that we may contact you.': 'Bằng việc lựa chọn bạn đồng ý chúng tôi có thể liên lạc với bạn', 'CBDRM': 'QLRRTHDVCĐ', 'COPY': 'Sao chép', 'CREATE': 'TẠO', 'CSS file %s not writable - unable to apply theme!': 'không viết được file CSS %s - không thể áp dụng chủ đề', 'CV': 'Quá trình công tác', 'Calculate': 'Tính toán', 'Calculation': 'Tính toán', 'Calendar': 'Lịch', 'Camp': 'Trạm/chốt tập trung', 'Can only approve 1 record at a time!': 'Chỉ có thể phê duyệt 1 hồ sơ mỗi lần', 'Can only disable 1 record at a time!': 'Chỉ có thể vô hiệu 1 hồ sơ mỗi lần', 'Can only update 1 record at a time!': 'Chỉ có thể cập nhật 1 hồ sơ mỗi lần', 'Can read PoIs either from an OpenStreetMap file (.osm) or mirror.': 'Có thể đọc PoIs từ cả định dạng file OpenStreetMap (.osm) hoặc mirror.', 'Canadian Dollars': 'Đô la Canada', 'Cancel Log Entry': 'Hủy ghi chép nhật ký', 'Cancel Shipment': 'Hủy lô hàng vận chuyển', 'Cancel editing': 'Hủy chỉnh sửa', 'Cancel': 'Hủy', 'Canceled': 'Đã hủy', 'Cannot delete whilst there are linked records. Please delete linked records first.': 'Không xóa được khi đang có bản thu liên quan.Hãy xóa bản thu trước', 'Cannot disable your own account!': 'Không thể vô hiệu tài khoản của chính bạn', 'Cannot make an Organization a branch of itself!': 'Không thể tạo ra tổ chức là tổ chức cơ sở của chính nó', 'Cannot open created OSM file!': 'Không thể mở file OSM đã tạo', 'Cannot read from file: %(filename)s': 'Không thể đọc file: %(filename)s', 'Cannot send messages if Messaging module disabled': 'Không thể gửi tin nhắn nếu chức năng nhắn tin bị tắt', 'Capacity Building of Staff': 'Xây dựng năng lực cho Cán bộ', 'Capacity Building of Volunteers': 'Xây dựng năng lực cho Tình nguyện viên', 'Capacity Building': 'Xây dựng năng lực', 'Capacity Development': 'Nâng cao năng lực', 'Capture Information on Disaster Victim groups (Tourists, Passengers, Families, etc.)': 'Nắm bắt thông tin của các nạn nhân chịu ảnh hưởng của thiên tai(Khách du lịch,Gia đình...)', 'Card number': 'Số thẻ BHXH', 'Cardiology': 'Bệnh tim mạch', 'Cases': 'Trường hợp', 'Casual Labor': 'Nhân công thời vụ', 'Catalog Details': 'Thông tin danh mục', 'Catalog Item added': 'Mặt hàng trong danh mục đã được thêm', 'Catalog Item deleted': 'Mặt hàng trong danh mục đã được xóa', 'Catalog Item updated': 'Mặt hàng trong danh mục đã được cập nhật', 'Catalog Items': 'Mặt hàng trong danh mục', 'Catalog added': 'Danh mục đã được thêm', 'Catalog deleted': 'Danh mục đã được xóa', 'Catalog updated': 'Danh mục đã được cập nhật', 'Catalog': 'Danh mục', 'Catalogs': 'Danh mục', 'Categories': 'Chủng loại', 'Category': 'Chủng loại', 'Center': 'Trung tâm', 'Certificate Catalog': 'Danh mục chứng nhận', 'Certificate Details': 'Thông tin chứng nhận', 'Certificate List': 'Danh sách chứng nhận', 'Certificate Status': 'Tình trạng của chứng nhận', 'Certificate added': 'Chứng nhận đã được thêm', 'Certificate deleted': 'Chứng nhận đã được xóa', 'Certificate updated': 'Chứng nhận đã được cập nhật', 'Certificate': 'Chứng nhận', 'Certificates': 'Chứng nhận', 'Certification Details': 'Thông tin bằng cấp', 'Certification added': 'Bằng cấp đã được thêm', 'Certification deleted': 'Bằng cấp đã được xóa', 'Certification updated': 'Bằng cấp đã được cập nhật', 'Certifications': 'Bằng cấp', 'Certifying Organization': 'Tổ chức xác nhận', 'Change Password': 'Thay đổi mật khẩu', 'Chart': 'Biểu đồ', 'Check Request': 'Kiểm tra yêu cầu', 'Check for errors in the URL, maybe the address was mistyped.': 'Kiểm tra lỗi đường dẫn URL, địa chỉ có thể bị đánh sai', 'Check if the URL is pointing to a directory instead of a webpage.': 'Kiểm tra nếu đường dẫn URL chỉ dẫn đến danh bạ chứ không phải đến trang web', 'Check outbox for the message status': 'Kiểm tra hộp thư đi để xem tình trạng thư gửi đi', 'Check this to make your search viewable by others.': 'Chọn ô này để người khác có thể xem được tìm kiếm của bạn', 'Check': 'Kiểm tra', 'Check-In': 'Đăng ký', 'Check-Out': 'Thanh toán', 'Checked': 'Đã kiểm tra', 'Checking your file...': 'Kiểm tra file của bạn', 'Checklist of Operations': 'Danh sách kiểm tra các hoạt động', 'Chemical Hazard': 'Hiểm họa óa học', 'Child (2-11)': 'Trẻ em (2-11)', 'Child Abduction Emergency': 'Tình trạng khẩn cấp về lạm dụng trẻ em', 'Children (2-5 years)': 'Trẻ em (từ 2-5 tuổi)', 'Children (< 2 years)': 'Trẻ em (dưới 2 tuổi)', 'Choose Country': 'Lựa chọn quốc gia', 'Choose File': 'Chọn file', 'Choose country': 'Lựa chọn quốc gia', 'Choose': 'Lựa chọn', 'Christian': 'Tín đồ Cơ-đốc giáo', 'Church': 'Nhà thờ', 'Circumstances of disappearance, other victims/witnesses who last saw the missing person alive.': 'Hoàn cảnh mất tích, những nhân chứng nhìn thấy lần gần đây nhất nạn nhân còn sống', 'City / Town / Village': 'Phường/ Xã', 'Civil Emergency': 'Tình trạng khẩn cấp dân sự', 'Civil Society/NGOs': 'Tổ chức xã hội/NGOs', 'Clear filter': 'Xóa', 'Clear selection': 'Xóa lựa chọn', 'Clear': 'Xóa', 'Click anywhere on the map for full functionality': 'Bấm vào vị trí bất kỳ trên bản đồ để có đầy đủ chức năng', 'Click on a marker to see the Completed Assessment Form': 'Bấm vào nút đánh dấu để xem Mẫu đánh giá đã hoàn chỉnh', 'Click on the chart to show/hide the form.': 'Bấm vào biểu đồ để hiển thị/ ẩn mẫu', 'Click on the link %(url)s to reset your password': 'Bấm vào đường dẫn %(url)s khởi tạo lại mật khẩu của bạn', 'Click on the link %(url)s to verify your email': 'Bấm vào đường dẫn %(url)s để kiểm tra địa chỉ email của bạn', 'Click to dive in to regions or rollover to see more': 'Bấm để dẫn tới vùng hoặc cuộn chuột để xem gần hơn', 'Click where you want to open Streetview': 'Bấm vào chỗ bạn muốn xem ở chế độ Đường phố', 'Climate Change Adaptation': 'Thích ứng với Biến đổi khí hậu', 'Climate Change Mitigation': 'Giảm nhẹ Biến đổi khí hậu', 'Climate Change': 'Biến đổi khí hậu', 'Clinical Laboratory': 'Phòng thí nghiệm lâm sàng', 'Close Adjustment': 'Đóng điều chỉnh', 'Close map': 'Đóng bản đồ', 'Close': 'Đóng', 'Closed': 'Đã đóng', 'Closed?': 'Đã Đóng?', 'Cluster Details': 'Thông tin nhóm', 'Cluster Distance': 'Khoảng cách các nhóm', 'Cluster Threshold': 'Ngưỡng của mỗi nhóm', 'Cluster added': 'Nhóm đã được thêm', 'Cluster deleted': 'Nhóm đã được xóa', 'Cluster updated': 'Nhóm đã được cập nhật', 'Cluster': 'Nhóm', 'Cluster(s)': 'Nhóm', 'Clusters': 'Nhóm', 'Code Share': 'Chia sẻ mã', 'Code': 'Mã', 'Cold Wave': 'Đợt lạnh', 'Collect PIN from Twitter': 'Thu thập mã PIN từ Twitter', 'Color of selected Input fields': 'Màu của trường đã được chọn', 'Column Choices (One Per Line': 'Chọn cột', 'Columns': 'Cột', 'Combined Method': 'phương pháp được kết hợp', 'Come back later. Everyone visiting this site is probably experiencing the same problem as you.': 'Quay lại sau. Mọi người ghé thăm trang này đều gặp vấn đề giống bạn.', 'Come back later.': 'Quay lại sau.', 'Comment': 'Ghi chú', 'Comments': 'Ghi chú', 'Commit Date': 'Thời điểm cam kết', 'Commit': 'Cam kết', 'Commit Status': 'Tình trạng cam kết', 'Commitment Added': 'Cam kết đã được thêm', 'Commitment Canceled': 'Cam kết đã được hủy', 'Commitment Details': 'Thông tin của cam kết', 'Commitment Item Details': 'Thông tin mặt hàng cam kết', 'Commitment Item added': 'Mặt hàng cam kết đã được thêm', 'Commitment Item deleted': 'Mặt hàng cam kết đã được xóa', 'Commitment Item updated': 'Mặt hàng cam kết đã được cập nhật', 'Commitment Items': 'Mặt hàng cam kết', 'Commitment Updated': 'Cam kết đã được cập nhật', 'Commitment': 'Cam kết', 'Commitments': 'Cam kết', 'Committed By': 'Cam kết bởi', 'Committed People': 'Người đã Cam kết', 'Committed Person Details': 'Thông tin người đã cam kết', 'Committed Person updated': 'Người cam kết đã được cập nhật', 'Committed': 'Đã Cam kết', 'Committing Organization': 'Tổ chức cam kết', 'Committing Person': 'Người đang cam Kết', 'Committing Warehouse': 'Kho hàng đang cam kết', 'Commodities Loaded': 'Hàng hóa được đưa lên xe', 'Commune Name': 'Tên xã', 'Commune': 'Phường/ Xã', 'Communicable Diseases': 'Bệnh dịch lây truyền', 'Communities': 'Địa bàn dự án', 'Community Action Planning': 'Lập kế hoạch hành động của cộng đồng', 'Community Added': 'Công đồng đã được thêm', 'Community Contacts': 'Thông tin liên hệ của cộng đồng', 'Community Deleted': 'Công đồng đã được xóa', 'Community Details': 'Thông tin về cộng đồng', 'Community Health Center': 'Trung tâm sức khỏe cộng đồng', 'Community Health': 'Chăm sóc sức khỏe cộng đồng', 'Community Member': 'Thành viên cộng đồng', 'Community Mobilisation': 'Huy động cộng đồng', 'Community Mobilization': 'Huy động cộng đồng', 'Community Organisation': 'Tổ chức cộng đồng', 'Community Organization': 'Tổ chức cộng đồng', 'Community Updated': 'Công đồng đã được cập nhật', 'Community Health': 'CSSK Cộng đồng', 'Community': 'Cộng đồng', 'Community-based DRR': 'GTRRTH dựa vào cộng đồng', 'Company': 'Công ty', 'Competency Rating Catalog': 'Danh mục xếp hạng năng lực', 'Competency Rating Details': 'Thông tin xếp hạng năng lực', 'Competency Rating added': 'Xếp hạng năng lực đã được thêm', 'Competency Rating deleted': 'Xếp hạng năng lực đã được xóa', 'Competency Rating updated': 'Xếp hạng năng lực đã được cập nhật', 'Competency Rating': 'Xếp hạng năng lực', 'Competency': 'Cấp độ thành thục', 'Complete Returns': 'Quay lại hoàn toàn', 'Complete Unit Label for e.g. meter for m.': 'Nhãn đơn vị đầy đủ. Ví dụ mét cho m.', 'Complete': 'Hoàn thành', 'Completed Assessment Form Details': 'Thông tin biểu mẫu đánh giá đã hoàn thiện', 'Completed Assessment Form deleted': 'Biểu mẫu đánh giá đã hoàn thiện đã được thêm', 'Completed Assessment Form entered': 'Biểu mẫu đánh giá đã hoàn thiện đã được nhập', 'Completed Assessment Form updated': 'Biểu mẫu đánh giá đã hoàn thiện đã được cập nhật', 'Completed Assessment Forms': 'Biểu mẫu đánh giá đã hoàn thiện', 'Completed Assessments': 'Các Đánh giá đã Hoàn thành', 'Completed': 'Hoàn thành', 'Completion Question': 'Câu hỏi hoàn thành', 'Complex Emergency': 'Tình huống khẩn cấp phức tạp', 'Complexion': 'Cục diện', 'Compose': 'Soạn thảo', 'Condition': 'Điều kiện', 'Conduct a Disaster Assessment': 'Thực hiện đánh giá thảm họa', 'Config added': 'Cấu hình đã được thêm', 'Config updated': 'Cập nhật tùy chỉnh', 'Config': 'Tùy chỉnh', 'Configs': 'Cấu hình', 'Configuration': 'Cấu hình', 'Configure Layer for this Symbology': 'Thiết lập cấu hình lớp cho biểu tượng này', 'Configure Run-time Settings': 'Thiết lập cấu hình cho cài đặt thời gian hoạt động', 'Configure connection details and authentication': 'Thiêt lập cấu hình cho thông tin kết nối và xác thực', 'Configure resources to synchronize, update methods and policies': 'Cài đặt cấu hình các nguồn lực để đồng bộ, cập nhật phương pháp và chính sách', 'Configure the default proxy server to connect to remote repositories': 'Thiết lập cấu hình cho máy chủ mặc định để kết nối tới khu vực lưu trữ từ xa', 'Configure/Monitor Synchonization': 'Thiêt lập cấu hình/ giám sát đồng bộ hóa', 'Confirm Shipment Received': 'Xác nhận lô hàng đã nhận', 'Confirm that some items were returned from a delivery to beneficiaries and they will be accepted back into stock.': 'Xác nhận một số mặt hàng đã được trả lại từ bên vận chuyển tới người hưởng lợi và các mặt hàng này sẽ được chấp thuân nhập trở lại kho.', 'Confirm that the shipment has been received by a destination which will not record the shipment directly into the system and confirmed as received.': 'Xác nhận lô hàng đã nhận đến điểm gửi mà không biên nhập lô hàng trực tiếp vào hệ thống và đã xác nhận việc nhận hàng', 'Confirmed': 'Đã xác nhận', 'Confirming Organization': 'Tổ chức xác nhận', 'Conflict Policy': 'Xung đột Chính sách', 'Construction of Transitional Shelter': 'Xây dựng nhà tạm', 'Consumable': 'Có thể tiêu dùng được', 'Contact Added': 'Thông tin liên hệ đã được thêm', 'Contact Data': 'Dữ liệu thông tin liên hệ', 'Contact Deleted': 'Thông tin liên hệ đã được xóa', 'Contact Description': 'Số điện thoại/ Email', 'Contact Details': 'Thông tin hợp đồng', 'Contact Info': 'Thông tin liên hệ', 'Contact Information Added': 'Thông tin liên hệ đã được thêm', 'Contact Information Deleted': 'Thông tin liên hệ đã được xóa', 'Contact Information Updated': 'Thông tin liên hệ đã được cập nhật', 'Contact Information': 'Thông tin liên hệ', 'Contact Method': 'Phương pháp liên hệ', 'Contact People': 'Người liên hệ', 'Contact Person': 'Người liên hệ', 'Contact Persons': 'Người liên hệ', 'Contact Updated': 'Thông tin liên hệ đã được cập nhật', 'Contact us': 'Liên hệ chúng tôi', 'Contact': 'Thông tin liên hệ', 'Contacts': 'Thông tin liên hệ', 'Contents': 'Nội dung', 'Context': 'Bối cảnh', 'Contingency/ Preparedness Planning': 'Lập kế hoạch dự phòng/ phòng ngừa', 'Contract End Date': 'Ngày kết thúc hợp đồng', 'Contributor': 'Người đóng góp', 'Controller': 'Người kiểm soát', 'Conversion Tool': 'Công cụ chuyển đổi', 'Coordinate Layer': 'Lớp điều phối', 'Coordination and Partnerships': 'Điều phối và Hợp tác', 'Copy': 'Sao chép', 'Corn': 'Ngũ cốc', 'Corporate Entity': 'Thực thể công ty', 'Could not add person record': 'Không thêm được hồ sơ cá nhân', 'Could not auto-register at the repository, please register manually.': 'Không thể đăng ký tự động vào kho dữ liệu, đề nghị đăng ký thủ công', 'Could not create record.': 'Không tạo được hồ sơ', 'Could not generate report': 'Không tạo được báo cáo', 'Could not initiate manual synchronization.': 'Không thể bắt đầu việc đồng bộ hóa thủ công', 'Count of Question': 'Số lượng câu Hỏi', 'Count': 'Số lượng', 'Countries': 'Quốc gia', 'Country Code': 'Quốc gia cấp', 'Country in': 'Quốc gia ở', 'Country is required!': 'Quốc gia bắt buộc điền!', 'Country': 'Quốc gia', 'County / District (Count)': 'Quận / Huyện (số lượng)', 'County / District': 'Quận/ Huyện', 'Course Catalog': 'Danh mục khóa tập huấn', 'Course Certificate Details': 'Thông tin chứng nhận khóa tập huấn', 'Course Certificate added': 'Chứng nhận khóa tập huấn đã được thêm', 'Course Certificate deleted': 'Chứng nhận khóa tập huấn đã được xóa', 'Course Certificate updated': 'Chứng nhận khóa tập huấn đã được cập nhật', 'Course Certificates': 'Chứng chỉ khóa học', 'Course Details': 'Thông tin khóa tập huấn', 'Course added': 'Khóa tập huấn đã được thêm', 'Course deleted': 'Khóa tập huấn đã được xóa', 'Course updated': 'Khóa tập huấn đã được cập nhật', 'Course': 'Khóa tập huấn', 'Create & manage Distribution groups to receive Alerts': 'Tạo & quản lý nhóm phân phát để nhận cảnh báo', 'Create Activity Type': 'Thêm loại hình hoạt động', 'Create Activity': 'Thêm hoạt động', 'Create Assessment Template': 'Thêm biểu mẫu đánh giá', 'Create Assessment': 'Thêm đợt đánh giá', 'Create Asset': 'Thêm tài sản', 'Create Award': 'Thêm khen thưởng', 'Create Award Type': 'Thêm hình thức khen thưởng', 'Create Beneficiary Type': 'Thêm loại người hưởng lợi', 'Create Brand': 'Thêm nhãn hàng', 'Create Catalog Item': 'Thêm mặt hàng vào danh mục', 'Create Catalog': 'Thêm danh mục', 'Create Certificate': 'Thêm chứng nhận', 'Create Cluster': 'Thêm nhóm', 'Create Community': 'Thêm cộng đồng', 'Create Competency Rating': 'Thêm xếp loại năng lực', 'Create Contact': 'Thêm liên lạc', 'Create Course': 'Thêm khóa tập huấn', 'Create Department': 'Thêm phòng/ban', 'Create Disaster Assessment': 'Thêm báo cáo đánh giá thảm họa', 'Create Facility Type': 'Thêm loại hình bộ phận', 'Create Facility': 'Thêm bộ phận', 'Create Feature Layer': 'Thêm lớp chức năng', 'Create Group Entry': 'Tạo ghi chép nhóm', 'Create Group': 'Thêm nhóm', 'Create Hazard': 'Thêm hiểm họa', 'Create Hospital': 'Thêm Bệnh viện', 'Create Incident Report': 'Thêm báo cáo sự cố', 'Create Incident': 'Thêm sự kiện', 'Create Item Category': 'Thêm loại hàng hóa', 'Create Item Pack': 'Thêm gói hàng hóa', 'Create Item': 'Tạo mặt hàng mới', 'Create Item': 'Thêm hàng hóa', 'Create Job Title': 'Thêm chức danh công việc', 'Create Job': 'Thêm công việc', 'Create Kit': 'Thêm dụng cụ', 'Create Layer': 'Thêm lớp', 'Create Location Hierarchy': 'Thêm thứ tự địa điểm', 'Create Location': 'Thêm địa điểm', 'Create Mailing List': 'Thêm danh sách gửi thư', 'Create Map Profile': 'Thêm cài đặt cấu hình bản đồ', 'Create Marker': 'Thêm công cụ đánh dấu', 'Create Member': 'Thêm hội viên', 'Create Membership Type': 'Thêm loại hội viên', 'Create Milestone': 'Thêm mốc quan trọng', 'Create National Society': 'Thêm Hội Quốc gia', 'Create Office Type': 'Thêm loại hình văn phòng mới', 'Create Office': 'Thêm văn phòng', 'Create Organization Type': 'Thêm loại hình tổ chức', 'Create Organization': 'Thêm tổ chức', 'Create PDF': 'Tạo PDF', 'Create Partner Organization': 'Thêm tổ chức đối tác', 'Create Program': 'Thêm chương trình', 'Create Project': 'Thêm dự án', 'Create Projection': 'Thêm dự đoán', 'Create Question Meta-Data': 'Thêm siêu dữ liệu câu hỏi', 'Create Report': 'Thêm báo cáo mới', 'Create Repository': 'Thêm kho chứa', 'Create Request': 'Khởi tạo yêu cầu', 'Create Resource': 'Thêm nguồn lực', 'Create Role': 'Thêm vai trò', 'Create Room': 'Thêm phòng', 'Create Sector': 'Thêm lĩnh vực', 'Create Shelter': 'Thêm Nơi cư trú mới', 'Create Skill Type': 'Thêm loại kỹ năng', 'Create Skill': 'Thêm kỹ năng', 'Create Staff Level': 'Thêm ngạch công chức', 'Create Staff Member': 'Thêm cán bộ', 'Create Status': 'Thêm trạng thái', 'Create Supplier': 'Thêm nhà cung cấp', 'Create Symbology': 'Thêm biểu tượng', 'Create Task': 'Thêm nhiệm vụ', 'Create Team': 'Tạo đội TNV', 'Create Theme': 'Thêm chủ đề', 'Create Training Event': 'Thêm khóa tập huấn', 'Create User': 'Thêm người dùng', 'Create Volunteer Cluster Position': 'Thêm vi trí của nhóm tình nguyện viên', 'Create Volunteer Cluster Type': 'Thêm loại hình nhóm tình nguyện viên', 'Create Volunteer Cluster': 'Thêm nhóm tình nguyện viên', 'Create Volunteer Role': 'Thêm vai trò của tình nguyện viên', 'Create Volunteer': 'Thêm tình nguyện viên', 'Create Warehouse': 'Thêm kho hàng', 'Create a Person': 'Thêm họ tên', 'Create a group entry in the registry.': 'Tạo ghi chép nhóm trong hồ sơ đăng ký', 'Create a new Team': 'Tạo đội TNV mới', 'Create a new facility or ensure that you have permissions for an existing facility.': 'Tạo tiện ích mới hoặc đảm bảo rằng bạn có quyền truy cập vào tiện ích sẵn có', 'Create a new organization or ensure that you have permissions for an existing organization.': 'Tạo tổ chức mới hoặc đảm bảo rằng bạn có quyền truy cập vào một tổ chức có sẵn', 'Create alert': 'Tạo cảnh báo', 'Create an Assessment Question': 'Thêm câu hỏi trong mẫu đánh giá', 'Create search': 'Thêm tìm kiếm', 'Create template': 'Tạo mẫu biểu', 'Create': 'Thêm', 'Created By': 'Tạo bởi', 'Created by': 'Tạo bởi', 'Credential Details': 'Thông tin thư ủy nhiệm', 'Credential added': 'Thư ủy nhiệm đã được thêm', 'Credential deleted': 'Thư ủy nhiệm đã được xóa', 'Credential updated': 'Thư ủy nhiệm đã được cập nhật', 'Credentialling Organization': 'Tổ chức ủy nhiệm', 'Credentials': 'Thư ủy nhiệm', 'Crime': 'Tội phạm', 'Criteria': 'Tiêu chí', 'Critical Infrastructure': 'Cở sở hạ tầng trọng yếu', 'Currency': 'Tiền tệ', 'Current Group Members': 'Nhóm thành viên hiện tại', 'Current Home Address': 'Địa chỉ nhà riêng hiện tại', 'Current Identities': 'Nhận dạng hiện tại', 'Current Location': 'Vị trí hiện tại', 'Current Memberships': 'Thành viên hiện tại', 'Current Owned By (Organization/Branch)': 'Hiện tại đang được sở hữu bởi (Tổ chức/ cơ sở)', 'Current Status': 'Trạng thái hiện tại', 'Current Twitter account': 'Tài khoản Twitter hiện tại', 'Current request': 'Yêu cầu hiện tại', 'Current response': 'Hoạt động ưng phó hiện tại', 'Current session': 'Phiên họp hiện tại', 'Current': 'Đang đề xuất', 'Currently no Certifications registered': 'Hiện tại chưa có chứng nhận nào được đăng ký', 'Currently no Course Certificates registered': 'Hiện tại chưa có chứng nhận khóa tập huấn nào được đăng ký', 'Currently no Credentials registered': 'Hiện tại chưa có thư ủy nhiệm nào được đăng ký', 'Currently no Participants registered': 'Hiện tại chưa có người tham dự nào đăng ký', 'Currently no Professional Experience entered': 'Hiện tại chưa có kinh nghiệm nghề nghiệp nào được nhập', 'Currently no Skill Equivalences registered': 'Hiện tại chưa có kỹ năng tương đương nào được đăng ký', 'Currently no Skills registered': 'Hiện tại chưa có kỹ năng nào được đăng ký', 'Currently no Trainings registered': 'Hiện tại chưa có khóa tập huấn nào được đăng ký', 'Currently no entries in the catalog': 'Hiện chưa có hồ sơ nào trong danh mục', 'Currently no hours recorded for this volunteer': 'Hiện tại chưa có thời gian hoạt động được ghi cho tình nguyện viên này', 'Currently no programmes registered': 'Hiện tại chưa có chương trình nào được đăng ký', 'Currently no staff assigned': 'Hiện tại chưa có cán bộ nào được phân công', 'Currently no training events registered': 'Hiện tại chưa có khóa tập huấn nào được đăng ký', 'Customer': 'Khách hàng', 'Customisable category of aid': 'Các tiêu chí cứu trợ có thể tùy chỉnh', 'Cyclone': 'Bão', 'DATA QUALITY': 'CHẤT LƯỢNG DỮ LIỆU', 'DATA/REPORT': 'DỮ LIỆU/BÁO CÁO', 'DECIMAL_SEPARATOR': 'Ngăn cách bằng dấu phẩy', 'DELETE': 'XÓA', 'DRR': 'GTRRTH', 'DRRPP Extensions': 'Gia hạn DRRPP', 'Daily Work': 'Công việc hàng ngày', 'Daily': 'Hàng ngày', 'Dam Overflow': 'Tràn đập', 'Damaged': 'Thiệt hại', 'Dangerous Person': 'Người nguy hiểm', 'Dashboard': 'Bảng điều khiển', 'Data Quality': 'Chất lượng Dữ liệu', 'Data Source': 'Nguồn Dữ liệu', 'Data Type': 'Loại dữ liệu', 'Data added to Theme Layer': 'Dữ liệu đã được thêm vào lớp chủ đề', 'Data import error': 'Lỗi nhập khẩu dữ liệu', 'Data uploaded': 'Dữ liệu đã được tải lên', 'Data': 'Dữ liệu', 'Data/Reports': 'Dữ liệu/Báo cáo', 'Database Development': 'Xây dựng cơ sở dữ liệu', 'Database': 'Cơ sở Dữ liệu', 'Date Available': 'Ngày rãnh rỗi', 'Date Created': 'Ngày đã được tạo', 'Date Due': 'Ngày đến hạn', 'Date Expected': 'Ngày được mong muốn', 'Date Joined': 'Ngày tham gia', 'Date Needed By': 'Ngày cần bởi', 'Date Published': 'Ngày xuất bản', 'Date Question': 'Hỏi Ngày', 'Date Range': 'Khoảng thời gian', 'Date Received': 'Ngày Nhận được', 'Date Released': 'Ngày Xuất ra', 'Date Repacked': 'Ngày Đóng gói lại', 'Date Requested': 'Ngày Đề nghị', 'Date Required Until': 'Trước Ngày Đòi hỏi ', 'Date Required': 'Ngày Đòi hỏi', 'Date Sent': 'Ngày gửi', 'Date Taken': 'Ngày Nhận được', 'Date Until': 'Trước Ngày', 'Date and Time of Goods receipt. By default shows the current time but can be modified by editing in the drop down list.': 'Ngày giờ nhận hàng hóa.Hiển thị thời gian theo mặc định nhưng vẫn có thể chỉnh sửa', 'Date and Time': 'Ngày và giờ', 'Date must be %(max)s or earlier!': 'Ngày phải %(max)s hoặc sớm hơn!', 'Date must be %(min)s or later!': 'Ngày phải %(min)s hoặc muộn hơn!', 'Date must be between %(min)s and %(max)s!': 'Ngày phải trong khoản %(min)s và %(max)s!', 'Date of Birth': 'Ngày Sinh', 'Date of Report': 'Ngày báo cáo', 'Date of adjustment': 'Điều chỉnh ngày', 'Date of submission': 'Ngày nộp', 'Date resigned': 'Ngày từ nhiệm', 'Date': 'Ngày bắt đầu', 'Date/Time of Alert': 'Ngày/Giờ Cảnh báo', 'Date/Time of Dispatch': 'Ngày/Giờ Gửi', 'Date/Time of Find': 'Ngày giờ tìm kiếm', 'Date/Time': 'Ngày/Giờ', 'Day': 'Ngày', 'De-duplicator': 'Bộ chống trùng', 'Dead Bodies': 'Các xác chết', 'Dead Body Reports': 'Báo cáo thiệt hại về người', 'Dead Body': 'Xác chết', 'Deaths/24hrs': 'Số người chết/24h', 'Deceased': 'Đã chết', 'Decimal Degrees': 'Độ âm', 'Decision': 'Quyết định', 'Decline failed': 'Thất bại trong việc giảm', 'Default Base layer?': 'Lớp bản đồ cơ sở mặc định', 'Default Location': 'Địa điểm mặc định', 'Default Marker': 'Đánh dấu mặc định', 'Default Realm = All Entities the User is a Staff Member of': 'Realm mặc định=tất cả các đơn vị, người Sử dụng là cán bộ thành viên của', 'Default Realm': 'Realm mặc định', 'Default map question': 'Câu hỏi bản đồ mặc định', 'Default synchronization policy': 'Chính sách đồng bộ hóa mặc định', 'Default': 'Mặc định', 'Defaults': 'Mặc định', 'Defines the icon used for display of features on handheld GPS.': 'Định nghĩa biểu tượng được sử dụng để miêu tả các chức năng trên máy GPS cầm tay.', 'Defines the icon used for display of features on interactive map & KML exports.': 'Định nghĩa biểu tượng được sử dụng để miêu tả các chức năng trên bản đồ tương tác và chiết xuất KML.', 'Degrees in a latitude must be between -90 to 90.': 'Giá trị vĩ độ phải trong khoảng -90 tới 90', 'Degrees in a longitude must be between -180 to 180.': 'Giá trị kinh độ phải nằm giữa -180 tới 180', 'Degrees must be a number.': 'Độ: phải hiển thị bằng số', 'Delete Affiliation': 'Xóa liên kết', 'Delete Aid Request': 'Xóa yêu cầu cứu trợ', 'Delete Alternative Item': 'Xóa mặt hàng thay thế', 'Delete Asset Log Entry': 'Xóa ghi chép nhật ký tài sản', 'Delete Asset': 'Xóa tài sản', 'Delete Branch': 'Xóa tổ chức cơ sở', 'Delete Brand': 'Xóa nhãn hiệu', 'Delete Budget': 'Xóa ngân sách', 'Delete Catalog Item': 'Xóa mặt hang trong danh mục', 'Delete Catalog': 'Xóa danh mục', 'Delete Certificate': 'Xóa chứng chỉ', 'Delete Certification': 'Xóa bằng cấp', 'Delete Cluster': 'Xóa nhóm', 'Delete Commitment Item': 'Xóa mặt hàng cam kết', 'Delete Commitment': 'Xóa cam kết', 'Delete Competency Rating': 'Xóa xếp loại năng lực', 'Delete Config': 'Xóa cấu hình', 'Delete Contact Information': 'Xóa thông tin liên hệ', 'Delete Course Certificate': 'Xóa chứng chỉ khóa học', 'Delete Course': 'Xóa khóa học', 'Delete Credential': 'Xóa thư ủy nhiệm', 'Delete Data from Theme layer': 'Xoá dữ liệu khỏi lớp chủ đề', 'Delete Department': 'Xóa phòng/ban', 'Delete Document': 'Xóa tài liệu', 'Delete Donor': 'Xóa nhà tài trợ', 'Delete Facility Type': 'Xóa loại hinh bộ phận', 'Delete Facility': 'Xóa bộ phận', 'Delete Feature Layer': 'Xóa lớp chức năng', 'Delete Group': 'Xóa nhóm', 'Delete Hazard': 'Xóa hiểm họa', 'Delete Hospital': 'Xóa Bệnh viện', 'Delete Hours': 'Xóa thời gian hoạt động', 'Delete Image': 'Xóa hình ảnh', 'Delete Incident Report': 'Xóa báo cáo sự kiện', 'Delete Inventory Store': 'Xóa kho lưu trữ', 'Delete Item Category': 'Xóa danh mục hàng hóa', 'Delete Item Pack': 'Xóa gói hàng', 'Delete Item from Request': 'Xóa mặt hàng từ yêu cầu', 'Delete Item': 'Xóa mặt hàng', 'Delete Job Role': 'Xóa vai trò công việc', 'Delete Job Title': 'Xóa chức danh', 'Delete Kit': 'Xóa dụng cụ', 'Delete Layer': 'Xóa lớp', 'Delete Location Hierarchy': 'Xóa thứ tự địa điểm', 'Delete Location': 'Xóa địa điểm', 'Delete Mailing List': 'Xóa danh sách gửi thư', 'Delete Map Profile': 'Xóa cài đặt cấu hình bản đồ', 'Delete Marker': 'Xóa công cụ đánh dấu', 'Delete Member': 'Xóa hội viên', 'Delete Membership Type': 'Xóa loại hình nhóm hội viên', 'Delete Membership': 'Xóa nhóm hội viên', 'Delete Message': 'Xóa tin nhắn', 'Delete Metadata': 'Xóa siêu dữ liệu', 'Delete National Society': 'Xóa Hội Quốc gia', 'Delete Office Type': 'Xóa loại hình văn phòng', 'Delete Office': 'Xóa văn phòng', 'Delete Order': 'Xóa đơn đặt hàng', 'Delete Organization Domain': 'Xóa lĩnh vực hoạt động của tổ chức', 'Delete Organization Type': 'Xóa loại hình tổ chức', 'Delete Organization': 'Xóa tổ chức', 'Delete Participant': 'Xóa người tham dự', 'Delete Partner Organization': 'Xóa tổ chức đối tác', 'Delete Person': 'Xóa đối tượng', 'Delete Photo': 'Xóa ảnh', 'Delete Professional Experience': 'Xóa kinh nghiệm nghề nghiệp', 'Delete Program': 'Xóa chương trình', 'Delete Project': 'Xóa dự án', 'Delete Projection': 'Xóa dự đoán', 'Delete Received Shipment': 'Xóa lô hàng đã nhận', 'Delete Record': 'Xóa hồ sơ', 'Delete Report': 'Xóa báo cáo', 'Delete Request Item': 'Xóa yêu cầu hàng hóa', 'Delete Request': 'Xóa yêu cầu', 'Delete Role': 'Xóa vai trò', 'Delete Room': 'Xóa phòng', 'Delete Sector': 'Xóa lĩnh vực', 'Delete Sent Shipment': 'Xóa lô hàng đã gửi', 'Delete Service Profile': 'Xóa hồ sơ đăng ký dịch vụ', 'Delete Shipment Item': 'Xóa mặt hàng trong lô hàng', 'Delete Skill Equivalence': 'Xóa kỹ năng tương đương', 'Delete Skill Type': 'Xóa loại kỹ năng', 'Delete Skill': 'Xóa kỹ năng', 'Delete Staff Assignment': 'Xóa phân công cho cán bộ', 'Delete Staff Member': 'Xóa cán bộ', 'Delete Status': 'Xóa tình trạng', 'Delete Stock Adjustment': 'Xóa điều chỉnh hàng lưu kho', 'Delete Supplier': 'Xóa nhà cung cấp', 'Delete Survey Question': 'Xóa câu hỏi khảo sát', 'Delete Survey Template': 'Xóa mẫu khảo sát', 'Delete Symbology': 'Xóa biểu tượng', 'Delete Theme': 'Xóa chủ đề', 'Delete Training Event': 'Xóa sự kiện tập huấn', 'Delete Training': 'Xóa tập huấn', 'Delete Unit': 'Xóa đơn vị', 'Delete User': 'Xóa người dùng', 'Delete Volunteer Cluster Position': 'Xóa vị trí nhóm tình nguyện viên', 'Delete Volunteer Cluster Type': 'Xóa loại hình nhóm tình nguyện viên', 'Delete Volunteer Cluster': 'Xóa nhóm tình nguyện viên', 'Delete Volunteer Role': 'Xóa vai trò của tình nguyện viên', 'Delete Volunteer': 'Xóa tình nguyện viên', 'Delete Warehouse': 'Xóa kho hàng', 'Delete all data of this type which the user has permission to before upload. This is designed for workflows where the data is maintained in an offline spreadsheet and uploaded just for Reads.': 'Xóa tất cả dữ liệu loại này mà người dùng có quyền truy cập trước khi tải lên. Việc này được thiết kế cho chu trình làm việc mà dữ liệu được quản lý trên excel ngoại tuyến và được tải lên chỉ để đọc.', 'Delete from Server?': 'Xóa khỏi máy chủ', 'Delete saved search': 'Xóa tìm kiếm đã lưu', 'Delete this Assessment Answer': 'Xóa câu trả lời này trong mẫu đánh giá', 'Delete this Assessment Question': 'Xóa câu hỏi này trong mẫu đánh giá', 'Delete this Assessment Template': 'Xóa biểu mẫu đánh giá này', 'Delete this Completed Assessment Form': 'Xóa biểu mẫu đánh giá đã được hoàn thiện này', 'Delete this Disaster Assessment': 'Xóa đánh giá thảm họa này', 'Delete this Question Meta-Data': 'Xóa siêu dữ liệu câu hỏi này', 'Delete this Template Section': 'Xóa nội dung này trong biểu mẫu', 'Delete': 'Xóa', 'Deliver To': 'Gửi tới', 'Delivered By': 'Được bởi', 'Delivered To': 'Đã gửi tới', 'Demographic Data Details': 'Thông tin số liệu dân số', 'Demographic Data added': 'Số liệu dân số đã được thêm', 'Demographic Data deleted': 'Số liệu dân số đã được xóa', 'Demographic Data updated': 'Số liệu dân số đã được cập nhật', 'Demographic Data': 'Số liệu dân số', 'Demographic Details': 'Thông tin dân số', 'Demographic Source Details': 'Thông tin về nguồn dữ liệu dân số', 'Demographic Sources': 'Nguồn dữ liệu dân số', 'Demographic added': 'Dữ liệu nhân khẩu đã được thêm', 'Demographic data': 'Số liệu dân số', 'Demographic deleted': 'Dữ liệu nhân khẩu đã được xóa', 'Demographic source added': 'Nguồn số liệu dân số đã được thêm', 'Demographic source deleted': 'Nguồn số liệu dân số đã được xóa', 'Demographic source updated': 'Nguồn số liệu dân số đã được cập nhật', 'Demographic updated': 'Dữ liệu nhân khẩu đã được cập nhật', 'Demographic': 'Nhân khẩu', 'Demographics': 'Nhân khẩu', 'Demonstrations': 'Trình diễn', 'Dental Examination': 'Khám nha khoa', 'Dental Profile': 'Hồ sơ khám răng', 'Department / Unit': 'Ban / Đơn vị', 'Department Catalog': 'Danh sách phòng/ban', 'Department Details': 'Thông tin phòng/ban', 'Department added': 'Phòng ban đã được thêm', 'Department deleted': 'Phòng ban đã được xóa', 'Department updated': 'Phòng ban đã được cập nhật', 'Deployment Location': 'Địa điểm điều động', 'Deployment Request': 'Yêu cầu điều động', 'Deployment': 'Triển khai', 'Describe the condition of the roads to your hospital.': 'Mô tả tình trạng các con đường tới bệnh viện.', "Describe the procedure which this record relates to (e.g. 'medical examination')": 'Mô tả qui trình liên quan tới hồ sơ này (ví dụ: "kiểm tra sức khỏe")', 'Description of Contacts': 'Mô tả thông tin mối liên lạc', 'Description of defecation area': 'Mo tả khu vực defecation', 'Description': 'Mô tả', 'Design, deploy & analyze surveys.': 'Thiết kế, triển khai và phân tích đánh giá.', 'Destination': 'Điểm đến', 'Destroyed': 'Bị phá hủy', 'Detailed Description/URL': 'Mô tả chi tiêt/URL', 'Details field is required!': 'Ô Thông tin chi tiết là bắt buộc!', 'Details of Disaster Assessment': 'Thông tin chi tiết về đánh giá thảm họa', 'Details of each question in the Template': 'Chi tiết về mỗi câu hỏi trong biểu mẫu', 'Details': 'Chi tiết', 'Dignitary Visit': 'Chuyến thăm cấp cao', 'Direction': 'Định hướng', 'Disable': 'Vô hiệu', 'Disabled': 'Đã tắt', 'Disaster Assessment Chart': 'Biểu đồ đánh giá thảm họa', 'Disaster Assessment Map': 'Bản đồ đánh giá thảm họa', 'Disaster Assessment Summary': 'Tóm tắt đánh giá thảm họa', 'Disaster Assessment added': 'Báo cáo đánh giá thảm họa đã được thêm', 'Disaster Assessment deleted': 'Báo cáo đánh giá thảm họa đã được xóa', 'Disaster Assessment updated': 'Báo cáo đánh giá thảm họa đã được cập nhật', 'Disaster Assessments': 'Đánh giá thảm họa', 'Disaster Law': 'Luật phòng, chống thiên tai', 'Disaster Risk Management': 'QLRRTH', 'Disaster Risk Reduction': 'GTRRTH', 'Disaster Victim Identification': 'Nhận dạng nạn nhân trong thảm họa', 'Disaster chemical spill/leak, explosions, collapses, gas leaks, urban fire, oil spill, technical failure': 'rò rỉ hóa học, nổ, rò khí ga, hỏa hoạn trong đô thị, tràn dầu', 'Disciplinary Action Type': 'Hình thức kỷ luật', 'Disciplinary Body': 'Cấp kỷ luật', 'Disciplinary Record': 'Kỷ luật', 'Discussion Forum': 'Diễn đàn thảo luận', 'Dispatch Time': 'Thời gian gửi đi', 'Dispatch': 'Gửi đi', 'Dispensary': 'Y tế dự phòng', 'Displaced Populations': 'Dân cư bị sơ tán', 'Display Chart': 'Hiển thị biểu đồ', 'Display Polygons?': 'Hiển thị hình đa giác?', 'Display Question on Map': 'Hiển thị câu hỏi trên bản đồ', 'Display Routes?': 'Hiển thị tuyến đường?', 'Display Selected Questions': 'Hiển thị câu hỏi được lựa chọn', 'Display Tracks?': 'Hiển thị dấu vết?', 'Display Waypoints?': 'Hiển thị các cột báo trên đường?', 'Display': 'Hiển thị', 'Distance from %s:': 'Khoảng cách từ %s:', 'Distribution Item Details': 'Chi tiết hàng hóa cứu trợ ', 'Distribution Item': 'Hàng hóa đóng góp', 'Distribution groups': 'Nhóm cấp phát', 'Distribution of Food': 'Cấp phát lương thực', 'Distribution of Non-Food Items': 'Cấp phát các mặt hàng phi lương thực', 'Distribution of Shelter Repair Kits': 'Cấp phát bộ dụng cụ sửa nhà', 'Distribution': 'Cấp phát', 'District': 'Quận/ Huyện', 'Diversifying Livelihoods': 'Đa dạng nguồn sinh kế', 'Divorced': 'Ly hôn', 'Do you really want to approve this record?': 'Bạn có thực sự muốn chấp thuân hồ sơ này không?', 'Do you really want to delete these records?': 'Bạn có thực sự muốn xóa các hồ sơ này không?', 'Do you really want to delete this record? (This action can not be reversed)': 'Bạn có thực sự muốn xóa hồ sơ này không? (Hồ sơ không thể khôi phục lại sau khi xóa)', 'Do you want to cancel this received shipment? The items will be removed from the Warehouse. This action CANNOT be undone!': 'Bạn có muốn hủy lô hàng đã nhận được này không? Hàng hóa này sẽ bị xóa khỏi Kho hàng. Dữ liệu không thể khôi phục lại sau khi xóa!', 'Do you want to cancel this sent shipment? The items will be returned to the Warehouse. This action CANNOT be undone!': 'Bạn có muốn hủy Lô hàng đã nhận được này không? Hàng hóa này sẽ được trả lại Kho hàng. Dữ liệu không thể khôi phục lại sau khi xóa!', 'Do you want to close this adjustment?': 'Bạn có muốn đóng điều chỉnh này lại?', 'Do you want to complete the return process?': 'Bạn có muốn hoàn thành quá trình trả lại hàng này?', 'Do you want to over-write the file metadata with new default values?': 'Bạn có muốn thay dữ liệu file bằng giá trị mặc định mới không?', 'Do you want to receive this shipment?': 'Bạn có muốn nhận lô hàng này?', 'Do you want to send this shipment?': 'Bạn có muốn gửi lô hàng này?', 'Document Details': 'Chi tiết tài liệu', 'Document Scan': 'Quyét Tài liệu', 'Document added': 'Tài liệu đã được thêm', 'Document deleted': 'Tài liệu đã được xóa', 'Document updated': 'Tài liệu đã được cập nhật', 'Document': 'Tài liệu', 'Documents': 'Tài liệu', 'Doing nothing (no structured activity)': 'Không làm gì (không có hoạt động theo kế hoạch', 'Domain': 'Phạm vi hoạt động', 'Domestic chores': 'Công việc nội trợ', 'Donated': 'Đã tài trợ', 'Donating Organization': 'Tổ chức tài trợ', 'Donation Phone #': 'Số điện thoại để ủng hộ', 'Donation': 'Ủng hộ', 'Donor Details': 'Thông tin nhà tài trợ', 'Donor Driven Housing Reconstruction': 'Xây lại nhà theo yêu cầu của nhà tài trợ', 'Donor added': 'Nhà tài trợ đã được thêm', 'Donor deleted': 'Nhà tài trợ đã được xóa', 'Donor updated': 'Nhà tài trợ đã được cập nhật', 'Donor': 'Nhà Tài trợ', 'Donors': 'Nhà tài trợ', 'Donor(s)': 'Nhà tài trợ', 'Donors Report': 'Báo cáo nhà tài trợ', 'Download Assessment Form Document': 'Biểu mẫu đánh giá đã dạng văn bản được tải về', 'Download Assessment Form Spreadsheet': 'Biểu mẫu đánh giá đã dạng excel được tải về', 'Download OCR-able PDF Form': 'Tải về biểu mẫu định dạng OCR-able PDF', 'Download Template': 'Tải Mẫu nhập liệu', 'Download last build': 'Tải về bộ tài liệu cập nhật nhất', 'Download': 'Tải về', 'Download.CSV formatted Template': 'Tải về biểu mẫu định dạng CSV', 'Draft Features': 'Chức năng dự thảo', 'Draft': 'Dự thảo', 'Drainage': 'Hệ thống thoát nước', 'Draw a square to limit the results to just those within the square.': 'Vẽ một ô vuông để giới hạn kết quả tìm kiếm chỉ nằm trong ô vuông đó', 'Driving License': 'Giấy phép lái xe', 'Drought': 'Hạn hán', 'Drugs': 'Thuốc', 'Due %(date)s': 'hết hạn %(date)s', 'Dug Well': 'Đào giếng', 'Dump': 'Trút xuống', 'Duplicate Locations': 'Nhân đôi các vị trí', 'Duplicate label selected': 'Nhân đôi biểu tượng đã chọn', 'Duplicate': 'Nhân đôi', 'Duration (months)': 'Khoảng thời gian (tháng)', 'Dust Storm': 'Bão cát', 'EMS Status': 'Tình trạng EMS', 'Early Warning': 'Cảnh báo sớm', 'Earthquake': 'Động đất', 'Economics of DRR': 'Tính kinh tế của GTRRTH', 'Edit Activity Type': 'Chỉnh sửa loại hình hoạt động', 'Edit Activity': 'Chỉnh sửa hoạt động', 'Edit Address': 'Chỉnh sửa địa chỉ', 'Edit Adjustment': 'Chỉnh sửa điều chỉnh', 'Edit Affiliation': 'Chỉnh sửa liên kết', 'Edit Aid Request': 'Chỉnh sửa Yêu cầu cứu trợ', 'Edit Alternative Item': 'Chỉnh sửa mặt hàng thay thê', 'Edit Annual Budget': 'Chỉnh sửa ngân sách năm', 'Edit Assessment Answer': 'Chỉnh sửa câu trả lời trong mẫu đánh giá', 'Edit Assessment Question': 'Chỉnh sửa câu trả hỏi trong mẫu đánh giá', 'Edit Assessment Template': 'Chỉnh sửa biểu mẫu đánh giá', 'Edit Assessment': 'Chỉnh sửa Đánh giá', 'Edit Asset Log Entry': 'Chỉnh sửa ghi chép nhật ký tài sản', 'Edit Asset': 'Chỉnh sửa tài sản', 'Edit Beneficiaries': 'Chỉnh sửa người hưởng lợi', 'Edit Beneficiary Type': 'Chỉnh sửa loại người hưởng lợi', 'Edit Branch Organization': 'Chỉnh sửa tổ chức cơ sở', 'Edit Brand': 'Chỉnh sửa nhãn hiệu', 'Edit Catalog Item': 'Chỉnh sửa mặt hàng trong danh mục', 'Edit Catalog': 'Chỉnh sửa danh mục hàng hóa', 'Edit Certificate': 'Chỉnh sửa chứng chỉ', 'Edit Certification': 'Chỉnh sửa bằng cấp', 'Edit Cluster': 'Chỉnh sửa nhóm', 'Edit Commitment Item': 'Chỉnh sửa mặt hàng cam kết', 'Edit Commitment': 'Chỉnh sửa cam kết', 'Edit Committed Person': 'Chỉnh sửa đối tượng cam kết', 'Edit Community Details': 'Chỉnh sửa thông tin về cộng đồng', 'Edit Competency Rating': 'Chỉnh sửa xếp hạng năng lực', 'Edit Completed Assessment Form': 'Chỉnh sửa biểu mẫu đánh giá đã hoàn thiện', 'Edit Contact Details': 'Chỉnh sửa thông tin liên hệ', 'Edit Contact Information': 'Chỉnh sửa thông tin liên hệ', 'Edit Course Certificate': 'Chỉnh sửa chứng chỉ khóa học', 'Edit Course': 'Chỉnh sửa khóa học', 'Edit Credential': 'Chỉnh sửa thư ủy nhiệm', 'Edit DRRPP Extensions': 'Chỉnh sửa gia hạn DRRPP', 'Edit Defaults': 'Chỉnh sửa mặc định', 'Edit Demographic Data': 'Chỉnh sửa số liệu dân số', 'Edit Demographic Source': 'Chỉnh sửa nguồn số liệu dân số', 'Edit Demographic': 'Chỉnh sửa dữ liệu nhân khẩu', 'Edit Department': 'Chỉnh sửa phòng/ban', 'Edit Description': 'Chỉnh sửa mô tả', 'Edit Details': 'Chỉnh sửa thông tin chi tiết', 'Edit Disaster Victims': 'Chỉnh sửa thông tin nạn nhân trong thiên tai', 'Edit Distribution': 'Chỉnh sửa Quyên góp', 'Edit Document': 'Chỉnh sửa tài liệu', 'Edit Donor': 'Chỉnh sửa nhà tài trợ', 'Edit Education Details': 'Chỉnh sửa thông tin về trình độ học vấn', 'Edit Email Settings': 'Chỉnh sửa cài đặt email', 'Edit Entry': 'Chỉnh sửa hồ sơ', 'Edit Facility Type': 'Chỉnh sửa loại hình bộ phận', 'Edit Facility': 'Chỉnh sửa bộ phận', 'Edit Feature Layer': 'Chỉnh sửa lớp chức năng', 'Edit Framework': 'Chỉnh sửa khung chương trình', 'Edit Group': 'Chỉnh sửa nhóm', 'Edit Hazard': 'Chỉnh sửa hiểm họa', 'Edit Hospital': 'Chỉnh sửa Bệnh viện', 'Edit Hours': 'Chỉnh sửa thời gian hoạt động', 'Edit Human Resource': 'Chỉnh sửa nguồn nhân lực', 'Edit Identification Report': 'Chỉnh sửa báo cáo định dạng', 'Edit Identity': 'Chỉnh sửa nhận dạng', 'Edit Image Details': 'Chỉnh sửa thông tin hình ảnh', 'Edit Image': 'Chỉnh sửa ảnh', 'Edit Incident Report': 'Chỉnh sửa báo cáo sự cố', 'Edit Incident': 'Chỉnh sửa Các sự việc xảy ra', 'Edit Item Catalog Categories': 'Chỉnh sửa danh mục hàng hóa', 'Edit Item Category': 'Chỉnh sửa danh mục hàng hóa', 'Edit Item Pack': 'Chỉnh sửa gói hàng', 'Edit Item in Request': 'Chỉnh sửa mặt hàng đang được yêu cầu', 'Edit Item': 'Chỉnh sửa mặt hàng', 'Edit Job Role': 'Chỉnh sửa chức năng nhiệm vụ', 'Edit Job Title': 'Chỉnh sửa chức danh', 'Edit Job': 'Chỉnh sửa công việc', 'Edit Key': 'Chỉnh sửa Key', 'Edit Layer': 'Chỉnh sửa lớp', 'Edit Level %d Locations?': 'Chỉnh sửa cấp độ %d địa điểm?', 'Edit Location Details': 'Chỉnh sửa chi tiết địa điểm', 'Edit Location Hierarchy': 'Chỉnh sửa thứ tự địa điểm', 'Edit Location': 'Chỉnh sửa địa điểm', 'Edit Log Entry': 'Chỉnh sửa ghi chép nhật ký', 'Edit Logged Time': 'Chỉnh sửa thời gian đăng nhập', 'Edit Mailing List': 'Chỉnh sửa danh sách gửi thư', 'Edit Map Profile': 'Chỉnh sửa cài đặt cấu hình bản đồ', 'Edit Map Services': 'Chỉnh sửa dịch vụ bản đồ', 'Edit Marker': 'Chỉnh sửa công cụ đánh dấu', 'Edit Member': 'Chỉnh sửa hội viên', 'Edit Membership Type': 'Chỉnh sửa loại hình nhóm hội viên', 'Edit Membership': 'Chỉnh sửa nhóm hội viên', 'Edit Message': 'Chỉnh sửa tin nhắn', 'Edit Messaging Settings': 'Chỉnh sửa thiết lập tin nhắn', 'Edit Metadata': 'Chỉnh sửa dữ liệu', 'Edit Milestone': 'Chỉnh sửa mốc thời gian quan trọng', 'Edit Modem Settings': 'Chỉnh sửa cài đặt Modem', 'Edit National Society': 'Chỉnh sửa Hội Quốc gia', 'Edit Office Type': 'Chỉnh sửa loại hình văn phòng', 'Edit Office': 'Chỉnh sửa văn phòng', 'Edit Options': 'Chỉnh sửa lựa chọn', 'Edit Order': 'Chỉnh sửa lệnh', 'Edit Organization Domain': 'Chỉnh sửa lĩnh vực hoạt động của tổ chức', 'Edit Organization Type': 'Chỉnh sửa loại hình tổ chức', 'Edit Organization': 'Chỉnh sửa tổ chức', 'Edit Output': 'Chỉnh sửa kết quả đầu ra', 'Edit Parser Settings': 'Chỉnh sửa cài đặt cú pháp', 'Edit Participant': 'Chỉnh sửa người tham dự', 'Edit Partner Organization': 'Chỉnh sửa tổ chức đối tác', 'Edit Peer Details': 'Chỉnh sửa chi tiết nhóm người', 'Edit Permissions for %(role)s': 'Chỉnh sửa quyền truy cập cho %(role)s', 'Edit Person Details': 'Chỉnh sửa thông tin cá nhân', 'Edit Photo': 'Chỉnh sửa ảnh', 'Edit Problem': 'Chỉnh sửa Vấn đề', 'Edit Professional Experience': 'Chỉnh sửa kinh nghiệm nghề nghiệp', 'Edit Profile Configuration': 'Chỉnh sửa định dạng hồ sơ tiểu sử', 'Edit Program': 'Chỉnh sửa chương trình', 'Edit Project Organization': 'Chỉnh sửa tổ chức thực hiện dự án', 'Edit Project': 'Chỉnh sửa dự án', 'Edit Projection': 'Chỉnh sửa dự đoán', 'Edit Question Meta-Data': 'Chỉnh sửa siêu dữ liệu câu hỏi', 'Edit Record': 'Chỉnh sửa hồ sơ', 'Edit Recovery Details': 'Chỉnh sửa chi tiết khôi phục', 'Edit Report': 'Chỉnh sửa báo cáo', 'Edit Repository Configuration': 'Chỉnh sửa định dạng lưu trữ', 'Edit Request Item': 'Chỉnh sửa yêu cầu hàng hóa', 'Edit Request': 'Chỉnh sửa yêu cầu', 'Edit Requested Skill': 'Chỉnh sửa kỹ năng được yêu cầu', 'Edit Resource Configuration': 'Chỉnh sửa định dạng nguồn', 'Edit Resource': 'Chỉnh sửa tài nguyên', 'Edit Response': 'Chỉnh sửa phản hồi', 'Edit Role': 'Chỉnh sửa vai trò', 'Edit Room': 'Chỉnh sửa phòng', 'Edit SMS Message': 'Chỉnh sửa tin nhắn SMS', 'Edit SMS Settings': 'Chỉnh sửa cài đặt tin nhắn SMS', 'Edit SMTP to SMS Settings': 'Chỉnh sửa SMTP sang cài đặt SMS', 'Edit Sector': 'Chỉnh sửa lĩnh vực', 'Edit Setting': 'Chỉnh sửa cài đặt', 'Edit Settings': 'Thay đổi thiết lập', 'Edit Shelter Service': 'Chỉnh sửa dịch vụ cư trú', 'Edit Shelter': 'Chỉnh sửa thông tin cư trú', 'Edit Shipment Item': 'Chỉnh sửa hàng hóa trong lô hàng vận chuyển', 'Edit Site': 'Chỉnh sửa thông tin trên website ', 'Edit Skill Equivalence': 'Chỉnh sửa kỹ năng tương đương', 'Edit Skill Type': 'Chỉnh sửa loại kỹ năng', 'Edit Skill': 'Chỉnh sửa kỹ năng', 'Edit Staff Assignment': 'Chỉnh sửa phân công cán bộ', 'Edit Staff Member Details': 'Chỉnh sửa thông tin chi tiết của cán bộ', 'Edit Status': 'Chỉnh sửa tình trạng', 'Edit Supplier': 'Chỉnh sửa nhà cung cấp', 'Edit Survey Answer': 'Chỉnh sửa trả lời khảo sát', 'Edit Survey Series': 'Chỉnh sửa chuỗi khảo sát', 'Edit Survey Template': 'Chỉnh sửa mẫu điều tra', 'Edit Symbology': 'Chỉnh sửa biểu tượng', 'Edit Synchronization Settings': 'Chỉnh sửa cài đặt đồng bộ hóa', 'Edit Task': 'Chỉnh sửa nhiệm vụ', 'Edit Team': 'Chỉnh sửa Đội/Nhóm', 'Edit Template Section': 'Chỉnh sửa nội dung trong biểu mẫu', 'Edit Theme Data': 'Chỉnh sửa dữ liệu chủ đề', 'Edit Theme': 'Chỉnh sửa chủ đề', 'Edit Training Event': 'Chỉnh sửa sự kiện tập huấn', 'Edit Training': 'Chỉnh sửa tập huấn', 'Edit Tropo Settings': 'Chỉnh sửa cài đặt Tropo', 'Edit Twilio Settings': 'Chỉnh sửa cài đặt Twilio', 'Edit User': 'Chỉnh sửa người sử dụng', 'Edit Vehicle Assignment': 'Chỉnh sửa phân công phương tiện vận chuyển', 'Edit Volunteer Cluster Position': 'Chỉnh sửa vị trí nhóm tình nguyện viên', 'Edit Volunteer Cluster Type': 'Chỉnh sửa loại hình nhóm tình nguyện viên', 'Edit Volunteer Cluster': 'Chỉnh sửa nhóm tình nguyện viên', 'Edit Volunteer Details': 'Chỉnh sửa thông tin tình nguyện viên', 'Edit Volunteer Registration': 'Chỉnh sửa đăng ký tình nguyện viên', 'Edit Volunteer Role': 'Chỉnh sửa vai trò tình nguyện viên', 'Edit Vulnerability Aggregated Indicator': 'Chỉnh sửa chỉ số gộp đánh giá tình trạng dễ bị tổn thương', 'Edit Vulnerability Data': 'Chỉnh sửa dữ liệu về tình trạng dễ bị tổn thương', 'Edit Vulnerability Indicator Sources': 'Chỉnh sửa nguồn chỉ số đánh giá tình trạng dễ bị tổn thương', 'Edit Vulnerability Indicator': 'Chỉnh sửa chỉ số đánh giá tình trạng dễ bị tổn thương', 'Edit Warehouse Stock': 'Chỉnh sửa hàng lưu kho', 'Edit Warehouse': 'Chỉnh sửa kho hàng', 'Edit Web API Settings': 'Chỉnh sửa Cài đặt Web API', 'Edit current record': 'Chỉnh sửa hồ sơ hiện tại', 'Edit message': 'Chỉnh sửa tin nhắn', 'Edit saved search': 'Chỉnh sửa tìm kiếm đã lưu', 'Edit the Application': 'Chỉnh sửa ứng dụng', 'Edit the OpenStreetMap data for this area': 'Chỉnh sửa dữ liệu bản đồ OpenStreetMap cho vùng này', 'Edit this Disaster Assessment': 'Chỉnh sửa báo cáo đánh giá thảm họa này', 'Edit this entry': 'Chỉnh sửa hồ sơ này', 'Edit': 'Chỉnh sửa', 'Editable?': 'Có thể chỉnh sửa', 'Education & Advocacy': 'Giáo dục và Vận động chính sách', 'Education & School Safety': 'Giáo dục và An toàn trong trường học', 'Education Details': 'Thông tin về trình độ học vấn', 'Education details added': 'Thông tin về trình độ học vấn đã được thêm', 'Education details deleted': 'Thông tin về trình độ học vấn đã được xóa', 'Education details updated': 'Thông tin về trình độ học vấn đã được cập nhật', 'Education materials received': 'Đã nhận được tài liệu, dụng cụ phục vụ học tập', 'Education materials, source': 'Dụng cụ học tập, nguồn', 'Education': 'Trình độ học vấn', 'Either a shelter or a location must be specified': 'Nhà tạm hoặc vị trí đều cần được nêu rõ', 'Either file upload or document URL required.': 'File để tải lên hoặc được dẫn tới tài liệu đều được yêu cầu.', 'Either file upload or image URL required.': 'File để tải lên hoặc được dẫn tới hình ảnh đều được yêu cầu.', 'Elevated': 'Nâng cao lên', 'Email Address to which to send SMS messages. Assumes sending to phonenumber@address': 'Địa chỉ email để gửi tin nhắn SMS. Giả định gửi đến số điện thoại', 'Email Address': 'Địa chỉ email', 'Email Details': 'Thông tin về địa chỉ email', 'Email InBox': 'Hộp thư đến trong email', 'Email Setting Details': 'Thông tin cài đặt email', 'Email Setting deleted': 'Cài đặt email đã được xóa', 'Email Settings': 'Cài đặt email', 'Email address verified, however registration is still pending approval - please wait until confirmation received.': 'Địa chỉ email đã được xác nhận, tuy nhiên đăng ký vẫn còn chờ duyệt - hãy đợi đến khi nhận được phê chuẩn', 'Email deleted': 'Email đã được xóa', 'Email settings updated': 'Cài đặt email đã được cập nhật', 'Emergency Contact': 'Thông tin liên hệ trong trường hợp khẩn cấp', 'Emergency Contacts': 'Thông tin liên hệ trong trường hợp khẩn cấp', 'Emergency Department': 'Bộ phận cấp cứu', 'Emergency Health': 'Chăm sóc sức khỏe trong tình huống khẩn cấp', 'Emergency Medical Technician': 'Nhân viên y tế EMT', 'Emergency Shelter': 'Nhà tạm trong tình huống khẩn cấp', 'Emergency Support Facility': 'Bộ phận hỗ trợ khẩn cấp', 'Emergency Support Service': 'Dịch vụ hỗ trợ khẩn cấp', 'Emergency Telecommunication': 'Truyền thông trong tình huống khẩn cấp', 'Emergency Telecommunications': 'Thông tin liên lạc trong tình huống khẩn cấp', 'Emergency contacts': 'Thông tin liên hệ khẩn cấp', 'Employment type': 'Loại hình lao động', 'Enable in Default Config?': 'Cho phép ở cấu hình mặc định?', 'Enable': 'Cho phép', 'Enable/Disable Layers': 'Kích hoạt/Tắt Layer', 'Enabled': 'Được cho phép', 'End Date': 'Ngày kết thúc', 'End date': 'Ngày kết thúc', 'Enter Completed Assessment Form': 'Nhập biểu mẫu đánh giá đã hoàn thiện', 'Enter Completed Assessment': 'Nhập báo cáo đánh giá đã hoàn thiện', 'Enter Coordinates in Deg Min Sec': 'Nhập tọa độ ở dạng Độ,Phút,Giây', 'Enter a name for the spreadsheet you are uploading (mandatory).': 'Nhập tên cho bảng tính bạn đang tải lên(bắt buộc)', 'Enter a new support request.': 'Nhập một yêu cầu hỗ trợ mới', 'Enter a summary of the request here.': 'Nhập tóm tắt các yêu cầu ở đây', 'Enter a valid email': 'Nhập địa chỉ email có giá trị', 'Enter a value carefully without spelling mistakes, this field will be crosschecked.': 'Nhập giá trị cẩn thận tránh các lỗi chính tả, nội dung này sẽ được kiểm tra chéo', 'Enter indicator ratings': 'Nhập xếp hạng chỉ số', 'Enter keywords': 'Từ khóa tìm kiếm', 'Enter some characters to bring up a list of possible matches': 'Nhập một vài ký tự để hiện ra danh sách có sẵn', 'Enter the same password as above': 'Nhập lại mật khẩu giống như trên', 'Enter your first name': 'Nhập tên của bạn', 'Enter your organization': 'Nhập tên tổ chức của bạn', 'Entering a phone number is optional, but doing so allows you to subscribe to receive SMS messages.': 'Nhập số điện thoại là không bắt buộc, tuy nhiên nếu nhập số điện thoại bạn sẽ có thể nhận được các tin nhắn', 'Entity': 'Pháp nhân', 'Entry added to Asset Log': 'Ghi chép đã được thêm vào nhật ký tài sản', 'Environment': 'Môi trường', 'Epidemic': 'Dịch bệnh', 'Epidemic/Pandemic Preparedness': 'Phòng dịch', 'Error File missing': 'Lỗi không tìm thấy file', 'Error in message': 'Lỗi trong tin nhắn', "Error logs for '%(app)s'": "Báo cáo lỗi cho '%(app)s'", 'Errors': 'Lỗi', 'Essential Staff?': 'Cán bộ Chủ chốt?', 'Estimated # of households who are affected by the emergency': 'Ước tính # số hộ chịu ảnh hưởng từ thiên tai', 'Estimated Delivery Date': 'Thời gian giao hàng dự kiến', 'Estimated Value per Pack': 'Giá trị dự tính mỗi gói', 'Ethnicity': 'Dân tộc', 'Euros': 'Đồng Euro', 'Evaluate the information in this message. (This value SHOULD NOT be used in public warning applications.)': 'Đánh giá thông tin trong thư. (giá trị này KHÔNG NÊN sử dụng trong các ứng dụng cảnh báo công cộng)', 'Event Type': 'Loại Sự kiện', 'Event type': 'Loại sự kiện ', 'Events': 'Sự kiện', 'Example': 'Ví dụ', 'Excellent': 'Tuyệt vời', 'Excreta Disposal': 'Xử lý phân', 'Expected Out': 'Theo dự kiến', 'Experience': 'Kinh nghiệm', 'Expiration Date': 'Ngày hết hạn', 'Expiration Details': 'Thông tin về hết hạn', 'Expiration Report': 'Báo cáo hết hạn', 'Expired': 'Đã hết hạn', 'Expiring Staff Contracts Report': 'Hợp đồng lao động sắp hết hạn', 'Expiry (months)': 'Hết hạn (tháng)', 'Expiry Date': 'Ngày hết hạn', 'Expiry Date/Time': 'Ngày/Giờ hết hạn', 'Expiry Time': 'Hạn sử dụng ', 'Explanation about this view': 'Giải thích về quan điểm này', 'Explosive Hazard': 'Hiểm họa cháy nổ', 'Export Data': 'Xuất dữ liệu', 'Export all Completed Assessment Data': 'Chiết xuất toàn bộ dữ liệu đánh giá đã hoàn thiện', 'Export as Pootle (.po) file (Excel (.xls) is default)': 'Chiết xuất định dạng file Pootle (.po) (định dạng excel là mặc định)', 'Export as': 'Chiết suất tới', 'Export in EDXL-HAVE format': 'Chiết suất ra định dạng EDXL-HAVE ', 'Export in GPX format': 'Chiết xuất định dạng file GPX', 'Export in HAVE format': 'Chiết suất định dạng HAVE', 'Export in KML format': 'Chiết suất định dạng KML', 'Export in OSM format': 'Chiết xuất định dạng OSM', 'Export in PDF format': 'Chiết suất định dạng PDF', 'Export in RSS format': 'Chiết suất định dạng RSS', 'Export in XLS format': 'Chiết suất định dạng XLS', 'Export to': 'Chiết suất tới', 'Eye Color': 'Màu mắt', 'FAIR': 'CÔNG BẰNG', 'FROM': 'TỪ', 'Facial hair, color': 'Màu râu', 'Facial hair, length': 'Độ dài râu', 'Facial hair, type': 'Kiểu râu', 'Facilities': 'Bộ phận', 'Facility Contact': 'Thông tin liên hệ của bộ phận', 'Facility Details': 'Thông tin về bộ phận', 'Facility Type Details': 'Thông tin về loại hình bộ phận', 'Facility Type added': 'Loại hình bộ phận đã được thêm', 'Facility Type deleted': 'Loại hình bộ phận đã được xóa', 'Facility Type updated': 'Loại hình bộ phận đã được cập nhật', 'Facility Types': 'Loại hình bộ phận', 'Facility added': 'Bộ phận đã được thêm', 'Facility deleted': 'Bộ phận đã được xóa', 'Facility updated': 'Bộ phận đã được cập nhật', 'Facility': 'Bộ phận', 'Fail': 'Thất bại', 'Failed to approve': 'Không phê duyệt thành công', 'Fair': 'công bằng', 'Falling Object Hazard': 'Hiểm họa vật thể rơi từ trên cao', 'Family': 'Gia đình', 'Family/friends': 'Gia đình/Bạn bè', 'Feature Info': 'Thông tin chức năng', 'Feature Layer Details': 'Thông tin về lớp chức năng', 'Feature Layer added': 'Lớp chức năng đã được thêm', 'Feature Layer deleted': 'Lớp chức năng đã được xóa', 'Feature Layer updated': 'Lớp chức năng đã được cập nhật', 'Feature Layer': 'Lớp Chức năng', 'Feature Layers': 'Lớp Chức năng', 'Feature Namespace': 'Vùng tên chức năng', 'Feature Request': 'Yêu cầu chức năng', 'Feature Type': 'Loại chức năng', 'Features Include': 'Chức năng bao gồm', 'Feedback': 'Phản hồi', 'Female headed households': 'Phụ nữ đảm đương công việc nội trợ', 'Female': 'Nữ', 'Few': 'Một vài', 'File Uploaded': 'File đã được tải lên', 'File uploaded': 'File đã được tải lên', 'Fill out online below or ': 'Điền thông tin trực tuyến vào phía dưới hoặc', 'Filter Field': 'Ô lọc thông tin', 'Filter Options': 'Lựa chọn lọc', 'Filter Value': 'Giá trị lọc', 'Filter by Category': 'Lọc theo danh mục', 'Filter by Country': 'Lọc theo quốc gia', 'Filter by Organization': 'Lọc theo tổ chức', 'Filter by Status': 'Lọc theo tình trạng', 'Filter type ': 'Hình thức lọc', 'Filter': 'Bộ lọc', 'Financial System Development': 'Xây dựng hệ thống tài chính', 'Find Recovery Report': 'Tìm Báo cáo phục hồi', 'Find by Name': 'Tìm theo tên', 'Find': 'Tìm', 'Fingerprint': 'Vân tay', 'Fingerprinting': 'Dấu vân tay', 'Fire Station': 'Trạm chữa cháy', 'Fire Stations': 'Trạm chữa cháy', 'Fire': 'Hỏa hoạn', 'First Name': 'Tên', 'First': 'Trang đầu', 'Flash Flood': 'Lũ Quét', 'Flash Freeze': 'Lạnh cóng đột ngột', 'Flood Alerts': 'Báo động lũ', 'Flood Report Details': 'Chi tiết báo cáo tình hình lũ lụt', 'Flood Report added': 'Báo cáo lũ lụt đã được thêm', 'Flood Report updated': 'Đã cập nhật báo cáo tình hình lũ lụt ', 'Flood': 'Lũ lụt', 'Focal Point': 'Tiêu điểm', 'Fog': 'Sương mù', 'Food Security': 'An ninh lương thực', 'Food': 'Thực phẩm', 'For Entity': 'Đối với đơn vị', 'For POP-3 this is usually 110 (995 for SSL), for IMAP this is usually 143 (993 for IMAP).': 'Đối với POP-3 thường sử dụng 110 (995 cho SSL), đối với IMAP thường sử dụng 143 (993 cho IMAP).', 'For each sync partner, there is a default sync job that runs after a specified interval of time. You can also set up more sync jobs which could be customized on your needs. Click the link on the right to get started.': 'Đối với mỗi đối tác đồng bộ, có một công việc đồng bộ mặc định chạy sau một khoảng thời gian nhất định. Bạn cũng có thể thiết lập thêm công việc đồng bộ hơn nữa để có thể tùy biến theo nhu cầu. Nhấp vào liên kết bên phải để bắt đầu', 'For live help from the Sahana community on using this application, go to': 'Để được giúp đỡ trực tuyến từ cộng đồng Sahana về sử dụng phần mềm ứng dụng, mời đến', 'For more details on the Sahana Eden system, see the': 'Chi tiết hệ thống Sahana Eden xem tại', 'Forest Fire': 'Cháy rừng', 'Form Settings': 'Cài đặt biểu mẫu', 'Formal camp': 'Trại chính thức', 'Format': 'Định dạng', 'Found': 'Tìm thấy', 'Framework added': 'Khung chương trình đã được thêm', 'Framework deleted': 'Khung chương trình đã được xóa', 'Framework updated': 'Khung chương trình đã được cập nhật', 'Framework': 'Khung chương trình', 'Frameworks': 'Khung chương trình', 'Freezing Drizzle': 'Mưa bụi lạnh cóng', 'Freezing Rain': 'Mưa lạnh cóng', 'Freezing Spray': 'Mùa phùn lạnh cóng', 'Frequency': 'Tần suất', 'From Facility': 'Từ bộ phận', 'From Warehouse/Facility/Office': 'Từ Kho hàng/Bộ phận/Văn phòng', 'From': 'Từ', 'Frost': 'Băng giá', 'Fulfil. Status': 'Điền đầy đủ tình trạng', 'Full beard': 'Râu rậm', 'Full-time': 'Chuyên trách', 'Fullscreen Map': 'Bản đồ cỡ lớn', 'Function Permissions': 'Chức năng cho phép', 'Function for Value': 'Chức năng cho giá trị', 'Function': 'Chức năng', 'Functions available': 'Chức năng sẵn có', 'Funding Report': 'Báo cáo tài trợ', 'Funding': 'Kinh phí', 'Fundraising, income generation, in-kind support, partnership': 'Gây quỹ, tạo thu nhập, hỗ trợ bằng hiện vật, hợp tác', 'Funds Contributed by this Organization': 'Tài trợ đóng góp bởi tổ chức này', 'Funds Contributed': 'Kinh phí được tài trợ', 'GIS & Mapping': 'GIS & Lập bản đồ', 'GO TO ANALYSIS': 'ĐẾN MỤC PHÂN TÍCH', 'GO TO THE REGION': 'ĐẾN KHU VỰC', 'GPS Data': 'Dữ liệu GPS', 'GPS Marker': 'Dụng cụ đánh dấu GPS', 'GPS Track File': 'File vẽ GPS', 'GPS Track': 'Đường vẽ GPS', 'GPX Layer': 'Lớp GPX', 'Gale Wind': 'Gió mạnh', 'Gap Analysis Map': 'Bản đồ phân tích thiếu hụt', 'Gap Analysis Report': 'Báo cáo phân tích thiếu hụt', 'Gauges': 'Máy đo', 'Gender': 'Giới', 'Generate portable application': 'Tạo ứng dụng cầm tay', 'Generator': 'Bộ sinh', 'GeoJSON Layer': 'Lớp GeoJSON', 'GeoRSS Layer': 'Lớp GeoRSS', 'Geocoder Selection': 'Lựa chọn các mã địa lý', 'Geometry Name': 'Tên trúc hình', 'Get Feature Info': 'Lấy thông tin về chức năng', 'Give a brief description of the image, e.g. what can be seen where on the picture (optional).': 'Đưa ra chú thích hình ảnh ngắn gọn, vd: có thể xem gì ở đâu trên bức hình này (không bắt buộc).', 'Global Messaging Settings': 'Cài đặt hộp thư tin nhắn toàn cầu', 'Go to Functional Map': 'Tới bản đồ chức năng', 'Go to Request': 'Đến mục yêu cầu', 'Go to the': 'Đến', 'Go': 'Thực hiện', 'Goatee': 'Chòm râu dê', 'Good Condition': 'Điều kiện tốt', 'Good': 'Tốt', 'Goods Received Note': 'Giấy nhận Hàng hóa', 'Google Layer': 'Lớp Google', 'Governance': 'Quản lý nhà nước', 'Grade Code': 'Bậc lương', 'Grade': 'Tốt nghiệp hạng', 'Graduate': 'Đại học', 'Graph': 'Đường vẽ', 'Great British Pounds': 'Bảng Anh', 'Greater than 10 matches. Please refine search further': 'Tìm thấy nhiều hơn 10 kết quả. Hãy nhập lại từ khóa', 'Grid': 'Hiển thị dạng lưới', 'Group Description': 'Mô tả về nhóm', 'Group Details': 'Thông tin về nhóm', 'Group Head': 'Trưởng Nhóm', 'Group Members': 'Thành viên Nhóm', 'Group Memberships': 'Hội viên nhóm', 'Group Name': 'Tên nhóm', 'Group Type': 'Loại hình nhóm', 'Group added': 'Nhóm đã được thêm', 'Group deleted': 'Nhóm đã được xóa', 'Group description': 'Mô tả Nhóm', 'Group type': 'Loại nhóm', 'Group updated': 'Nhóm đã được cập nhật', 'Group': 'Nhóm', 'Grouped by': 'Nhóm theo', 'Groups': 'Nhóm', 'Guide': 'Hướng dẫn', 'HFA Priorities': 'Ưu tiên HFA', 'HFA1: Ensure that disaster risk reduction is a national and a local priority with a strong institutional basis for implementation.': 'HFA1: Đảm bảo rằng giảm thiểu rủi ro thảm họa là ưu tiên quốc gia và địa phương với một nền tảng tổ chức mạnh mễ để thực hiện hoạt động', 'HFA2: Identify, assess and monitor disaster risks and enhance early warning.': 'HFA2: Xác định, đánh giá và giám sát rủi ro thảm họa và tăng cường cảnh báo sớm.', 'HFA3: Use knowledge, innovation and education to build a culture of safety and resilience at all levels.': 'HFA3: Sử dụng kiến thức, sáng kiến và tập huấn để xây dựng cộng đồng an toàn ở mọi cấp.', 'HFA4: Reduce the underlying risk factors.': 'HFA4: Giảm các yếu tố rủi ro gốc rễ', 'HFA5: Strengthen disaster preparedness for effective response at all levels.': 'HFA5: Tăng cường phòng ngừa thảm họa để đảm bảo ứng phó hiệu quả ở mọi cấp.', 'HIGH RESILIENCE': 'MỨC ĐỘ AN TOÀN CAO', 'HIGH': 'CAO', 'Hail': 'Mưa đá', 'Hair Color': 'Màu tóc', 'Hair Length': 'Độ dài tóc', 'Hair Style': 'Kiểu tóc', 'Has the %(GRN)s (%(GRN_name)s) form been completed?': 'Mẫu %(GRN)s (%(GRN_name)s) đã được hoàn thành chưa?', 'Has the Certificate for receipt of the shipment been given to the sender?': 'Chứng nhận đã nhận được lô hàng đã gửi đến người gửi chưa?', 'Hazard Details': 'Thông tin vê hiểm họa', 'Hazard Points': 'Điểm hiểm họa', 'Hazard added': 'Hiểm họa đã được thêm', 'Hazard deleted': 'Hiểm họa đã được xóa', 'Hazard updated': 'Hiểm họa đã được cập nhật', 'Hazard': 'Hiểm họa', 'Hazardous Material': 'Vật liệu nguy hiểm', 'Hazardous Road Conditions': 'Điều kiện đường xá nguy hiểm', 'Hazards': 'Hiểm họa', 'Header Background': 'Nền vùng trên', 'Health & Health Facilities': 'CSSK & Cơ sở CSSK', 'Health Insurance': 'Bảo hiểm y tế', 'Health center': 'Trung tâm y tế', #'Health': 'Sức khỏe', 'Health': 'CSSK', 'Heat Wave': 'Đợt nắng nóng kéo dài', 'Heat and Humidity': 'Nóng và ẩm', 'Height (cm)': 'Chiều cao (cm)', 'Height (m)': 'Chiều cao (m)', 'Height': 'Chiều cao', 'Help': 'Trợ giúp', 'Helps to monitor status of hospitals': 'Hỗ trợ giám sát trạng thái các bệnh viện', 'Helps to report and search for Missing Persons': 'Hỗ trợ báo cáo và tìm kếm những người mất tích', 'Hide Chart': 'Ẩn biểu đồ', 'Hide Pivot Table': 'Ẩn Pivot Table', 'Hide Table': 'Ẩn bảng', 'Hide': 'Ẩn', 'Hierarchy Level 1 Name (e.g. State or Province)': 'Hệ thống tên cấp 1 (ví dụ Bang hay Tỉnh)', 'Hierarchy Level 2 Name (e.g. District or County)': 'Hệ thống tên cấp 2 (ví dụ Huyện hay thị xã)', 'Hierarchy Level 3 Name (e.g. City / Town / Village)': 'Hệ thống tên cấp 3 (ví dụ Thành phố/thị trấn/xã)', 'Hierarchy Level 4 Name (e.g. Neighbourhood)': 'Hệ thống tên cấp 4 (ví dụ xóm làng)', 'Hierarchy Level 5 Name': 'Hệ thống tên cấp 5', 'Hierarchy': 'Thứ tự', 'High School': 'Phổ thông', 'High Water': 'Nước Cao', 'High': 'Cao', 'Hindu': 'Người theo đạo Hindu', 'History': 'Lịch sử', 'Hit the back button on your browser to try again.': 'Bấm nút trở lại trên màn hình để thử lại', 'Home Address': 'Địa chỉ nhà riêng', 'Home Country': 'Bản quốc', 'Home Crime': 'Tội ác tại nhà', 'Home Phone': 'Điện thoại nhà riêng', 'Home Town': 'Nguyên quán', 'Home': 'Trang chủ', 'Hospital Details': 'Chi tiết thông tin bệnh viện', 'Hospital Status Report': 'Báo cáo tình trạng bệnh viện', 'Hospital information added': 'Đã thêm thông tin Bệnh viện', 'Hospital information deleted': 'Đã xóa thông tin bệnh viện', 'Hospital information updated': 'Đã cập nhật thông tin bệnh viện', 'Hospital status assessment.': 'Đánh giá trạng thái bệnh viện', 'Hospital': 'Bệnh viện', 'Hospitals': 'Bệnh viện', 'Host National Society': 'Hội QG chủ nhà', 'Host': 'Chủ nhà', 'Hot Spot': 'Điểm Nóng', 'Hour': 'Thời gian', 'Hourly': 'Theo giờ', 'Hours Details': 'Thông tin về thời gian hoạt động', 'Hours Model': 'Chuyên trách/ kiêm nhiệm', 'Hours added': 'Thời gian hoạt động đã được thêm', 'Hours by Program Report': 'Thời gian hoạt động theo chương trình', 'Hours by Role Report': 'Thời gian hoạt động theo vai trò', 'Hours deleted': 'Thời gian hoạt động đã được xóa', 'Hours updated': 'Thời gian hoạt động đã được cập nhật', 'Hours': 'Thời gian hoạt động', 'Households below %(br)s poverty line': 'Hộ gia đình dưới %(br)s mức nghèo', 'Households below poverty line': 'Hộ gia đình dưới mức nghèo', 'Households': 'Hộ gia đình', 'Housing Repair & Retrofitting': 'Sửa chữa và cải tạo nhà', 'How data shall be transferred': 'Dữ liệu sẽ được chuyển giao như thế nào', 'How local records shall be updated': 'Hồ sơ địa phương sẽ được cập nhật thế nào', 'How many Boys (0-17 yrs) are Injured due to the crisis': 'Đối tượng nam trong độ tuổi 0-17 bị thương trong thiên tai', 'How many Boys (0-17 yrs) are Missing due to the crisis': 'Có bao nhiêu bé trai (0 đến 17 tuổi) bị mất tích do thiên tai', 'How many Girls (0-17 yrs) are Injured due to the crisis': 'Đối tượng nữ từ 0-17 tuổi bị thương trong thiên tai', 'How many Men (18 yrs+) are Dead due to the crisis': 'Bao nhiêu người (trên 18 tuổi) chết trong thảm họa', 'How many Men (18 yrs+) are Missing due to the crisis': 'Đối tượng nam 18 tuổi trở lên mất tích trong thiên tai', 'How many Women (18 yrs+) are Dead due to the crisis': 'Đối tượng nữ từ 18 tuổi trở lên thiệt mạng trong thiên tai', 'How many Women (18 yrs+) are Injured due to the crisis': 'Số nạn nhân là nữ trên 18 tuổi chịu ảnh hưởng của cuộc khủng hoảng', 'How much detail is seen. A high Zoom level means lot of detail, but not a wide area. A low Zoom level means seeing a wide area, but not a high level of detail.': 'Mức độ chi tiết có thể xem. Mức phóng to cao có thể xem được nhiều chi tiết, nhưng không xem được diện tích rộng. Mức Phóng thấp có thể xem được diện tích rộng, nhưng không xem được nhiều chi tiết.', 'How often you want to be notified. If there are no changes, no notification will be sent.': 'Mức độ thường xuyên bạn muốn nhận thông báo. Nếu không có thay đổi, bạn sẽ không nhận được thông báo.', 'How you want to be notified.': 'Bạn muốn được thông báo như thế nào.', 'Human Resource Assignment updated': 'Phân bổ nguồn nhân lực đã được cập nhật', 'Human Resource Assignments': 'Phân bổ nguồn nhân lực', 'Human Resource Details': 'Thông tin về nguồn nhân lực', 'Human Resource assigned': 'Nguồn nhân lực được phân bổ', 'Human Resource Development': 'Phát triển nguồn nhân lực', 'Human Resource unassigned': 'Nguồn nhân lực chưa được phân bổ', 'Human Resource': 'Nguồn Nhân lực', 'Human Resources': 'Nguồn Nhân lực', 'Hurricane Force Wind': 'Gió mạnh cấp bão lốc', 'Hurricane': 'Bão lốc', 'Hygiene Promotion': 'Tăng cường vệ sinh', 'Hygiene kits, source': 'Dụng cụ vệ sinh, nguồn', 'I accept. Create my account.': 'Tôi đồng ý. Tạo tài khoản của tôi', 'ICONS': 'BIỂU TƯỢNG', 'ID Card Number': 'Số Chứng mính thư nhân dân', 'ID Number': 'Số CMT/ Hộ chiếủ', 'ID Tag Number': 'Số nhận dạng thẻ', 'ID Type': 'Loại giấy tờ nhận dạng', 'ID': 'Thông tin nhận dạng', 'IEC Materials': 'Tài liệu tuyên truyền', 'INDICATOR RATINGS': 'XẾP LOẠI CHỈ SỐ', 'INDICATORS': 'CHỈ SỐ', 'Ice Pressure': 'Sức ép băng tuyết', 'Iceberg': 'Tảng băng', 'Identification label of the Storage bin.': 'Nhãn xác định Bin lưu trữ', 'Identifier Name for your Twilio Account.': 'Xác định tên trong tài khoản Twilio của bạn', 'Identifier which the repository identifies itself with when sending synchronization requests.': 'Xác định danh mục lưu trữ nào cần được yêu cầu đồng bộ hóa', 'Identities': 'Các Chứng minh', 'Identity Details': 'Chi tiết Chứng minh', 'Identity added': 'Thêm Chứng minh', 'Identity deleted': 'Xóa Chứng minh', 'Identity updated': 'Cập nhất Chứng minh', 'Identity': 'Chứng minh ND', 'If a ticket was issued then please provide the Ticket ID.': 'Nếu vé đã được cấp, vui lòng cung cấp mã vé', 'If a user verifies that they own an Email Address with this domain, the Approver field is used to determine whether & by whom further approval is required.': 'Nếu người dùng xác nhận rằng họ sở hữu địa chỉ email với miền này, ô Người phê duyệt sẽ được sử dụng để xác định xem liệu có cần thiết phải có phê duyệt và phê duyệt của ai.', 'If checked, the notification will contain all modified records. If not checked, a notification will be send for each modified record.': 'Nếu chọn, thông báo sẽ bao gồm toàn bộ hồ sơ được chỉnh sửa. Nếu không chọn, thông báo sẽ được gửi mỗi khi có hồ sơ được chỉnh sửa', 'If it is a URL leading to HTML, then this will downloaded.': 'Nếu đó là đường dẫn URL dẫn đến trang HTML, thì sẽ được tải xuống', 'If neither are defined, then the Default Marker is used.': 'Nếu cả hai đều không được xác định, thì đánh dấu mặc định sẽ được sử dụng.', 'If none are selected, then all are searched.': 'Nếu không chọn gì, thì sẽ tìm kiếm tất cả.', 'If not found, you can have a new location created.': 'Nếu không tìm thấy, bạn có thể tạo địa điểm mới.', 'If the location is a geographic area, then state at what level here.': 'Nếu địa điểm là một vùng địa lý thì cần nêu rõ là cấp độ nào ở đây.', 'If the person counts as essential staff when evacuating all non-essential staff.': 'Nếu người đó là cán bộ chủ chốt khi đó sẽ sơ tán mọi cán bộ không quan trọng.', 'If the request is for %s, please enter the details on the next screen.': 'Nếu yêu cầu là %s thì xin mời nhập các chi tiết vào trang tiếp theo.', 'If the request type is "Other", please enter request details here.': "Nếu loại yêu cầu là 'Khác', xin nhập chi tiết của yêu cầu ở đây.", 'If this field is populated then a user with the Domain specified will automatically be assigned as a Staff of this Organization': 'Nếu trường này đã nhiều người khi đó người dùng có chức năng tổ chức sẽ được tự động phân bổ như là Cán bộ của tổ chức.', 'If this is set to True then mails will be deleted from the server after downloading.': 'Nếu đã được xác định là Đúng thư sau đó sẽ bị xóa khỏi máy chủ sau khi tải về', 'If this record should be restricted then select which role is required to access the record here.': 'Nếu hồ sơ này cần bị hạn chế truy cập, lựa chọn ở đây chức năng nào có thể truy cập vào hồ sơ này ', 'If this record should be restricted then select which role(s) are permitted to access the record here.': 'Nếu hồ sơ này cần bị hạn chế truy cập, lựa chọn ở đây những chức năng nào được quyền truy cập vào hồ sơ này ', 'If yes, specify what and by whom': 'Nếu có, hãy ghi rõ đã chỉnh sửa những gì và chỉnh sửa', 'If yes, which and how': 'nếu có thì cái nào và như thế nào', 'If you need to add a new document then you can click here to attach one.': 'Nếu cần thêm một tài liệu mới, nhấn vào đây để đính kèm', 'If you want several values, then separate with': 'Nếu bạn muốn nhiều giá trị, thì tách rời với', 'If you would like to help, then please %(sign_up_now)s': 'Nếu bạn muốn giúp đỡ, thì xin mời %(đăng ký bây giờ)s', 'If you would like to help, then please': 'Vui lòng giúp đỡ nếu bạn muốn', 'Ignore Errors?': 'Bỏ qua lỗi?', 'Illegal Immigrant': 'Người nhập cư bất hợp pháp', 'Image Details': 'Chi tiết hình ảnh', 'Image File(s), one image per page': 'Tệp hình ảnh, một hình ảnh trên một trang', 'Image Type': 'Loại hình ảnh', 'Image added': 'Thêm hình ảnh', 'Image deleted': 'Xóa hình ảnh', 'Image updated': 'Cập nhật hình ảnh', 'Image': 'Hình ảnh', 'Image/Attachment': 'Ảnh/ tệp đính kèm', 'Images': 'Các hình ảnh', 'Impact Assessments': 'Đánh giá tác động', 'Import Activity Data': 'Nhập khẩu dữ liệu hoạt động', 'Import Annual Budget data': 'Nhập khẩu dữ liệu ngân sách hàng năm', 'Import Assets': 'Nhập khẩu dữ liệu tài sản', 'Import Branch Organizations': 'Nhập khẩu dữ liệu về Tỉnh/thành Hội', 'Import Certificates': 'Nhập khẩu dữ liệu về chứng chỉ tập huấn', 'Import Community Data': 'Nhập khẩu dữ liệu cộng đồng', 'Import Completed Assessment Forms': 'Nhập khẩu biểu mẫu đánh giá đã hoàn chỉnh', 'Import Courses': 'Nhập khẩu dữ liệu về khóa tập huấn', 'Import Data for Theme Layer': 'Nhập khảu dữ liệu cho lớp chủ đề', 'Import Demographic Data': 'Nhập khẩu số liệu dân số', 'Import Demographic Sources': 'Nhập khẩu nguồn số liệu dân số', 'Import Demographic': 'Nhập khẩu dữ liệu nhân khẩu', 'Import Demographics': 'Tải dữ liệu dân số', 'Import Departments': 'Nhập khẩu dữ liệu phòng/ban', 'Import Facilities': 'Nhập khẩu bộ phận', 'Import Facility Types': 'Nhập khẩu loại hình bộ phận', 'Import File': 'Nhập khẩu File', 'Import Framework data': 'Nhập khẩu dữ liệu về khung chương trình', 'Import Hazards': 'Nhập khẩu hiểm họa', 'Import Hours': 'Nhập khẩu thời gian hoạt động', 'Import Incident Reports from Ushahidi': 'Nhập khẩu báo cáo sự cố từ Ushahidi', 'Import Incident Reports': 'Nhập khẩu báo cáo sự cố', 'Import Job Roles': 'Nhập khẩu vai trò công việc', 'Import Jobs': 'Chuyển đổi nghề nghiệp', 'Import Location Data': 'Nhập khẩu dữ liệu địa điểm', 'Import Locations': 'Nhập khẩu địa điểm', 'Import Logged Time data': 'Nhập khẩu dữ liệu thời gian truy cập', 'Import Members': 'Nhập khẩu thành viên', 'Import Membership Types': 'Nhập khẩu loại hình thành viên', 'Import Milestone Data': 'Nhập khẩu dự liệu các thời điểm quan trọng', 'Import Milestones': 'Tải dự liệu các thời điểm quan trọng', 'Import Offices': 'Nhập khẩu văn phòng', 'Import Organizations': 'Nhập khẩu tổ chức', 'Import Participant List': 'Nhập khẩu danh sách học viên', 'Import Participants': 'Tải người tham dự', 'Import Partner Organizations': 'Nhập khẩu dữ liệu về tổ chức đối tác', 'Import Project Communities': 'Đối tượng hưởng lợi dự án', 'Import Project Organizations': 'Tổ chức thực hiện dự án', 'Import Projects': 'Dự án', 'Import Red Cross & Red Crescent National Societies': 'Nhập khẩu dữ liệu về Hội CTĐ & TLLĐ Quốc gia', 'Import Staff': 'Nhập khẩu cán bộ', 'Import Stations': 'Nhập khẩu các trạm', 'Import Statuses': 'Nhập khẩu tình trạng', 'Import Suppliers': 'Nhập khẩu các nhà cung cấp', 'Import Tasks': 'Nhập khẩu Nhiệm vụ', 'Import Template Layout': 'Nhập khẩu sơ đồ mẫu', 'Import Templates': 'Nhập khẩu biểu mẫu', 'Import Theme data': 'Nhập khẩu dữ liệu chủ đề', 'Import Themes': 'Nhập khẩu Chủ đề', 'Import Training Events': 'Nhập khẩu sự kiện tập huấn', 'Import Training Participants': 'Nhập khẩu dữ liệu học viên được tập huấn', 'Import Vehicles': 'Nhập khẩu các phương tiện đi lại', 'Import Volunteer Cluster Positions': 'Nhập khẩu vị trí nhóm tình nguyện viên', 'Import Volunteer Cluster Types': 'Nhập khẩu loại hình nhóm tình nguyện viên', 'Import Volunteer Clusters': 'Nhập khẩu nhóm tình nguyện viên', 'Import Volunteers': 'Nhập khẩu tình nguyện viên', 'Import Vulnerability Aggregated Indicator': 'Nhập khẩu chỉ số phân tách tình trạng dễ bị tổn thương', 'Import Vulnerability Data': 'Nhập khẩu dữ liệu tình trạng dễ bị tổn thương', 'Import Vulnerability Indicator Sources': 'Nhập khẩu Nguồn chỉ số tình trạng dễ bị tổn thương', 'Import Vulnerability Indicator': 'Nhập khẩu chỉ số tình trạng dễ bị tổn thương', 'Import Warehouse Stock': 'Nhập khẩu hàng lưu kho', 'Import Warehouses': 'Nhập khẩu kho', 'Import from CSV': 'Nhập khẩu từ CSV', 'Import from OpenStreetMap': 'Nhập khẩu từ bản đồ OpenstreetMap', 'Import multiple tables as CSV': 'Chuyển đổi định dạng bảng sang CSV', 'Import': 'Nhập khẩu dữ liệu', 'Import/Export': 'Nhập/ Xuất dữ liệu', 'Important': 'Quan trọng', 'Imported data': 'Dữ liệu đã nhập', 'In Catalogs': 'Trong danh mục', 'In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Trong GeoServer, đây là tên lớp. Trong WFS getCapabilities, đây là tên FeatureType, phần sau dấu hai chấm (:).', 'In Inventories': 'Trong nhóm hàng', 'In Process': 'Đang tiến hành', 'In Stock': 'Đang lưu kho', 'In error': 'mắc lỗi', 'In order to be able to edit OpenStreetMap data from within %(name_short)s, you need to register for an account on the OpenStreetMap server.': 'Để có thể chỉnh sửa dữ liệu trên OpenstreetMap từ trong %(name_short)s, ban cần đăng ký tài khoản trên máy chủ OpenStreetMap.', 'In transit': 'Đang trên đường', 'Inbound Mail Settings': 'Cài đặt thư đến', 'Inbound Message Source': 'Nguồn thư đến', 'Incident Categories': 'Danh mục sự cố', 'Incident Commander': 'Chỉ huy tình huống tai nạn', 'Incident Report Details': 'Chi tiết Báo cáo tai nạn', 'Incident Report added': 'Thêm Báo cáo tai nạn', 'Incident Report deleted': 'Xóa Báo cáo tai nạn', 'Incident Report updated': 'Cập nhật Báo cáo tai nạn', 'Incident Report': 'Báo cáo tai nạn', 'Incident Reports': 'Báo cáo sự cố', 'Incident Timeline': 'Dòng thời gian tai nạn', 'Incident Types': 'Loại sự cố', 'Incident': 'Sự cố', 'Incidents': 'Tai nạn', 'Include any special requirements such as equipment which they need to bring.': 'Bao gồm các yêu cầu đặc biệt như thiết bị cần mang theo', 'Include core files': 'Bao gồm các tệp chủ chốt', 'Including emerging and re-emerging diseases, vaccine preventable diseases, HIV, TB': 'Gồm các bệnh mới bùng phát và tái bùng phát, các bệnh có thể ngừa bằng vaccine, HIV, lao phổi', 'Incoming Shipments': 'Lô hàng đang đến', 'Incorrect parameters': 'Tham số không đúng', 'Indicator Comparison': 'So sánh chỉ số', 'Indicator': 'Chỉ số', 'Indicators': 'Chỉ số', 'Individuals': 'Cá nhân', 'Industrial Crime': 'Tội ác công nghiệp', 'Industry Fire': 'Cháy nổ công nghiệp', 'Infant (0-1)': 'Trẻ sơ sinh (0-1)', 'Infectious Disease (Hazardous Material)': 'Dịch bệnh lây nhiễm (vật liệu nguy hiểm)', 'Infectious Disease': 'Dịch bệnh lây nhiễm', 'Infestation': 'Sự phá hoại', 'Informal camp': 'Trại không chính thức', 'Information Management': 'Quản lý thông tin', #'Information Technology': 'Công nghệ thông tin', 'Information Technology': 'CNTT', 'Infrastructure Development': 'Phát triển cơ sở hạ tầng', 'Inherited?': 'Được thừa kế?', 'Initials': 'Tên viết tắt', 'Insect Infestation': 'Dịch sâu bọ', 'Instance Type': 'Loại ví dụ', 'Instant Porridge': 'Cháo ăn liền', 'Insurance Number': 'Số sổ/thẻ bảo hiểm', 'Insurer': 'Nơi đăng ký BHXH', 'Instructor': 'Giảng viên', 'Insufficient Privileges': 'Không đủ đặc quyền', 'Insufficient vars: Need module, resource, jresource, instance': 'Không đủ var: cần module, nguồn lực, j nguồn lực, tức thời', 'Integrity error: record can not be deleted while it is referenced by other records': 'Lỗi liên kết: hồ sơ không thể bị xóa khi đang được liên kết với hồ sơ khác', 'Intermediate': 'Trung cấp', 'Internal Shipment': 'Vận chuyển nội bộ', 'Internal State': 'Tình trạng bên trong', 'International NGO': 'Tổ chức phi chính phủ quốc tế', 'International Organization': 'Tổ chức quốc tế', 'Interview taking place at': 'Phỏng vấn diễn ra tại', 'Invalid Location!': 'Vị trí không hợp lệ!', 'Invalid Query': 'Truy vấn không hợp lệ', 'Invalid Site!': 'Trang không hợp lệ!', 'Invalid form (re-opened in another window?)': 'Mẫu không hợp lệ (mở lại trong cửa sổ khác?)', 'Invalid phone number!': 'Số điện thoại không hợp lệ!', 'Invalid phone number': 'Số điện thoại không đúng', 'Invalid request!': 'Yêu cầu không hợp lệ!', 'Invalid request': 'Yêu cầu không hợp lệ', 'Invalid source': 'Nguồn không hợp lệ', 'Invalid ticket': 'Vé không đúng', 'Invalid': 'Không đúng', 'Inventory Adjustment Item': 'Mặt hàng điều chỉnh sau kiểm kê', 'Inventory Adjustment': 'Điều chỉnh sau kiểm kê', 'Inventory Item Details': 'Chi tiết hàng hóa trong kho', 'Inventory Item added': 'Bổ sung hàng hóa vào kho lưu trữ.', 'Inventory Items include both consumable supplies & those which will get turned into Assets at their destination.': 'Hàng hóa kiểm kê bao gồm cả hàng tiêu hao & hàng hóa sẽ được trả lại như tài sản tại đích đến', 'Inventory Items': 'Mặt hàng kiểm kê', 'Inventory Store Details': 'Chi tiết kho lưu trữ', 'Inventory of Effects': 'Kho dự phòng', 'Inventory': 'Kiểm kê', 'Is editing level L%d locations allowed?': 'Có được phép chỉnh sửa vị trí cấp độ L%d?', 'Is this a strict hierarchy?': 'Có phải là thứ tự đúng?', 'Issuing Authority': 'Cơ quan cấp', 'It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'Nó không chỉ nhận các vị trí đang kích hoạt mà cũng nhận các thông tin về các dự án đang có ở từng vùng', 'Item Added to Shipment': 'Mặt hàng được thêm vào lô hàng vận chuyển', 'Item Catalog Details': 'Thông tin danh mục hàng hóa', 'Item Catalog added': 'Đã thêm danh mục hàng hóa', 'Item Catalog deleted': 'Đã xóa danh mục hàng hóa', 'Item Catalog updated': 'Đã cập nhật danh mục hàng hóa', 'Item Catalogs': 'Danh mục hàng hóa', 'Item Categories': 'Loại hàng hóa', 'Item Category Details': 'Thông tin danh mục hàng hóa', 'Item Category added': 'Danh mục hàng hóa đã được thêm', 'Item Category deleted': 'Danh mục hàng hóa đã được xóa', 'Item Category updated': 'Danh mục hàng hóa đã được cập nhật', 'Item Category': 'Danh mục hàng hóa', 'Item Code': 'Mã hàng', 'Item Details': 'Thông tin hàng hóa', 'Item Name': 'Tên hàng', 'Item Pack Details': 'Thông tin về gói hàng', 'Item Pack added': 'Gói hàng đã được thêm', 'Item Pack deleted': 'Gói hàng đã được xóa', 'Item Pack updated': 'Gói hàng đã được cập nhật', 'Item Packs': 'Gói hàng', 'Item Status': 'Tình trạng hàng hóa', 'Item Sub-Category updated': 'Đã cập nhật tiêu chí phụ của hàng hóa', 'Item Tracking Status': 'Theo dõi tình trạng hàng hóa', 'Item added to stock': 'Mặt hàng được thêm vào kho', 'Item added': 'Mặt hàng đã được thêm', 'Item already in Bundle!': 'Hàng đã có trong Bundle!', 'Item deleted': 'Mặt hàng đã được xóa', 'Item quantity adjusted': 'Số lượng hàng đã được điều chỉnh', 'Item updated': 'Mặt hàng đã được cập nhật', 'Item': 'Mặt hàng', 'Item(s) added to Request': 'Hàng hóa đã được thêm vào yêu cầu', 'Item(s) deleted from Request': 'Hàng hóa đã được xóa khỏi yêu cầu', 'Item(s) updated on Request': 'Hàng hóa đã được cập nhật vào yêu cầu', 'Item/Description': 'Mặt hàng/ Miêu tả', 'Items in Category are Vehicles': 'Mặt hàng trong danh mục là phương tiện vận chuyển', 'Items in Category can be Assets': 'Mặt hàng trong danh mục có thể là tài sản', 'Items in Request': 'Hàng hóa trong thư yêu cầu', 'Items in Stock': 'Hàng hóa lưu kho', 'Items': 'Hàng hóa', 'Items/Description': 'Mô tả/Hàng hóa', 'JS Layer': 'Lớp JS', 'Jewish': 'Người Do Thái', 'Job Role Catalog': 'Danh mục vai trò công việc', 'Job Role Details': 'Chi tiết vai trò công việc', 'Job Role added': 'Vai trò công việc đã được thêm', 'Job Role deleted': 'Vai trò công việc đã được xóa', 'Job Role updated': 'Vai trò công việc đã được cập nhật', 'Job Role': 'Vai trò công việc', 'Job Schedule': 'Kế hoạch công việc', 'Job Title Catalog': 'Vị trí chức vụ', 'Job Title Details': 'Chi tiết chức danh công việc', 'Job Title added': 'Chức danh công việc đã được thêm', 'Job Title deleted': 'Chức danh công việc đã được xóa', 'Job Title updated': 'Chức danh công việc đã được cập nhật', 'Job Title': 'Chức danh công việc', 'Job Titles': 'Chức vụ', 'Job added': 'Công việc đã được thêm', 'Job deleted': 'Công việc đã được xóa', 'Job reactivated': 'Công việc đã được kích hoạt lại', 'Job updated': 'Công việc đã được cập nhật', 'Journal Entry Details': 'Chi tiết ghi chép nhật ký', 'Journal entry added': 'Ghi chép nhật ký đã được thêm', 'Journal entry deleted': 'Ghi chép nhật ký đã được xóa', 'Journal entry updated': 'Ghi chép nhật ký đã được cập nhật', 'Journal': 'Nhật ký', 'KML Layer': 'Lớp KML', 'Key Value pairs': 'Đôi giá trị Khóa', 'Key deleted': 'Đã xóa từ khóa', 'Key': 'Phím', 'Keyword': 'Từ khóa', 'Keywords': 'Từ khóa', 'Kit Created': 'Thùng hàng đã được tạo', 'Kit Details': 'Chi tiết thùng hàng', 'Kit Item': 'Mặt hàng trong thùng', 'Kit Items': 'Mặt hàng trong thùng', 'Kit canceled': 'Thùng hàng đã được hủy', 'Kit deleted': 'Đã xóa Kit', 'Kit updated': 'Thùng hàng đã được cập nhật', 'Kit': 'Thùng hàng', 'Kit?': 'Thùng hàng?', 'Kits': 'Thùng hàng', 'Kitting': 'Trang bị dụng cụ', 'Knowledge Management': 'Quản lý tri thức', 'Known Locations': 'Vị trí được xác định', 'LEGEND': 'CHÚ GIẢI', 'LICENSE': 'Bản quyền', 'LOW RESILIENCE': 'MỨC ĐỘ AN TOÀN THẤP', 'LOW': 'THẤP', 'Label': 'Nhãn', 'Lack of transport to school': 'Thiếu phương tiện di chuyển cho trẻ em đến trường', 'Lahar': 'Dòng dung nham', 'Land Slide': 'Sạt lở đất', 'Landslide': 'Sạt lở đất', 'Language Code': 'Mã Ngôn ngữ', 'Language code': 'Mã ngôn ngữ', 'Language': 'Ngôn ngữ', 'Last Checked': 'Lần cuối cùng được kiểm tra', 'Last Data Collected on': 'Dữ liệu mới nhất được thu thập trên', 'Last Name': 'Tên họ', 'Last Pull': 'Kéo gần nhất', 'Last Push': 'Đầy gần nhất', 'Last known location': 'Địa điểm vừa biết đến', 'Last pull on': 'Kéo về gần đây', 'Last push on': 'Đẩy vào gần đây', 'Last run': 'Lần chạy gần nhất', 'Last status': 'Trạng thái gần đây', 'Last updated': 'Cập nhật mới nhất', 'Last': 'Trang cuối', 'Latitude & Longitude': 'Vĩ độ & Kinh độ', 'Latitude is Invalid!': 'Vị độ không hợp lệ', 'Latitude is North-South (Up-Down). Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Vĩ độ là Bắc-Nam (trên xuống). Vĩ độ bằng không trên đường xích đạo, dương phía bán cầu Bắc và âm phía bán cầu Nam', 'Latitude is North-South (Up-Down).': 'Vĩ độ Bắc-Nam (trên-xuống)', 'Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere.': 'Vĩ độ bằng 0 là ở xích đạo và có giá trị dương ở bắc bán cầu và giá trị âm ở nam bán cầu', 'Latitude must be between -90 and 90.': 'Vĩ độ phải nằm giữa -90 và 90', 'Latitude of Map Center': 'Vĩ độ trung tâm bản đồ vùng', 'Latitude of far northern end of the region of interest.': 'Vĩ độ bắc điểm cuối của vùng quan tâm', 'Latitude of far southern end of the region of interest.': 'Vĩ độ nam điểm cuối của vùng quan tâm', 'Latitude should be between': 'Vĩ độ phải từ ', 'Latitude': 'Vĩ độ', 'Latrines': 'nhà vệ sinh', 'Layer Details': 'Thông tin về Lớp', 'Layer Name': 'Tên lớp', 'Layer Properties': 'Đặc tính của lớp bản đồ', 'Layer added': 'Lớp đã được thêm', 'Layer deleted': 'Lớp đã được xóa', 'Layer has been Disabled': 'Lớp đã bị khóa', 'Layer has been Enabled': 'Lớp đã được bật', 'Layer removed from Symbology': 'Lớp đã được gỡ khỏi danh mục biểu tượng', 'Layer updated': 'Lớp đã được cập nhật', 'Layer': 'Lớp', 'Layers updated': 'Đã cập nhật Layer', 'Layers': 'Lớp', 'Layout': 'Định dạng', 'Lead Implementer for this project is already set, please choose another role.': 'Người thực hiện chính của Dự án này đã được chỉ định, đề nghị chọn một vai trò khác', 'Lead Implementer': 'Trưởng nhóm thực hiện', 'Lead Organization': 'Tổ chức chỉ đạo', 'Leader': 'Người lãnh đạo', 'Leave blank to request an unskilled person': 'Bỏ trắng nếu yêu cầu người không cần kỹ năng', 'Left-side is fully transparent (0), right-side is opaque (1.0).': 'Bên trái là hoàn toàn trong suốt (0), bên phải là không trong suốt (1.0)', 'Legend URL': 'Chú giải URL', 'Legend': 'Chú giải', 'Length (m)': 'Chiều dài (m)', 'Length': 'Độ dài', 'Less Options': 'Thu hẹp chức năng', 'Level of Award (Count)': 'Trình độ học vấn (Số lượng)', 'Level of Award': 'Trình độ học vấn', 'Level of competency this person has with this skill.': 'Cấp độ năng lực của người này với kỹ năng đó', 'Level': 'Cấp độ', 'Library support not available for OpenID': 'Thư viện hỗ trợ không có sẵn cho việc tạo ID', 'License Number': 'Số giấy phép', 'Link (or refresh link) between User, Person & HR Record': 'Đường dẫn (hay đường dẫn mới) giữa người dùng, người và hồ sơ cán bộ', 'Link to this result': 'Đường dẫn tới kết quả này', 'Link': 'Liên kết', 'List / Add Baseline Types': 'Liệt kê / thêm loại hình khảo sát trước can thiệp', 'List / Add Impact Types': 'Liệt kê / thêm loại tác động', 'List Activities': 'Liêt kê hoạt động', 'List Activity Types': 'Liệt kê loại hoạt động', 'List Addresses': 'Liệt kê địa chỉ', 'List Affiliations': 'Liệt kê liên kết', 'List Aid Requests': 'Danh sách Yêu cầu cứu trợ', 'List All Catalogs & Add Items to Catalogs': 'Liệt kê danh mục & Thêm mục mặt hàng vào danh mục', 'List All Commitments': 'Liệt kê tất cả cam kết', 'List All Community Contacts': 'Liệt kê tất cả thông tin liên lạc của cộng đồng', 'List All Entries': 'Liệt kê tất cả hồ sơ', 'List All Essential Staff': 'Liệt kê tất cả cán bộ quan trọng', 'List All Item Categories': 'Liệt kê tât cả danh mục hàng hóa', 'List All Items': 'Liệt kê tất cả mặt hàng', 'List All Memberships': 'Danh sách tất cả các thành viên', 'List All Requested Items': 'Liệt kê tất cả mặt hàng được yêu cầu', 'List All Requested Skills': 'Liệt kê tất cả kỹ năng được yêu cầu', 'List All Requests': 'Liệt kê tất cả yêu cầu', 'List All Roles': 'Liệt kê tất cẩ vai trò', 'List All Security-related Staff': 'Liệt kê tất cả cán bộ liên quan đến vai trò bảo vệ', 'List All Users': 'Liệt kê tất cả người dùng', 'List All': 'Liệt kê tất cả', 'List Alternative Items': 'Liệt kê mặt hàng thay thế', 'List Annual Budgets': 'Liệt kê ngân sách năm', 'List Assessment Answers': 'Liêt kê câu trả lời trong biểu mẫu đánh giá', 'List Assessment Questions': 'Liệt kê câu hỏi trong biểu mẫu đánh giá', 'List Assessment Templates': 'Liệt kê biểu mẫu đánh giá', 'List Assessments': 'Danh sách Trị giá tính thuế', 'List Assets': 'Liệt kê tài sản', 'List Assigned Human Resources': 'Liệt kê nguồn nhân lực đã được phân công', 'List Beneficiaries': 'Liệt kê người hưởng lợi', 'List Beneficiary Types': 'Liệt kê loại người hưởng lợi', 'List Branch Organizations': 'Liệt kê tổ chức cơ sở', 'List Brands': 'Liệt kê nhãn hiệu', 'List Catalog Items': 'Liệt kê mặt hàng trong danh mục', 'List Catalogs': 'Liệt kê danh mục', 'List Certificates': 'Liệt kê chứng chỉ', 'List Certifications': 'Liệt kê bằng cấp', 'List Checklists': 'Danh sách Checklists ', 'List Clusters': 'Liệt kê nhóm', 'List Commitment Items': 'Liệt kê mặt hàng cam kết', 'List Commitments': 'Liệt kê cam kết', 'List Committed People': 'Liệt kê người cam kết', 'List Communities': 'Liệt kê cộng đồng', 'List Community Contacts': 'Thông tin liên hệ cộng đồng', 'List Competency Ratings': 'Liệt kê xếp hạng năng lực', 'List Completed Assessment Forms': 'Liệt kê biểu mẫu đánh giá đã hoàn thiện', 'List Contact Information': 'Liệt kê thông tin liên lạc', 'List Contacts': 'Liệt kê liên lạc', 'List Course Certificates': 'Liệt kê Chứng chỉ khóa học', 'List Courses': 'Liệt kê khóa học', 'List Credentials': 'Liệt kê thư ủy nhiệm', 'List Current': 'Danh mục hiện hành', 'List Data in Theme Layer': 'Liệt kê dữ liệu trong lớp chủ đề ', 'List Demographic Data': 'Liệt kê số liệu dân số', 'List Demographic Sources': 'Liệt kê nguồn thông tin về dân số', 'List Demographics': 'Liệt kê dữ liệu nhân khẩu', 'List Departments': 'Liệt kê phòng/ban', 'List Disaster Assessments': 'Liệt kê báo cáo đánh giá thảm họa', 'List Distributions': 'Danh sách ủng hộ,quyên góp', 'List Documents': 'Liệt kê tài liệu', 'List Donors': 'Liệt kê nhà tài trợ', 'List Education Details': 'Liệt kê thông tin về trình độ học vấn', 'List Facilities': 'Liệt kê bộ phận', 'List Facility Types': 'Liệt kê loại hình bộ phận', 'List Feature Layers': 'Liệt kê lớp chức năng', 'List Frameworks': 'Liệt kê khung chương trình', 'List Groups': 'Liệt kê nhóm', 'List Hazards': 'Liệt kê hiểm họa', 'List Hospitals': 'Danh sách Bệnh viện', 'List Hours': 'Liệt kê thời gian hoạt động', 'List Identities': 'Liệt kê nhận dạng', 'List Images': 'Liệt kê hình ảnh', 'List Incident Reports': 'Liệt kê báo cáo sự cố', 'List Item Categories': 'Liệt kê danh mục hàng hóa', 'List Item Packs': 'Liệt kê gói hàng', 'List Items in Request': 'Liệt kê mặt hàng đang được yêu cầu', 'List Items in Stock': 'Liệt kê mặt hàng đang lưu kho', 'List Items': 'Liệt kê hàng hóa', 'List Job Roles': 'Liệt kê vai trò công việc', 'List Job Titles': 'Liệt kê chức danh công việc', 'List Jobs': 'Liệt kê công việc', 'List Kits': 'Liệt kê thùng hàng', 'List Layers in Profile': 'Liệt kê lớp trong hồ sơ tiểu sử', 'List Layers in Symbology': 'Liệt kê lớp trong biểu tượng', 'List Layers': 'Liệt kê lớp', 'List Location Hierarchies': 'Liệt kê thứ tự địa điểm', 'List Locations': 'Liệt kê địa điểm', 'List Log Entries': 'Liệt kê ghi chép nhật ký', 'List Logged Time': 'Liệt kê thời gian đang nhập', 'List Mailing Lists': 'Liệt kê danh sách gửi thư', 'List Map Profiles': 'Liệt kê cấu hình bản đồ', 'List Markers': 'Liệt kê công cụ đánh dấu', 'List Members': 'Liệt kê hội viên', 'List Membership Types': 'Liệt kê loại hình nhóm hội viên', 'List Memberships': 'Liệt kê nhóm hội viên', 'List Messages': 'Liệt kê tin nhắn', 'List Metadata': 'Danh sách dữ liệu', 'List Milestones': 'Liệt kê mốc thời gian quan trọng', 'List Missing Persons': 'Danh sách những người mất tích', 'List Office Types': 'Liệt kê loại hình văn phòng', 'List Offices': 'Liệt kê văn phòng', 'List Orders': 'Liệt kê lệnh', 'List Organization Domains': 'Liệt kê lĩnh vực hoạt động của tổ chức', 'List Organization Types': 'Liệt kê loại hình tổ chức', 'List Organizations': 'Liệt kê tổ chức', 'List Outputs': 'Liệt kê đầu ra', 'List Participants': 'Liệt kê người Tham dự', 'List Partner Organizations': 'Liệt kê tổ chức đối tác', 'List Persons': 'Liệt kê đối tượng', 'List Photos': 'Liệt kê ảnh', 'List Profiles configured for this Layer': 'Liệt kê tiểu sử được cấu hình cho lớp này', 'List Programs': 'Liệt kê chương trình', 'List Project Organizations': 'Liệt kê tổ chức dự án', 'List Projections': 'Liệt kê dự đoán', 'List Projects': 'Liệt kê dự án', 'List Question Meta-Data': 'Liệt kê siêu dữ liệu câu hỏi', 'List Received/Incoming Shipments': 'Liệt kê lô hàng nhận được/đang đến', 'List Records': 'Liệt kê hồ sơ', 'List Red Cross & Red Crescent National Societies': 'Liệt kê Hội CTĐ & TLLĐ quốc gia', 'List Repositories': 'Liệt kê kho lưu trữ', 'List Request Items': 'Danh sách Hang hóa yêu cầu', 'List Requested Skills': 'Liệt kê kỹ năng được yêu cầu', 'List Requests': 'Liệt kê yêu cầu', 'List Resources': 'Liệt kê nguồn lực', 'List Rivers': 'Danh sách sông', 'List Roles': 'Liệt kê vai trò', 'List Rooms': 'Liệt kê phòng', 'List Sectors': 'Liệt kê lĩnh vực', 'List Sent Shipments': 'Liệt kê lô hàng đã gửi đi', 'List Shelter Services': 'Danh sách dịch vụ cư trú', 'List Shipment Items': 'Liệt kê mặt hàng trong lô hàng', 'List Shipment/Way Bills': 'Danh sách Đơn hàng/Phí đường bộ', 'List Sites': 'Danh sách site', 'List Skill Equivalences': 'Liệt kê kỹ năng tương đương', 'List Skill Types': 'Liệt kê loại kỹ năng', 'List Skills': 'Liệt kê kỹ năng', 'List Staff & Volunteers': 'Liệt kê Cán bộ và Tình nguyện viên', 'List Staff Assignments': 'Liệt kê phân công cán bộ', 'List Staff Members': 'Liệt kê cán bộ', 'List Staff Types': 'Lên danh sách các bộ phận nhân viên', 'List Staff': 'Danh sách Nhân viên', 'List Statuses': 'Liệt kê tình trạng', 'List Stock Adjustments': 'Liệt kê điều chỉnh hàng lưu kho', 'List Stock in Warehouse': 'Liệt kê hàng lưu trong kho hàng', 'List Storage Location': 'Danh sách vị trí kho lưu trữ', 'List Subscriptions': 'Danh sách Đăng ký', 'List Suppliers': 'Liệt kê nhà cung cấp', 'List Support Requests': 'Liệt kê đề nghị hỗ trợ', 'List Survey Questions': 'Danh sách câu hỏi khảo sát', 'List Survey Series': 'Lên danh sách chuỗi khảo sát', 'List Symbologies for Layer': 'Liệt kê biểu tượng cho Lớp', 'List Symbologies': 'Liệt kê biểu tượng', 'List Tasks': 'Liệt kê nhiệm vụ', 'List Teams': 'Liệt kê Đội/Nhóm', 'List Template Sections': 'Liệt kê nội dung biểu mẫu', 'List Themes': 'Liệt kê chủ đề', 'List Training Events': 'Liệt kê khóa tập huấn', 'List Trainings': 'Liệt kê lớp tập huấn', 'List Units': 'Danh sách đơn vị', 'List Users': 'Liệt kê người sử dụng', 'List Vehicle Assignments': 'Liệt kê phân công phương tiện vận chuyển', 'List Volunteer Cluster Positions': 'Liệt kê vị trí nhóm tình nguyện viên', 'List Volunteer Cluster Types': 'Liệt kê loại hình nhóm tình nguyện viên', 'List Volunteer Clusters': 'Liệt kê nhóm tình nguyện viên', 'List Volunteer Roles': 'Liệt kê vai trò của tình nguyện viên', 'List Volunteers': 'Liệt kê tình nguyện viên', 'List Vulnerability Aggregated Indicators': 'Liệt kê chỉ số gộp đánh giá tình trạng dễ bị tổn thương', 'List Vulnerability Data': 'Liệt kê dữ liệu về tình trạng dễ bị tổn thương', 'List Vulnerability Indicator Sources': 'Liệt kê nguồn chỉ số đánh giá tình trạng dễ bị tổn thương', 'List Vulnerability Indicators': 'Liệt kê chỉ số đánh giá tình trạng dễ bị tổn thương', 'List Warehouses': 'Liệt kê kho hàng', 'List alerts': 'Liệt kê cảnh báo', 'List all Entries': 'Liệt kê tất cả hồ sơ', 'List all': 'Liệt kê tất cả', 'List of Missing Persons': 'Danh sách những người mất tích', 'List of Professional Experience': 'Danh sách kinh nghiệm nghề nghiệp', 'List of Requests': 'Danh sách yêu cầu', 'List of Roles': 'Danh sách vai trò', 'List of addresses': 'Danh sách các địa chỉ', 'List saved searches': 'Liệt kê tìm kiếm đã lưu', 'List templates': 'Liệt kê biểu mẫu', 'List unidentified': 'Liệt kê danh mục chư tìm thấy', 'List': 'Liệt kê', 'List/Add': 'Liệt kê/ Thêm', 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities': 'Danh sách "Ai làm gì, ở đâu"Cho phép các tổ chức cứu trợ điều phối hoạt động của mình', 'Live Help': 'Trợ giúp trực tuyến', 'Livelihood': 'Sinh kế', 'Livelihoods': 'Sinh kế', 'Load Cleaned Data into Database': 'Tải dữ liệu sạch vào cơ sở dữ liệu', 'Load Raw File into Grid': 'Tải file thô vào hệ thống mạng', 'Load': 'Tải', 'Loaded By': 'Được tải lên bởi', 'Loading report details': 'Tải thông tin báo cáo', 'Loading': 'Đang tải', 'Local Name': 'Tên địa phương', 'Local Names': 'Tên địa phương', 'Location (Site)': 'Địa điểm (vùng)', 'Location 1': 'Địa điểm 1', 'Location 2': 'Địa điểm 2', 'Location 3': 'Địa điểm 3', 'Location Added': 'Địa điểm đã được thêm', 'Location Deleted': 'Địa điểm đã được xóa', 'Location Detail': 'Thông tin địa điểm', 'Location Details': 'Thông tin địa điểm', 'Location Group': 'Nhóm địa điểm', 'Location Hierarchies': 'Thứ tự địa điểm', 'Location Hierarchy Level 1 Name': 'Tên thứ tự địa điểm cấp 1', 'Location Hierarchy Level 2 Name': 'Tên thứ tự địa điểm cấp 2', 'Location Hierarchy Level 3 Name': 'Tên thứ tự địa điểm cấp 3', 'Location Hierarchy Level 4 Name': 'Tên thứ tự địa điểm cấp 4', 'Location Hierarchy Level 5 Name': 'Tên thứ tự địa điểm cấp 5', 'Location Hierarchy added': 'Thứ tự địa điểm đã được thêm', 'Location Hierarchy deleted': 'Thứ tự địa điểm đã được xóa', 'Location Hierarchy updated': 'Thứ tự địa điểm đã được cập nhật', 'Location Hierarchy': 'Thứ tự địa điểm', 'Location Updated': 'Địa điểm đã được cập nhật', 'Location added': 'Địa điểm đã được thêm', 'Location deleted': 'Địa điểm đã được xóa', 'Location is Required!': 'Địa điểm được yêu cầu!', 'Location needs to have WKT!': 'Địa điểm cần để có WKT!', 'Location updated': 'Địa điểm đã được cập nhật', 'Location': 'Địa điểm', 'Locations of this level need to have a parent of level': 'Địa điểm ở cấp độ này cần có các cấp độ cha', 'Locations': 'Địa điểm', 'Log Entry Deleted': 'Ghi chép nhật ký đã được xóa', 'Log Entry Details': 'Thông tin về ghi chép nhật ký', 'Log Entry': 'Ghi chép nhật ký', 'Log New Time': 'Thời gian truy cập Mới', 'Log Time Spent': 'Thời gian đã Truy cập', 'Log entry added': 'Ghi chép nhật ký đã được thêm', 'Log entry deleted': 'Ghi chép nhật ký đã được xóa', 'Log entry updated': 'Ghi chép nhật ký đã được cập nhật', 'Log': 'Nhật ký', 'Logged Time Details': 'Thông tin về thời gian đã truy cập', 'Logged Time': 'Thời gian đã truy cập', 'Login with Facebook': 'Đăng nhập với Facebook', 'Login with Google': 'Đăng nhập với Google', 'Login': 'Đăng nhập', 'Logistics & Warehouse': 'Hậu cần & Nhà kho', 'Logo of the organization. This should be a png or jpeg file and it should be no larger than 400x400': 'Biểu trưng của một tổ chức phải là tệp png hay jpeg and không lớn hơn 400x400', 'Logo': 'Biểu tượng', 'Logout': 'Thoát', 'Long Name': 'Tên đầy đủ', 'Long Text': 'Đoạn văn bản dài', 'Long-term': 'Dài hạn', 'Longitude is Invalid!': 'Kinh độ không hợp lệ', 'Longitude is West - East (sideways). Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Kinh độ trải dài theo hướng Đông-Tây. Kinh tuyến không nằm trên kinh tuyến gốc (Greenwich Mean Time) hướng về phía đông, vắt ngang châu Âu và châu Á.', 'Longitude is West - East (sideways).': 'Kinh độ Tây - Đông (đường ngang)', 'Longitude is West-East (sideways).': 'Kinh độ Tây - Đông (đường ngang)', 'Longitude is zero on the prime meridian (Greenwich Mean Time) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Kinh độ là 0 tại đường kinh tuyến đầu tiên (Thời gian vùng Greenwich) và có giá trị dương sang phía đông, qua Châu Âu và Châu Á. Kinh tuyến có giá trị âm sang phía tây, từ Đại Tây Dương qua Châu Mỹ.', 'Longitude is zero on the prime meridian (through Greenwich, United Kingdom) and is positive to the east, across Europe and Asia. Longitude is negative to the west, across the Atlantic and the Americas.': 'Kinh độ là 0 tại đường kinh tuyến đầu tiên (xuyên qua Greenwich, Anh) và có giá trị dương sang phía đông, qua châu Âu và Châu Á. Kinh tuyến có giá trị âm sang phía tây qua Đại Tây Dương và Châu Mỹ.', 'Longitude must be between -180 and 180.': 'Kinh độ phải nằm giữa -180 và 180', 'Longitude of Map Center': 'Kinh độ trung tâm bản đồ của vùng quan tâm', 'Longitude of far eastern end of the region of interest.': 'Kinh độ phía đông điểm cuối của vùng quan tâm', 'Longitude of far western end of the region of interest.': 'Kinh độ phía tây điểm cuối của vùng quan tâm', 'Longitude should be between': 'Kinh độ phải từ giữa', 'Longitude': 'Kinh độ', 'Looting': 'Nạn cướp bóc', 'Lost Password': 'Mất mật khẩu', 'Lost': 'Mất', 'Low': 'Thấp', 'MEDIAN': 'ĐIỂM GIỮA', 'MGRS Layer': 'Lớp MGRS', 'MODERATE': 'TRUNG BÌNH', 'MY REPORTS': 'BÁO CÁO CỦA TÔI', 'Magnetic Storm': 'Bão từ trường', 'Mailing List Details': 'Thông tin danh sách gửi thư', 'Mailing List Name': 'Tên danh sách gửi thư', 'Mailing Lists': 'Danh sách gửi thư', 'Mailing list added': 'Danh sách gửi thư đã được thêm', 'Mailing list deleted': 'Danh sách gửi thư đã được xóa', 'Mailing list updated': 'Danh sách gửi thư đã được cập nhật', 'Mailing list': 'Danh sách gửi thư', 'Main Duties': 'Nhiệm vụ chính', 'Mainstreaming DRR': 'GTRRTH Chính thống', 'Major Damage': 'Thiệt hại lớn', 'Major outward damage': 'Vùng ngoài chính hỏng', 'Major': 'Chuyên ngành', 'Make Commitment': 'Làm một cam kết', 'Make New Commitment': 'Làm một cam kết Mới', 'Make Request': 'Đặt yêu cầu', 'Make a Request for Aid': 'Tạo yêu cầu cứu trợ', 'Make a Request': 'Tạo yêu cầu', 'Male': 'Nam', 'Manage Layers in Catalog': 'Quản lý Lớp trong danh mục', 'Manage National Society Data': 'Quản lý dữ liệu Hội quốc gia', 'Manage Offices Data': 'Quản lý dữ liệu văn phòng', 'Manage Returns': 'Quản lý hàng trả lại', 'Manage Staff Data': 'Quản lý dữ liệu cán bộ', 'Manage Sub-Category': 'Quản lý Tiêu chí phụ', 'Manage Teams Data': 'Quản lý dữ liệu đội TNV', 'Manage Users & Roles': 'Quản lý Người sử dụng & Vai trò', 'Manage Volunteer Data': 'Quản lý dữ liệu TNV', 'Manage Your Facilities': 'Quản lý bộ phận của bạn', 'Manage office inventories and assets.': 'Quản lý tài sản và thiết bị văn phòng', 'Manage volunteers by capturing their skills, availability and allocation': 'Quản ly tình nguyện viên bằng việc nắm bắt những kĩ năng, khả năng và khu vực hoạt động của họ', 'Managing material and human resources together to better prepare for future hazards and vulnerabilities.': 'Quản lý nguồn lực để chuẩn bị tốt hơn cho hiểm họa trong tương lai và tình trạng dễ bị tổn thương.', 'Managing, Storing and Distributing Relief Items.': 'Quản lý, Lưu trữ và Quyên góp hàng cứu trợ', 'Mandatory. In GeoServer, this is the Layer Name. Within the WFS getCapabilities, this is the FeatureType Name part after the colon(:).': 'Bắt buộc. Trong máy chủ về Địa lý, đây là tên Lớp. Trong lớp WFS theo Khả năng là đường dẫn, đây là phần Tên loại chức năng sau dấu hai chấm (:).', 'Mandatory. The URL to access the service.': 'Trường bắt buộc. URL để đăng nhập dịch vụ', 'Manual Synchronization': 'Đồng bộ hóa thủ công', 'Manual synchronization completed.': 'Đồng bộ hóa thủ công đã hoàn tất', 'Manual synchronization scheduled - refresh page to update status.': 'Đồng bộ hóa thủ công đã được đặt lịch - làm mới trang để cập nhật tình trạng', 'Manual synchronization started in the background.': 'Đồng bộ hóa thủ công đã bắt đầu ở nền móng', 'Map Center Latitude': 'Vĩ độ trung tâm bản đồ', 'Map Center Longitude': 'Kinh độ trung tâm bản đồ', 'Map Profile added': 'Cấu hình bản đồ đã được thêm', 'Map Profile deleted': 'Cấu hình bản đồ đã được xóa', 'Map Profile updated': 'Cấu hình bản đồ đã được cập nhật', 'Map Profile': 'Cấu hình bản đồ', 'Map Profiles': 'Cấu hình bản đồ', 'Map Height': 'Chiều cao bản đồ', 'Map Service Catalog': 'Catalogue bản đồ dịch vụ', 'Map Settings': 'Cài đặt bản đồ', 'Map Viewing Client': 'Người đang xem bản đồ', 'Map Width': 'Độ rộng bản đồ', 'Map Zoom': 'Phóng to thu nhỏ Bản đồ', 'Map from Sahana Eden': 'Bản đồ từ Sahana Eden', 'Map not available: No Projection configured': 'Bản đồ không có: Chưa có dự đoán được cài đặt', 'Map not available: Projection %(projection)s not supported - please add definition to %(path)s': 'Bản đồ không có: Dự đoán %(projection)s không được hỗ trỡ - xin thêm khái niệm đến %(path)s', 'Map of Communties': 'Bản đồ cộng đồng', 'Map of Hospitals': 'Bản đồ bệnh viện', 'Map of Incident Reports': 'Bản đồ báo cáo sự cố', 'Map of Offices': 'Bản đồ văn phòng', 'Map of Projects': 'Bản đồ dự án', 'Map of Warehouses': 'Bản đồ kho hàng', 'Map': 'Bản đồ', 'Map': 'Bản đồ', 'Marine Security': 'An ninh hàng hải', 'Marital Status': 'Tình trạng hôn nhân', 'Marker Details': 'Thông tin công cụ đánh dấu', 'Marker Levels': 'Cấp độ công cụ đánh dấu', 'Marker added': 'Công cụ đánh dấu đã được thêm', 'Marker deleted': 'Công cụ đánh dấu đã được xóa', 'Marker updated': 'Công cụ đánh dấu đã được cập nhật', 'Marker': 'Công cụ đánh dấu', 'Markers': 'Công cụ đánh dấu', 'Married': 'Đã kết hôn', 'Master Message Log to process incoming reports & requests': 'Kiểm soát log tin nhắn để xử lý báo cáo và yêu cầu gửi đến', 'Master Message Log': 'Nhật ký tin nhắn chính', 'Master': 'Chủ chốt', 'Master Degree or Higher': 'Trên đại học', 'Match Requests': 'Phù hợp với yêu cầu', 'Match?': 'Phù hợp?', 'Matching Catalog Items': 'Mặt hàng trong danh mục phù hợp', 'Matching Items': 'Mặt hàng phù hợp', 'Matching Records': 'Hồ sơ phù hợp', 'Maternal, Newborn and Child Health': 'CSSK Bà mẹ, trẻ sơ sinh và trẻ em', 'Matrix of Choices (Only one answer)': 'Ma trận lựa chọn (chỉ chọn một câu trả lời)', 'Maximum Location Latitude': 'Vĩ độ tối đa của địa điểm', 'Maximum Location Longitude': 'Kinh độ tối đa của địa điểm', 'Maximum Weight': 'Khối lượng tối đa', 'Maximum must be greater than minimum': 'Giá trị tối đa phải lớn hơn giá trị tối thiểu', 'Maximum': 'Tối đa', 'Mean': 'Trung bình', 'Measure Area: Click the points around the polygon & end with a double-click': 'Đo diện tích: Bấm chuột vào điểm của khu vực cần đo & kết thúc bằng nháy đúp chuột', 'Measure Length: Click the points along the path & end with a double-click': 'Đo Chiều dài: Bấm chuột vào điểm dọc đường đi & kết thúc bằng nháy đúp chuột', 'Media': 'Truyền thông', 'Median Absolute Deviation': 'Độ lệch tuyệt đối trung bình', 'Median': 'Điểm giữa', 'Medical Conditions': 'Tình trạng sức khỏe', 'Medical Services': 'Dịch vụ y tế', 'Medium': 'Trung bình', 'Member Base Development': 'Phát triển cơ sở hội viên', 'Member Details': 'Thông tin về hội viên', 'Member ID': 'Tên truy nhập của hội viên', 'Member added to Group': 'Thành viên nhóm đã được thêm', 'Member added to Team': 'Thành viên Đội/Nhóm đã thêm', 'Member added': 'Hội viên đã được thêm', 'Member deleted': 'Hội viên đã được xóa', 'Member removed from Group': 'Nhóm hội viên đã được xóa', 'Member updated': 'Hội viên đã được cập nhật', 'Member': 'Hội viên', 'Members': 'Hội viên', 'Membership Details': 'Thông tin về nhóm hội viên', 'Membership Fee': 'Phí hội viên', 'Membership Paid': 'Hội viên đã đóng phí', 'Membership Type Details': 'Thông tin về loại hình nhóm hội viên', 'Membership Type added': 'Loại hình nhóm hội viên đã được thêm', 'Membership Type deleted': 'Loại hình nhóm hội viên đã được xóa', 'Membership Type updated': 'Loại hình nhóm hội viên đã được cập nhật', 'Membership Types': 'Loại hình nhóm hội viên', 'Membership updated': 'Nhóm hội viên đã được cập nhật', 'Membership': 'Nhóm hội viên', 'Memberships': 'Nhóm hội viên', 'Message Details': 'Chi tiết tin nhắn', 'Message Parser settings updated': 'Cài đặt cú pháp tin nhắn đã được cập nhật', 'Message Source': 'Nguồn tin nhắn', 'Message Variable': 'Biến tin nhắn', 'Message added': 'Tin nhắn đã được thêm ', 'Message deleted': 'Tin nhắn đã được xóa', 'Message updated': 'Tin nhắn đã được cập nhật', 'Message variable': 'Biến tin nhắn', 'Message': 'Tin nhắn', 'Messages': 'Tin nhắn', 'Messaging': 'Soạn tin nhắn', 'Metadata Details': 'Chi tiết siêu dữ liệu', 'Metadata added': 'Đã thêm dữ liệu', 'Metadata': 'Lý lịch dữ liệu', 'Meteorite': 'Thiên thạch', 'Middle Name': 'Tên đệm', 'Migrants or ethnic minorities': 'Dân di cư hoặc dân tộc thiểu số', 'Milestone Added': 'Mốc thời gian quan trọng đã được thêm', 'Milestone Deleted': 'Mốc thời gian quan trọng đã được xóa', 'Milestone Details': 'Thông tin về mốc thời gian quan trọng', 'Milestone Updated': 'Mốc thời gian quan trọng đã được cập nhật', 'Milestone': 'Mốc thời gian quan trọng', 'Milestones': 'Mốc thời gian quan trọng', 'Minimum Location Latitude': 'Vĩ độ tối thiểu của địa điểm', 'Minimum Location Longitude': 'Kinh độ tối thiểu của địa điểm', 'Minimum': 'Tối thiểu', 'Minor Damage': 'Thiệt hại nhỏ', 'Minute': 'Phút', 'Minutes must be a number.': 'Giá trị của phút phải bằng chữ số', 'Minutes must be less than 60.': 'Giá trị của phút phải ít hơn 60', 'Missing Person Details': 'Chi tiết về người mất tích', 'Missing Person Reports': 'Báo cáo số người mất tích', 'Missing Person': 'Người mất tích', 'Missing Persons Report': 'Báo cáo số người mất tích', 'Missing Persons': 'Người mất tích', 'Missing Senior Citizen': 'Người già bị mất tích', 'Missing Vulnerable Person': 'Người dễ bị tổn thương mất tích', 'Missing': 'Mất tích', 'Mobile Phone Number': 'Số di động', 'Mobile Phone': 'Số di động', 'Mobile': 'Di động', 'Mode': 'Phương thức', 'Model/Type': 'Đời máy/ Loại', 'Modem settings updated': 'Cài đặt mô đem được đã được cập nhật', 'Modem': 'Mô đem', 'Moderator': 'Điều tiết viên', 'Modify Feature: Select the feature you wish to deform & then Drag one of the dots to deform the feature in your chosen manner': 'Sửa đổi tính năng: Lựa chọn tính năng bạn muốn để thay đổi và sau đó kéo vào một trong điểm để thay đổi tính năng theoh bạn chọn', 'Modify Information on groups and individuals': 'Thay đổi thông tin của nhóm và cá nhân', 'Module Administration': 'Quản trị Mô-đun', 'Monday': 'Thứ Hai', 'Monetization Details': 'Thông tin lưu hành tiền tệ', 'Monetization Report': 'Báo cáo lưu hành tiền tệ', 'Monetization': 'Lưu hành tiền tệ', 'Monitoring and Evaluation': 'Đánh giá và Giám sát', 'Month': 'Tháng', 'Monthly': 'Hàng tháng', 'Months': 'Tháng', 'More Options': 'Mở rộng chức năng', 'Morgue': 'Phòng tư liệu', 'Morgues': 'Phòng tư liệu', 'Moustache': 'Râu quai nón', 'Move Feature: Drag feature to desired location': 'Di chuyển tính năng: Kéo tính năng tới vị trí mong muốn', 'Multi-Option': 'Đa lựa chọn', 'Multiple Matches': 'Nhiều kết quả phù hợp', 'Multiple': 'Nhiều', 'Muslim': 'Tín đồ Hồi giáo', 'Must a location have a parent location?': 'Một địa danh cần phải có địa danh trực thuộc đi kèm?', 'My Logged Hours': 'Thời gian truy cập của tôi', 'My Open Tasks': 'Nhiệm vụ của tôi', 'My Profile': 'Hồ sơ của tôi', 'My Tasks': 'Nhiệm vụ của tôi', 'My reports': 'Báo cáo của tôi', 'N/A': 'Không xác định', 'NDRT (National Disaster Response Teams)': 'Đội ứng phó thảm họa cấp TW', 'NO': 'KHÔNG', 'NUMBER_GROUPING': 'SỐ_THEO NHÓM', 'NZSEE Level 1': 'Mức 1 NZSEE', 'NZSEE Level 2': 'Mức 2 NZSEE', 'Name and/or ID': 'Tên và/hoặc tên truy nhập', 'Name field is required!': 'Bắt buộc phải điền Tên!', 'Name of Award': 'Tên phần thưởng', 'Name of Driver': 'Tên tài xế', 'Name of Father': 'Tên cha', 'Name of Institute': 'Trường Đại học/ Học viện', 'Name of Mother': 'Tên mẹ', 'Name of Storage Bin Type.': 'Tên loại Bin lưu trữ', 'Name of the person in local language and script (optional).': 'Tên theo ngôn ngữ và chữ viết địa phương (tùy chọn)', 'Name of the repository (for you own reference)': 'Tên của kho (để bạn tham khảo)', 'Name': 'Tên', 'National ID Card': 'Chứng minh nhân dân', 'National NGO': 'Các tổ chức phi chính phủ ', 'National Societies': 'Hội Quốc gia', 'National Society / Branch': 'Trung ương/ Tỉnh, thành Hội', 'National Society Details': 'Thông tin về Hội Quốc gia', 'National Society added': 'Hội Quốc gia đã được thêm', 'National Society deleted': 'Hội Quốc gia đã được xóa', 'National Society updated': 'Hội Quốc gia đã được cập nhật', 'National Society': 'Hội QG', 'Nationality of the person.': 'Quốc tịch', 'Nationality': 'Quốc tịch', 'Nautical Accident': 'Tai nạn trên biển', 'Nautical Hijacking': 'Cướp trên biển', 'Need to configure Twitter Authentication': 'Cần thiết lập cấu hình Xác thực Twitter', 'Need to select 2 Locations': 'Cần chọn 2 vị trí', 'Need to specify a location to search for.': 'Cần xác định cụ thể một địa điểm để tìm kiếm', 'Need to specify a role!': 'Yêu cầu xác định vai trò', 'Needs Maintenance': 'Cần bảo dưỡng', 'Never': 'Không bao giờ', 'New Annual Budget created': 'Ngân sách hàng năm mới đã được tạo', 'New Certificate': 'Chứng chỉ mới', 'New Checklist': 'Checklist mới', 'New Entry in Asset Log': 'Ghi chép mới trong nhật ký tài sản', 'New Entry': 'Hồ sơ mới', 'New Job Title': 'Chức vụ công việc mới', 'New Organization': 'Tổ chức mới', 'Add Output': 'Kết quả đầu ra mới', 'New Post': 'Bài đăng mới', 'New Record': 'Hồ sơ mới', 'New Request': 'Yêu cầu mới', 'New Role': 'Vai trò mới', 'New Stock Adjustment': 'Điều chỉnh mới về kho hàng', 'New Support Request': 'Yêu cầu hỗ trợ mới', 'New Team': 'Đội/Nhóm mới', 'New Theme': 'Chủ đề mới', 'New Training Course': 'Khóa tập huấn mới', 'New Training Event': 'Khóa tập huấn mới', 'New User': 'Người sử dụng mới', 'New': 'Thêm mới', 'News': 'Tin tức', 'Next View': 'Hiển thị tiếp', 'Next run': 'Lần chạy tiếp theo', 'Next': 'Trang sau', 'No Activities Found': 'Không tìm thấy hoạt động nào', 'No Activity Types Found': 'Không tìm thấy loại hình hoạt động nào', 'No Addresses currently registered': 'Hiện tại chưa đăng ký Địa chỉ', 'No Affiliations defined': 'Không xác định được liên kết nào', 'No Aid Requests have been made yet': 'Chưa có yêu cầu cứu trợ nào được tạo', 'No Alternative Items currently registered': 'Hiện không có mặt hàng thay thế nào được đăng ký', 'No Assessment Answers': 'Không có câu trả lời cho đánh giá', 'No Assessment Questions': 'Không có câu hỏi đánh giá', 'No Assessment Templates': 'Không có mẫu đánh giá', 'No Assessments currently registered': 'Chưa đăng ký trị giá tính thuế', 'No Assets currently registered': 'Hiện không có tài sản nào được đăng ký', 'No Awards found': 'Không tìm thấy thônng tin về khen thưởng', 'No Base Layer': 'Không có lớp bản đồ cơ sở', 'No Beneficiaries Found': 'Không tìm thấy người hưởng lợi nào', 'No Beneficiary Types Found': 'Không tìm thấy nhóm người hưởng lợi nào', 'No Branch Organizations currently registered': 'Hiện không có tổ chức cơ sở nào được đăng ký', 'No Brands currently registered': 'Hiện không có nhãn hàng nào được đăng ký', 'No Catalog Items currently registered': 'Hiện không có mặt hàng nào trong danh mục được đăng ký', 'No Catalogs currently registered': 'Hiện không có danh mục nào được đăng ký', 'No Category<>Sub-Category<>Catalog Relation currently registered': 'Hiện tại chưa có Category<>Sub-Category<>Catalog Relation được đăng ký', 'No Clusters currently registered': 'Hiện không có nhóm nào được đăng ký', 'No Commitment Items currently registered': 'Hiện không có hàng hóa cam kết nào được đăng ký', 'No Commitments': 'Không có cam kết nào', 'No Communities Found': 'Không tìm thấy cộng đồng nào', 'No Completed Assessment Forms': 'Không có mẫu khảo sát đánh giá hoàn thiện nào', 'No Contacts Found': 'Không tìm thấy liên lạc nào', 'No Data currently defined for this Theme Layer': 'Hiện không xác định được dữ liệu nào cho lớp chủ đề này', 'No Data': 'Không có dữ liệu', 'No Disaster Assessments': 'Không có đánh giá thảm họa nào', 'No Distribution Items currently registered': 'Chưa đăng ký danh sách hàng hóa đóng góp', 'No Documents found': 'Không tìm thấy tài liệu nào', 'No Donors currently registered': 'Hiện không có nhà tài trợ nào được đăng ký', 'No Emails currently in InBox': 'Hiện không có thư điện tử nào trong hộp thư đến', 'No Entries Found': 'Không có hồ sơ nào được tìm thấy', 'No Facilities currently registered': 'Hiện không có trang thiết bị nào được đăng ký', 'No Facility Types currently registered': 'Không có bộ phận nào được đăng ký', 'No Feature Layers currently defined': 'Hiện không xác định được lớp đặc điểm nào', 'No File Chosen': 'Chưa chọn File', 'No Flood Reports currently registered': 'Chưa đăng ký báo cáo lũ lụt', 'No Frameworks found': 'Không tìm thấy khung chương trình nào', 'No Groups currently defined': 'Hiện tại không xác định được nhóm', 'No Groups currently registered': 'Hiện không có nhóm nào được đăng ký', 'No Hazards currently registered': 'Hiện không có hiểm họa nào được đăng ký', 'No Hospitals currently registered': 'Chưa có bệnh viện nào đăng ký', 'No Human Resources currently assigned to this incident': 'Hiện không có nhân sự nào được phân công cho công việc này', 'No Identities currently registered': 'Hiện không có nhận diện nào được đăng ký', 'No Image': 'Không có ảnh', 'No Images currently registered': 'Hiện không có hình ảnh nào được đăng ký', 'No Incident Reports currently registered': 'Hiện không có báo cáo sự việc nào được đăng ký', 'No Incidents currently registered': 'Chưa sự việc nào được đưa lên', 'No Inventories currently have suitable alternative items in stock': 'Hiện không có bảng kiểm kê nào có mặt hàng thay thế trong kho', 'No Inventories currently have this item in stock': 'Hiện không có bảng kiểm kê nào có mặt hàng này trong kho', 'No Item Categories currently registered': 'Hiện không có nhóm mặt hàng nào được đăng ký', 'No Item Packs currently registered': 'Hiện không có gói hàng nào được đăng ký', 'No Items currently registered': 'Hiện không có mặt hàng nào được đăng ký', 'No Items currently requested': 'Hiện tại không có hàng hóa nào được yêu cầu', 'No Kits': 'Không có thùng hành nào', 'No Layers currently configured in this Profile': 'Hiện không có lớp nào được tạo ra trong hồ sơ này', 'No Layers currently defined in this Symbology': 'Hiện không xác định được lớp nào trong biểu tượng này', 'No Layers currently defined': 'Hiện không xác định được lớp nào', 'No Location Hierarchies currently defined': 'Hiện không xác định được thứ tự địa điểm', 'No Locations Found': 'Không tìm thấy địa điểm nào', 'No Locations currently available': 'Hiện không có địa điểm', 'No Locations currently registered': 'Hiện tại chưa có vị trí nào được đăng ký', 'No Mailing List currently established': 'Hiện không có danh sách địa chỉ thư nào được thiết lập', 'No Map Profiles currently defined': 'Hiện không xác định được cài đặt cấu hình bản đồ nào', 'No Markers currently available': 'Hiện không có dấu mốc nào', 'No Match': 'Không phù hợp', 'No Matching Catalog Items': 'Không có mặt hàng nào trong danh mục phù hợp', 'No Matching Items': 'Không có mặt hàng phù hợp', 'No Matching Records': 'Không có hồ sơ phù hợp', 'No Members currently registered': 'Hiện không có hội viên nào được đăng ký', 'No Memberships currently defined': 'Chưa xác nhận đăng ký thành viên', 'No Messages currently in Outbox': 'Hiện không có thư nào trong hộp thư đi', 'No Metadata currently defined': 'Hiện tại không xác định được loại siêu dữ liệu', 'No Milestones Found': 'Không tìm thấy sự kiện quan trọng nào', 'No Office Types currently registered': 'Hiện không có loại hình văn phòng nào được đăng ký', 'No Offices currently registered': 'Hiện không có văn phòng nào được đăng ký', 'No Open Tasks for %(project)s': 'Không có công việc chưa được xác định nào cho %(project)s', 'No Orders registered': 'Không có đề nghị nào được đăng ký', 'No Organization Domains currently registered': 'Không có lĩnh vực hoạt động của tổ chức nào được đăng ký', 'No Organization Types currently registered': 'Hiện không có loại hình tổ chức nào được đăng ký', 'No Organizations currently registered': 'Hiện không có tổ chức nào được đăng ký', 'No Organizations for Project(s)': 'Không có tổ chức cho dự án', 'No Organizations found for this Framework': 'Không tìm thấy tổ chức trong chương trình khung này', 'No Packs for Item': 'Không có hàng đóng gói', 'No Partner Organizations currently registered': 'Hiện không có tổ chức đối tác nào được đăng ký', 'No People currently committed': 'Hiện không có người nào cam kết', 'No People currently registered in this shelter': 'Không có người đăng ký cư trú ở đơn vị này', 'No Persons currently registered': 'Hiện không có người nào đăng ký', 'No Persons currently reported missing': 'Hiện tại không thấy báo cáo về người mất tích', 'No Photos found': 'Không tìm thấy hình ảnh', 'No PoIs available.': 'Không có PoIs', 'No Presence Log Entries currently registered': 'Hiện chư có ghi chép nhật ký được đăng ký', 'No Professional Experience found': 'Không tìm thấy kinh nghiệm nghề nghiệp', 'No Profiles currently have Configurations for this Layer': 'Hiện không có hồ sơ nào có cài đặt cấu hình cho lớp này', 'No Projections currently defined': 'Hiện không xác định được trình diễn nào', 'No Projects currently registered': 'Hiện không có dự án nào được đăng ký', 'No Question Meta-Data': 'Không có siêu dữ liệu lớn câu hỏi', 'No Ratings for Skill Type': 'Không xếp loại cho loại kỹ năng', 'No Received Shipments': 'Không có chuyến hàng nào được nhận', 'No Records currently available': 'Hiện tại không có hồ sơ nào sẵn có', 'No Red Cross & Red Crescent National Societies currently registered': 'Hiện không có Hội Chữ thập đỏ và Trăng lưỡi liềm đỏ quốc gia nào được đăng ký', 'No Request Items currently registered': 'Hiện không có mặt hàng đề nghị nào được đăng ký', 'No Requests': 'Không có đề nghị', 'No Roles defined': 'Không có vai trò nào được xác định ', 'No Rooms currently registered': 'Hiện không có phòng nào được đăng ký', 'No Search saved': 'Không có tìm kiếm nào được lưu', 'No Sectors currently registered': 'Hiện không có lĩnh vực nào được đăng ký', 'No Sent Shipments': 'Không có chuyến hàng nào được gửi', 'No Settings currently defined': 'Hiện không có cài đặt nào được xác định', 'No Shelters currently registered': 'Hiện tại chưa đăng ký nơi cư trú', 'No Shipment Items': 'Không có hàng hóa vận chuyển nào', 'No Shipment Transit Logs currently registered': 'Không có số liệu lưu về vận chuyển được ghi nhận', 'No Skill Types currently set': 'Chưa cài đặt loại kỹ năng', 'No Skills currently requested': 'Hiện không có kỹ năng nào được đề nghị', 'No Staff currently registered': 'Hiện không có cán bộ nào được đăng ký', 'No Statuses currently registered': 'Hiện không có tình trạng nào được đăng ký', 'No Stock currently registered in this Warehouse': 'Hiện không có hàng hóa nào được đăng ký trong nhà kho này', 'No Stock currently registered': 'Hiện không có hàng hóa nào được đăng ký', 'No Storage Bin Type currently registered': 'Chưa đăng ký Loại Bin lưu trữ', 'No Suppliers currently registered': 'Hiện không có nhà cung cấp nào được đăng ký', 'No Support Requests currently registered': 'Hiện tại không có yêu cầu hỗ trợ nào được đăng ký', 'No Survey Questions currently registered': 'Hiện tại không có câu hỏi khảo sát nào được đăng ký', 'No Symbologies currently defined for this Layer': 'Hiện không xác định được biểu tượng nào cho lớp này', 'No Symbologies currently defined': 'Hiện không xác định được biểu tượng nào', 'No Tasks Assigned': 'Không có công việc nào được giao', 'No Teams currently registered': 'Hiện không có Đội/Nhóm nào được đăng ký', 'No Template Sections': 'Không có phần về biểu mẫu', 'No Themes currently registered': 'Hiện không có chủ đề nào được đăng ký', 'No Tickets currently registered': 'Hiện tại chưa đăng ký Ticket ', 'No Time Logged': 'Không có thời gian nào được ghi lại', 'No Twilio Settings currently defined': 'Hiện không có cài đặt Twilio nào được xác định', 'No Units currently registered': 'Chưa đăng ký tên đơn vị', 'No Users currently registered': 'Hiện không có người sử dụng nào được đăng ký', 'No Vehicles currently assigned to this incident': 'Hiện không có phương tiện vận chuyển nào được điều động cho sự việc này', 'No Volunteer Cluster Positions': 'Không có vị trí của nhóm tình nguyện viên', 'No Volunteer Cluster Types': 'Không có loại hình nhóm tình nguyện viên', 'No Volunteer Clusters': 'Không có nhóm tình nguyện viên', 'No Volunteers currently registered': 'Hiện không có tình nguyện viên nào được đăng ký', 'No Warehouses currently registered': 'Hiện không có nhà kho nào được đăng ký', 'No access at all': 'Không truy cập', 'No access to this record!': 'Không tiếp cận được bản lưu này!', 'No annual budgets found': 'Không tìm thấy bản ngân sách năm', 'No contact information available': 'Không có thông tin liên hệ', 'No contact method found': 'Không tìm thấy cách thức liên hệ', 'No contacts currently registered': 'Chưa đăng ký thông tin liên lạc', 'No data available in table': 'Không có dữ liệu trong bảng', 'No data available': 'Không có dữ liệu sẵn có', 'No data in this table - cannot create PDF!': 'Không có dữ liệu trong bảng - không thể tạo file PDF', 'No databases in this application': 'Không có cơ sở dữ liệu trong ứng dụng này', 'No demographic data currently available': 'Hiện không xác định được dữ liệu nhân khẩu', 'No demographic sources currently defined': 'Hiện không xác định được nguồn nhân khẩu', 'No demographics currently defined': 'Hiện không xác định được số liệu thống kê dân số', 'No education details currently registered': 'Hiện không có thông tin về học vấn được đăng ký', 'No entries currently available': 'Hiện chưa có hồ sơ nào', 'No entries found': 'Không có hồ sơ nào được tìm thấy', 'No entry available': 'Chưa có hồ sơ nào', 'No file chosen': 'Chưa chọn file', 'No forms to the corresponding resource have been downloaded yet.': 'Không tải được mẫu nào cho nguồn tài nguyên tương ứng', 'No further users can be assigned.': 'Không thể phân công thêm người sử dụng', 'No items currently in stock': 'Hiện không có mặt hàng nào trong kho', 'No items have been selected for shipping.': 'Không có mặt hàng nào được lựa chọn để vận chuyển', 'No jobs configured yet': 'Chưa thiết lập công việc', 'No jobs configured': 'Không thiết lập công việc', 'No linked records': 'Không có bản thu liên quan', 'No location information defined!': 'Không xác định được thông tin về địa điểm!', 'No match': 'Không phù hợp', 'No matching element found in the data source': 'Không tìm được yếu tố phù hợp từ nguồn dữ liệu', 'No matching records found': 'Không tìm thấy hồ sơ phù hợp', 'No matching result': 'Không có kết quả phù hợp', 'No membership types currently registered': 'Hiện không có loại hình hội viên nào được đăng ký', 'No messages in the system': 'Không có thư nào trong hệ thống', 'No offices registered for organisation': 'Không có văn phòng nào đăng ký tổ chức', 'No options available': 'Không có lựa chọn sẵn có', 'No outputs defined': 'Không tìm thấy đầu ra', 'No pending registrations found': 'Không tìm thấy đăng ký đang chờ', 'No pending registrations matching the query': 'Không tìm thấy đăng ký khớp với yêu cầu', 'No problem group defined yet': 'Chưa xác định được nhóm gặp nạn', 'No records in this resource': 'Không có hồ sơ nào trong tài nguyên mới', 'No records in this resource. Add one more records manually and then retry.': 'Không có hồ sơ nào trong tài nguyên này. Thêm một hoặc nhiều hồ sơ một cách thủ công và sau đó thử lại ', 'No records to delete': 'Không có bản thu để xóa', 'No records to review': 'Không có hồ sơ nào để rà soát', 'No report available.': 'Không có báo cáo', 'No reports available.': 'Không có báo cáo nào', 'No repositories configured': 'Không có chỗ chứa hàng nào được tạo ra', 'No requests found': 'Không tìm thấy yêu cầu', 'No resources configured yet': 'Chưa có nguồn lực nào được tạo ra', 'No role to delete': 'Không có chức năng nào để xóa', 'No roles currently assigned to this user.': 'Hiện tại không có chức năng nào được cấp cho người sử dụng này', 'No service profile available': 'Không có hồ sơ đăng ký dịch vụ nào', 'No staff or volunteers currently registered': 'Hiện không có cán bộ hay tình nguyện viên nào được đăng ký', 'No stock adjustments have been done': 'Không có bất kỳ điều chỉnh nào về hàng hóa', 'No synchronization': 'Chưa đồng bộ hóa', 'No tasks currently registered': 'Hiện không có công việc nào được đăng ký', 'No template found!': 'Không tìm thấy mẫu', 'No themes found': 'Không tìm thấy chủ đề nào', 'No translations exist in spreadsheet': 'Không có phần dịch trong bảng tính', 'No users with this role at the moment.': 'Hiện tại không có người sử dụng nào có chức năng này', 'No valid data in the file': 'Không có dữ liệu có giá trị trong tệp tin', 'No volunteer information registered': 'Chưa đăng ký thông tin tình nguyện viên', 'No vulnerability aggregated indicators currently defined': 'Hiện không xác định được chỉ số tổng hợp về tình trạng dễ bị tổn thương', 'No vulnerability data currently defined': 'Hiện không xác định được dữ liệu về tình trạng dễ bị tổn thương', 'No vulnerability indicator Sources currently defined': 'Hiện không xác định được nguồn chỉ số về tình trạng dễ bị tổn thương', 'No vulnerability indicators currently defined': 'Hiện không xác định được chỉ số về tình trạng dễ bị tổn thương', 'No': 'Không', 'Non-Communicable Diseases': 'Bệnh không lây nhiễm', 'None (no such record)': 'Không cái nào (không có bản lưu như thế)', 'None': 'Không có', 'Nonexistent or invalid resource': 'Không tồn tại hoặc nguồn lực không hợp lệ', 'Noodles': 'Mì', 'Normal Job': 'Công việc hiện nay', 'Normal': 'Bình thường', 'Not Authorized': 'Không được phép', 'Not Set': 'Chưa thiết đặt', 'Not implemented': 'Không được thực hiện', 'Not installed or incorrectly configured.': 'Không được cài đặt hoặc cài đặt cấu hình không chính xác', 'Not yet a Member of any Group': 'Hiện không có nhóm hội viên nào được đăng ký', 'Not you?': 'Không phải bạn chứ?', 'Note that when using geowebcache, this can be set in the GWC config.': 'Lưu ý khi sử dụng geowebcache, phần này có thể được cài đặt trong cấu hình GWC.', 'Note: Make sure that all the text cells are quoted in the csv file before uploading': 'Lưu ý: Đảm bảo tất cả các ô chữ được trích dẫn trong tệp tin csv trước khi tải lên', 'Notice to Airmen': 'Lưu ý cho phi công', 'Notification frequency': 'Tần suất thông báo', 'Notification method': 'Phương pháp thông báo', 'Notify': 'Thông báo', 'Number of Completed Assessment Forms': 'Số phiếu đánh giá đã được hoàn chỉnh', 'Number of People Affected': 'Số người bị ảnh hưởng', 'Number of People Dead': 'Số người chết', 'Number of People Injured': 'Số người bị thương', 'Number of People Required': 'Số người cần', 'Number of Rows': 'Số hàng', 'Number of alternative places for studying': 'Số địa điểm có thể dùng làm trường học tạm thời', 'Number of newly admitted patients during the past 24 hours.': 'Số lượng bệnh nhân tiếp nhận trong 24h qua', 'Number of private schools': 'Số lượng trường tư', 'Number of religious schools': 'Số lượng trường công giáo', 'Number of vacant/available beds in this hospital. Automatically updated from daily reports.': 'Số các giường bệnh trống trong bệnh viện. Tự động cập nhật từ các báo cáo hàng ngày.', 'Number or Label on the identification tag this person is wearing (if any).': 'Số hoặc nhãn trên thẻ nhận diện mà người này đang đeo (nếu có)', 'Number': 'Số', 'Number/Percentage of affected population that is Female & Aged 0-5': 'Đối tượng nữ trong độ tuổi 0-5 tuổi chịu ảnh hưởng của thiên tai ', 'Number/Percentage of affected population that is Female & Aged 6-12': 'Đối tượng nữ trong độ tuổi 6-12 chịu ảnh hưởng của thiên tai', 'Number/Percentage of affected population that is Male & Aged 0-5': 'Đối tượng nam trong độ tuổi 0-5 chịu ảnh hưởng từ thiên tai', 'Number/Percentage of affected population that is Male & Aged 18-25': 'Đối tượng nam giới trong độ tuổi 18-25 chịu ảnh hưởng của thiên tai', 'Number/Percentage of affected population that is Male & Aged 26-60': 'Đối tượng là Nam giới và trong độ tuổi từ 26-60 chịu ảnh hưởng lớn từ thiên tai', 'Numbers Only': 'Chỉ dùng số', 'Numeric': 'Bằng số', 'Nutrition': 'Dinh dưỡng', 'OCR Form Review': 'Mẫu OCR tổng hợp', 'OCR module is disabled. Ask the Server Administrator to enable it.': 'Module OCR không được phép. Yêu cầu Quản trị mạng cho phép', 'OCR review data has been stored into the database successfully.': 'Dự liệu OCR tổng hợp đã được lưu thành công vào kho dữ liệu', 'OK': 'Đồng ý', 'OSM file generation failed!': 'Chiết xuất tệp tin OSM đã bị lỗi!', 'OSM file generation failed: %s': 'Chiết xuất tệp tin OSM đã bị lỗi: %s', 'OTHER DATA': 'DỮ LIỆU KHÁC', 'OTHER REPORTS': 'BÁO CÁO KHÁC', 'OVERALL RESILIENCE': 'SỰ BỀN VỮNG TỔNG THỂ', 'Object': 'Đối tượng', 'Objectives': 'Mục tiêu', 'Observer': 'Người quan sát', 'Obsolete': 'Đã thôi hoạt động', 'Obstetrics/Gynecology': 'Sản khoa/Phụ khoa', 'Office Address': 'Địa chỉ văn phòng', 'Office Details': 'Thông tin về văn phòng', 'Office Phone': 'Điện thoại văn phòng', 'Office Type Details': 'Thông tin về loại hình văn phòng', 'Office Type added': 'Loại hình văn phòng được thêm vào', 'Office Type deleted': 'Loại hình văn phòng đã xóa', 'Office Type updated': 'Loại hình văn phòng được cập nhật', 'Office Type': 'Loại hình văn phòng', 'Office Types': 'Loại văn phòng', 'Office added': 'Văn phòng được thêm vào', 'Office deleted': 'Văn phòng đã xóa', 'Office updated': 'Văn phòng được cập nhật', 'Office': 'Văn phòng', 'Office/Center': 'Văn phòng/Trung tâm', 'Office/Warehouse/Facility': 'Trụ sở làm việc', 'Officer': 'Chuyên viên', 'Offices': 'Văn phòng', 'Old': 'Người già', 'On Hold': 'Tạm dừng', 'On Order': 'Theo đề nghị', 'On by default?': 'Theo mặc định?', 'One item is attached to this shipment': 'Một mặt hàng được bổ sung thêm vào kiện hàng này', 'One-time costs': 'Chí phí một lần', 'Ongoing': 'Đang thực hiện', 'Only showing accessible records!': 'Chỉ hiển thị hồ sơ có thể truy cập', 'Only use this button to accept back into stock some items that were returned from a delivery to beneficiaries who do not record the shipment details directly into the system': 'Chỉ sử dụng nút này để nhận lại vào kho một số mặt hàng được trả lại do người nhận không trực tiếp lưu thông tin về kiện hàng này trên hệ thống', 'Only use this button to confirm that the shipment has been received by a destination which will not record the shipment directly into the system': 'Chỉ sử dụng nút này để xác nhận kiện hàng đã được nhận tại một địa điểm không trực tiếp lưu thông tin về kiện hàng trên hệ thống', 'Oops! Something went wrong...': 'Xin lỗi! Có lỗi gì đó…', 'Oops! something went wrong on our side.': 'Xin lỗi! Có trục trặc gì đó từ phía chúng tôi.', 'Opacity': 'Độ mờ', 'Open Incidents': 'Mở sự kiện', 'Open Map': 'Mở bản đồ', 'Open Tasks for %(project)s': 'Các công việc chưa xác định cho %(project)s', 'Open Tasks for Project': 'Mở nhiệm vụ cho một dự án', 'Open recent': 'Mở gần đây', 'Open': 'Mở', 'OpenStreetMap Layer': 'Mở lớp bản đồ đường đi', 'OpenStreetMap OAuth Consumer Key': 'Mã khóa người sử dụng OpenStreetMap OAuth', 'OpenStreetMap OAuth Consumer Secret': 'Bí mật người sử dụng OpenStreetMap OAuth', 'OpenWeatherMap Layer': 'Lớp OpenWeatherMap (bản đồ thời tiết mở)', 'Operating Rooms': 'Phòng điều hành', 'Operation not permitted': 'Hoạt động không được phép', 'Option Other': 'Lựa chọn khác', 'Option': 'Lựa chọn', 'Optional Subject to put into Email - can be used as a Security Password by the service provider': 'Chủ đề tùy chọn để đưa vào Thư điện tử - có thể được sử dụng như một Mật khẩu bảo mật do nhà cung cấp dịch vụ cung cấp', 'Optional password for HTTP Basic Authentication.': 'Mật khẩu tùy chọn cho Sự xác thực cơ bản HTTP.', 'Optional selection of a MapServer map.': 'Tùy chọn một bản đồ trong Máy chủ bản đồ.', 'Optional selection of a background color.': 'Tùy chọn màu sắc cho nền.', 'Optional selection of an alternate style.': 'Tùy chọn một kiểu dáng thay thế.', 'Optional username for HTTP Basic Authentication.': 'Tên truy nhập tùy chọn cho Sự xác thực cơ bản HTTP.', 'Optional. If you wish to style the features based on values of an attribute, select the attribute to use here.': 'Tùy chọn. Nếu bạn muốn tự tạo ra chức năng dựa trên các giá trị của một thuộc tính, hãy lựa chọn thuộc tính để sử dụng tại đây.', 'Optional. In GeoServer, this is the Workspace Namespace URI (not the name!). Within the WFS getCapabilities, this is the FeatureType Name part before the colon(:).': 'Tùy chọn. Trong máy chủ về địa lý, đây là Vùng tên Vùng làm việc URI (không phải là một tên gọi!). Trong lớp WFS theo khả năng là đường dẫn, đây là phần Tên loại chức năng trước dấu hai chấm (:).', 'Optional. The name of an element whose contents should be a URL of an Image file put into Popups.': 'Tùy chọn. Tên của một bộ phận có chứa nội dung là một URL của một tệp tin hình ảnh được đưa vào các cửa sổ tự động hiển thị.', 'Optional. The name of an element whose contents should be put into Popups.': 'Tùy chọn. Tên của một bộ phận có chứa nội dung được đưa vào các cửa sổ tự động hiển thị.', 'Optional. The name of the schema. In Geoserver this has the form http://host_name/geoserver/wfs/DescribeFeatureType?version=1.1.0&;typename=workspace_name:layer_name.': 'Tùy chọn. Tên của sơ đồ. Trong Geoserver tên này có dạng http://tên máy chủ/geoserver/wfs/Mô tả Loại Đặc điểm ?phiên bản=1.1.0&;nhập tên=vùng làm việc_tên:lớp_tên.', 'Options': 'Các lựa chọn', 'Or add a new language code': 'Hoặc chọn một ngôn ngữ khác', 'Order Created': 'Đơn hàng đã tạo', 'Order Details': 'Thông tin đơn hàng', 'Order Due %(date)s': 'Thời hạn của đơn hàng %(date)s', 'Order Item': 'Các mặt hàng trong đơn hàng', 'Order canceled': 'Đơn hàng đã bị hủy', 'Order updated': 'Đơn hàng được cập nhật', 'Order': 'Đơn hàng', 'Orders': 'Các đơn hàng', 'Organization Details': 'Thông tin về tổ chức', 'Organization Domain Details': 'Thông tin về lĩnh vực hoạt động của tổ chức', 'Organization Domain added': 'Lĩnh vực hoạt động của tổ chức đã được thêm', 'Organization Domain deleted': 'Lĩnh vực hoạt động của tổ chức đã được xóa', 'Organization Domain updated': 'Lĩnh vực hoạt động của tổ chức đã được cập nhật', 'Organization Domains': 'Loại hình hoạt động của tổ chức', 'Organization Registry': 'Đăng ký tổ chức', 'Organization Type Details': 'Thông tin về loại hình tổ chức', 'Organization Type added': 'Loại hình tổ chức được thêm vào', 'Organization Type deleted': 'Loại hình tổ chức đã xóa', 'Organization Type updated': 'Loại hình tổ chức được cập nhật', 'Organization Type': 'Loại hình tổ chức', 'Organization Types': 'Loại hình tổ chức', 'Organization Units': 'Đơn vị của tổ chức', 'Organization added to Framework': 'Tổ chức được thêm vào Chương trình khung', 'Organization added to Project': 'Tổ chức được thêm vào Dự án', 'Organization added': 'Tổ chức được thêm vào', 'Organization deleted': 'Tổ chức đã xóa', 'Organization removed from Framework': 'Tổ chức đã rút ra khỏi Chương trình khung', 'Organization removed from Project': 'Tổ chức đã rút ra khỏi Dự án', 'Organization updated': 'Tổ chức được cập nhật', 'Organization': 'Tổ chức', 'Organization/Supplier': 'Tổ chức/ Nhà cung cấp', 'Organizational Development': 'Phát triển tổ chức', 'Organizations / Teams / Facilities': 'Tổ chức/ Đội/ Cơ sở hạ tầng', 'Organizations': 'Tổ chức', 'Organized By': 'Đơn vị tổ chức', 'Origin': 'Nguồn gốc', 'Original Quantity': 'Số lượng ban đầu', 'Original Value per Pack': 'Giá trị ban đầu cho mỗi gói hàng', 'Other Address': 'Địa chỉ khác', 'Other Details': 'Thông tin khác', 'Other Education': 'Trình độ học vấn khác', 'Other Employment': 'Quá trình công tác ngoài Chữ thập đỏ', 'Other Evidence': 'Bằng chứng khác', 'Other Faucet/Piped Water': 'Các đường xả lũ khác', 'Other Inventories': 'Kho hàng khác', 'Other Isolation': 'Những vùng bị cô lập khác', 'Other Users': 'Người sử dụng khác', 'Other activities of boys 13-17yrs': 'Các hoạt động khác của nam thanh niên từ 13-17 tuổi', 'Other activities of boys <12yrs before disaster': 'Các hoạt động khác của bé trai dưới 12 tuổi trước khi xảy ra thiên tai', 'Other alternative places for study': 'Những nơi có thể dùng làm trường học tạm thời', 'Other assistance needed': 'Các hỗ trợ cần thiết', 'Other assistance, Rank': 'Những sự hỗ trợ khác,thứ hạng', 'Other data': 'Dữ liệu khác', 'Other factors affecting school attendance': 'Những yếu tố khác ảnh hưởng đến việc đến trường', 'Other reports': 'Báo cáo khác', 'Other settings can only be set by editing a file on the server': 'Cài đặt khác chỉ có thể được cài đặt bằng cách sửa đổi một tệp tin trên máy chủ', 'Other side dishes in stock': 'Món trộn khác trong kho', 'Other': 'Khác', 'Others': 'Khác', 'Outbound Mail settings are configured in models/000_config.py.': 'Cài đặt thư gửi ra nước ngoài được cấu hình thành các kiểu/000_config.py.', 'Outbox': 'Hộp thư đi', 'Outcomes, Impact, Challenges': 'Kết quả, Tác động, Thách thức', 'Outgoing SMS handler': 'Bộ quản lý tin nhắn SMS gửi đi', 'Output added': 'Đầu ra được thêm vào', 'Output deleted': 'Đầu ra đã xóa', 'Output updated': 'Đầu ra được cập nhật', 'Output': 'Đầu ra', 'Outputs': 'Các đầu ra', 'Over 60': 'Trên 60', 'Overall Resilience': 'Sự bền vững tổng thể', 'Overland Flow Flood': 'Dòng nước lũ lụt trên đất đất liền', 'Overlays': 'Lớp dữ liệu phủ', 'Owned By (Organization/Branch)': 'Sở hữu bởi (Tổ chức/ Chi nhánh)', 'Owned Records': 'Hồ sơ được sở hữu', 'Owned Resources': 'Nguồn lực thuộc sở hữu', 'Owner Driven Housing Reconstruction': 'Xây lại nhà theo nhu cầu của chủ nhà', 'Owning Organization': 'Tổ chức nắm quyền sở hữu', 'PASSA': 'Phương pháp tiếp cận có sự tham gia về nhận thức an toàn nhà ở', 'PIL (Python Image Library) not installed': 'PIL (thư viện ảnh Python) chưa cài đặt', 'PIL (Python Image Library) not installed, images cannot be embedded in the PDF report': 'PIL (thư viện ảnh Python) chưa được cài đặt, hình ảnh không thể gắn vào báo cáo dạng PDF', 'PIN number from Twitter (leave empty to detach account)': 'Số PIN từ Twitter (để trống để tách tài khoản)', 'PMER Development': 'Phát triển năng lực Báo cáo, đánh giá, giám sát và lập kế hoạch (PMER)', 'POOR': 'NGHÈO', 'POPULATION DENSITY': 'MẬT ĐỘ DÂN SỐ', 'POPULATION:': 'DÂN SỐ:', 'Pack': 'Gói', 'Packs': 'Các gói', 'Page': 'Trang', 'Paid': 'Đã nộp', 'Pan Map: keep the left mouse button pressed and drag the map': 'Dính bản đồ: giữ chuột trái và di chuột để di chuyển bản đồ', 'Parameters': 'Tham số', 'Parent Item': 'Mặt hàng cùng gốc', 'Parent Project': 'Dự án cùng gốc', 'Parent needs to be of the correct level': 'Phần tử cấp trên cần ở mức chính xác', 'Parent needs to be set for locations of level': 'Phần tử cấp trên cần được cài đặt cho các điểm mức độ', 'Parent needs to be set': 'Phần tử cấp trên cần được cài đặt', 'Parent': 'Phần tử cấp trên', 'Parser Setting deleted': 'Cài đặt của bộ phân tích đã xóa', 'Parser Settings': 'Các cài đặt của bộ phân tích', 'Parsing Settings': 'Cài đặt cú pháp', 'Parsing Status': 'Tình trạng phân tích', 'Parsing Workflow': 'Quá trình phân tích', 'Part of the URL to call to access the Features': 'Phần URL để gọi để truy cập tới chức năng', 'Part-time': 'Kiêm nhiệm', 'Partial': 'Một phần', 'Participant Details': 'Thông tin về người tham dự', 'Participant added': 'Người tham dự được thêm vào', 'Participant deleted': 'Người tham dự đã xóa', 'Participant updated': 'Người tham dự được cập nhật', 'Participant': 'Người tham dự', 'Participants': 'Những người tham dự', 'Participating Organizations': 'Các tổ chức tham gia', 'Partner National Society': 'Hội Quốc gia thành viên', 'Partner Organization Details': 'Thông tin về tổ chức đối tác', 'Partner Organization added': 'Tổ chức đối tác được thêm vào', 'Partner Organization deleted': 'Tổ chức đối tác đã xóa', 'Partner Organization updated': 'Tổ chức đối tác đã được cập nhật', 'Partner Organizations': 'Tổ chức đối tác', 'Partner': 'Đối tác', 'Partners': 'Đối tác', 'Partnerships': 'Hợp tác', 'Pass': 'Qua', 'Passport': 'Hộ chiếu', 'Password to use for authentication at the remote site.': 'Mật khẩu để sử dụng để xác định tại một địa điểm ở xa', 'Password': 'Mật khẩu', 'Pathology': 'Bệnh lý học', 'Patients': 'Bệnh nhân', 'Pediatric ICU': 'Chuyên khoa nhi', 'Pediatric Psychiatric': 'Khoa Tâm thần dành cho bệnh nhi', 'Pediatrics': 'Khoa Nhi', 'Peer Registration Request': 'yêu cầu đăng ký', 'Peer registration request added': 'Đã thêm yêu cầu đăng ký', 'Peer registration request updated': 'Cập nhật yêu cẩu đăng ký', 'Pending Requests': 'yêu cầu đang chờ', 'Pending': 'Đang xử lý', 'People Trapped': 'Người bị bắt', 'People': 'Người', 'Percentage': 'Phần trăm', 'Performance Rating': 'Đánh giá quá trình thực hiện', 'Permanent Home Address': 'Địa chỉ thường trú', 'Permanent': 'Biên chế', 'Person (Count)': 'Họ tên (Số lượng)', 'Person Details': 'Thông tin cá nhân', 'Person Registry': 'Cơ quan đăng ký nhân sự', 'Person added to Commitment': 'Người được thêm vào Cam kết', 'Person added to Group': 'Người được thêm vào Nhóm', 'Person added to Team': 'Người được thêm vào Đội', 'Person added': 'Người được thêm vào', 'Person deleted': 'Người đã xóa', 'Person details updated': 'Thông tin cá nhân được cập nhật', 'Person must be specified!': 'Người phải được chỉ định!', 'Person or OU': 'Người hay OU', 'Person removed from Commitment': 'Người đã xóa khỏi Cam kết', 'Person removed from Group': 'Người đã xóa khỏi Nhóm', 'Person removed from Team': 'Người đã xóa khỏi Đội', 'Person reporting': 'Báo cáo về người', 'Person who has actually seen the person/group.': 'Người đã thực sự nhìn thấy người/ nhóm', 'Person who observed the presence (if different from reporter).': 'Người quan sát tình hình (nếu khác với phóng viên)', 'Person': 'Họ tên', 'Personal Effects Details': 'Chi tiết ảnh hưởng cá nhân', 'Personal Profile': 'Hồ sơ cá nhân', 'Personal': 'Cá nhân', 'Personnel': 'Nhân viên', 'Persons with disability (mental)': 'Người tàn tật (về tinh thần)', 'Persons with disability (physical)': 'Người tàn tật (về thể chất)', 'Persons': 'Họ tên', 'Philippine Pesos': 'Đồng Pê sô Phi-lip-pin', 'Phone #': 'Số điện thoại', 'Phone 1': 'Điện thoại 1', 'Phone 2': 'Điện thoại 2', 'Phone number is required': 'Yêu cầu nhập số điện thoại', 'Phone': 'Điện thoại', 'Photo Details': 'Thông tin về ảnh', 'Photo added': 'Ảnh được thêm vào', 'Photo deleted': 'Ảnh đã xóa', 'Photo updated': 'Ảnh được cập nhật', 'Photograph': 'Ảnh', 'Photos': 'Những bức ảnh', 'Place of Birth': 'Nơi sinh', 'Place of registration for health-check and medical treatment': 'Nơi đăng ký khám chữa bệnh', 'Place of registration': 'Nơi đăng ký BHXH', 'Place on Map': 'Vị trí trên bản đồ', 'Place': 'Nơi', 'Planned %(date)s': 'Đã lập kế hoạch %(date)s', 'Planned Procurement Item': 'Mặt hàng mua sắm theo kế hoạch', 'Planned Procurement': 'Mua sắm theo kế hoạch', 'Planned Procurements': 'Những trường hợp mua sắm đã lập kế hoạch', 'Planned': 'Đã lập kế hoạch', 'Please do not remove this sheet': 'Xin vui lòng không xóa bảng này', 'Please enter a First Name': 'Vui lòng nhập họ', 'Please enter a Warehouse/Facility/Office OR an Organization': 'Xin vui lòng nhập một Nhà kho/ Bộ phận/ Văn phòng HOẶC một Tổ chức', 'Please enter a Warehouse/Facility/Office': 'Xin vui lòng nhập một Nhà kho/ Bộ phận/ Văn phòng', 'Please enter a first name': 'Xin vui lòng nhập một tên', 'Please enter a last name': 'Xin vui lòng nhập một họ', 'Please enter a number only': 'Vui lòng chỉ nhập một số', 'Please enter a valid email address': 'Vui lòng nhập địa chỉ email hợp lệ', 'Please enter a valid email address.': 'Vui lòng nhập địa chỉ email hợp lệ', 'Please enter an Organization/Supplier': 'Xin vui lòng nhập một Tổ chức/ Nhà cung cấp', 'Please enter the first few letters of the Person/Group for the autocomplete.': 'Xin vui lòng nhập những chữ cái đầu tiên của Tên/ Nhóm để tự động dò tìm.', 'Please enter the recipient(s)': 'Xin vui lòng nhập người nhận', 'Please fill this!': 'Xin vui lòng nhập thông tin vào đây!', 'Please provide the URL of the page you are referring to, a description of what you expected to happen & what actually happened.': 'Vui lòng cung cấp đường dẫn trang bạn muốn tham chiếu tới, miêu tả bạn thực sự muốn gì và cái gì đã thực sự xảy ra.', 'Please record Beneficiary according to the reporting needs of your project': 'Xin vui lòng lưu thông tin Người hưởng lợi theo những nhu cầu về báo cáo của dự án của bạn', 'Please review demographic data for': 'Xin vui lòng rà soát lại số liệu dân số để', 'Please review indicator ratings for': 'Xin vui lòng rà soát lại những đánh giá về chỉ số để', 'Please select another level': 'Xin vui lòng lựa chọn một cấp độ khác', 'Please select': 'Xin vui lòng lựa chọn', 'Please use this field to record any additional information, including a history of the record if it is updated.': 'Vui lòng sử dụng ô này để điền thêm các thông tin bổ sung, bao gồm cả lịch sử của hồ sơ nếu được cập nhật.', 'Please use this field to record any additional information, such as Ushahidi instance IDs. Include a history of the record if it is updated.': 'Xin vui lòng sử dụng ô này để điền thông tin bổ sung, như là tên truy nhập phiên bản Ushahidi. Bao gồm một lịch sử của hồ sơ nếu được cập nhật.', 'PoIs successfully imported.': 'PoIs đã được nhập thành công.', 'Poisoning': 'Sự nhiễm độc', 'Poisonous Gas': 'Khí độc', 'Policy Development': 'Xây dựng chính sách', 'Political Theory Education': 'Trình độ Lý luận chính trị', 'Pollution and other environmental': 'Ô nhiễm và các vấn đề môi trường khác', 'Polygon': 'Đa giác', 'Poor': 'Nghèo', 'Population Report': 'Báo cáo dân số', 'Population': 'Dân số', 'Popup Fields': 'Các trường cửa sổ tự động hiển thị', 'Popup Label': 'Nhãn cửa sổ tự động hiển thị', 'Porridge': 'Cháo yến mạch', 'Port Closure': 'Cổng đóng', 'Port': 'Cổng', 'Portable App': 'Ứng dụng di động', 'Portal at': 'Cổng thông tin', 'Position': 'Vị trí', 'Positions': 'Những vị trí', 'Post Graduate': 'Trên đại học', 'Postcode': 'Mã bưu điện', 'Posts': 'Thư tín', 'Poultry restocking, Rank': 'Thu mua gia cầm, thứ hạng', 'Power Failure': 'Lỗi nguồn điện', 'Powered by ': 'Cung cấp bởi', 'Powered by Sahana Eden': 'Cung cấp bởi Sahana Eden', 'Powered by': 'Cung cấp bởi', 'Preferred Name': 'Tên thường gọi', 'Presence Condition': 'Điều kiện xuất hiện', 'Presence Log': 'Lịch trình xuất hiện', 'Presence': 'Sự hiện diện', 'Previous View': 'Hiển thị trước', 'Previous': 'Trang trước', 'Primary': 'Sơ cấp', 'Principal Officer': 'Chuyên viên chính', 'Print / Share': 'In ra / Chia sẻ', 'Print Extent': 'Kích thước in', 'Print Map': 'In bản đồ', 'Printed from Sahana Eden': 'Được in từ Sahana Eden', 'Printing disabled since server not accessible': 'Chức năng in không thực hiện được do không thể kết nối với máy chủ', 'Priority from 1 to 9. 1 is most preferred.': 'Thứ tự ưu tiên từ 1 đến 9. 1 được ưu tiên nhất.', 'Priority': 'Ưu tiên', 'Privacy': 'Riêng tư', 'Private-Public Partnerships': 'Hợp tác tư nhân và nhà nước', 'Problem Administration': 'Quản lý vấn đề', 'Problem connecting to twitter.com - please refresh': 'Vấn đề khi kết nối với twitter.com - vui lòng làm lại', 'Problem updated': 'Đã cập nhật vấn đề', 'Problem': 'Vấn đề', 'Problems': 'Vấn đề', 'Procedure': 'Thủ tục', 'Process Received Shipment': 'Thủ tục nhận lô hàng', 'Process Shipment to Send': 'Thủ tục gửi lô hàng', 'Processing': 'Đang xử lý', 'Procured': 'Được mua', 'Procurement Plans': 'Kế hoạch mua sắm', 'Profession': 'Nghề nghiệp', 'Professional Experience Details': 'Thông tin về kinh nghiệm nghề nghiệp', 'Professional Experience added': 'Kinh nghiệm nghề nghiệp đã được thêm vào', 'Professional Experience deleted': 'Kinh nghiệm nghề nghiệp đã xóa', 'Professional Experience updated': 'Kinh nghiệp nghề nghiệp được cập nhật', 'Professional Experience': 'Kinh nghiệm nghề nghiệp', 'Profile Configuration removed': 'Cấu hình hồ sơ đã xóa', 'Profile Configuration updated': 'Cấu hình hồ sơ được cập nhật', 'Profile Configuration': 'Cấu hình hồ sơ', 'Profile Configurations': 'Các cấu hình hồ sơ', 'Profile Configured': 'Hồ sơ đã được cài đặt cấu hình', 'Profile Details': 'Thông tin về hồ sơ', 'Profile Picture': 'Ảnh hồ sơ', 'Profile Picture?': 'Ảnh đại diện?', 'Profile': 'Hồ sơ', 'Profiles': 'Các hồ sơ', 'Program (Count)': 'Chương trình (Số lượng)', 'Program Details': 'Thông tin về chương trình', 'Program Hours (Month)': 'Thời gian tham gia chương trình (Tháng)', 'Program Hours (Year)': 'Thời gian tham gia chương trình (Năm)', 'Program Hours': 'Thời gian tham gia chương trình', 'Program added': 'Chương trình đã được thêm vào', 'Program deleted': 'Chương trình đã xóa', 'Program updated': 'Chương trình được cập nhật', 'Program': 'Chương trình tham gia', 'Programme Planning and Management': 'Quản lý và lập kế hoạch Chương trình', 'Programme Preparation and Action Plan, Budget & Schedule': 'Xây dựng Chương trình và Kế hoạch hành động, lập ngân sách và lịch hoạt động', 'Programs': 'Chương trình', 'Project Activities': 'Các hoạt động của dự án', 'Project Activity': 'Hoạt động của dự án', 'Project Assessments and Planning': 'Lập kế hoạch và đánh giá dự án', 'Project Beneficiary Type': 'Nhóm người hưởng lợi của dự án', 'Project Beneficiary': 'Người hưởng lợi của dự án', 'Project Calendar': 'Lịch dự án', 'Project Details': 'Thông tin về dự án', 'Project Name': 'Tên dự án', 'Project Organization Details': 'Thông tin về tổ chức của dự án', 'Project Organization updated': 'Tổ chức dự án được cập nhật', 'Project Organizations': 'Các tổ chức dự án', 'Project Time Report': 'Báo cáo thời gian dự án', 'Project Title': 'Tên dự án', 'Project added': 'Dự án được thêm vào', 'Project deleted': 'Dự án đã xóa', 'Project not Found': 'Không tìm thấy dự án', 'Project updated': 'Dự án được cập nhật', 'Project': 'Dự án', 'Projection Details': 'Thông tin dự đoán', 'Projection Type': 'Loại dự báo', 'Projection added': 'Dự đoán được thêm vào', 'Projection deleted': 'Dự đoán đã xóa', 'Projection updated': 'Dự đoán được cập nhật', 'Projection': 'Dự đoán', 'Projections': 'Nhiều dự đoán', 'Projects Map': 'Bản đồ dự án', 'Projects': 'Dự án', 'Proposed': 'Được đề xuất', 'Protecting Livelihoods': 'Bảo vệ Sinh kế', 'Protocol': 'Giao thức', 'Provide Metadata for your media files': 'Cung cấp lý lịch dữ liệu cho các tệp tin đa phương tiện', 'Provide a password': 'Cung cấp mật khẩu', 'Provider': 'Nơi đăng ký BHYT', 'Province': 'Tỉnh/thành', 'Provision of Tools and Equipment': 'Cung cấp công cụ và trang thiết bị', 'Proxy Server URL': 'Máy chủ ủy nhiệm URL', 'Psychiatrics/Pediatric': 'Khoa thần kinh/Khoa nhi', 'Psychosocial Support': 'Hỗ trợ tâm lý', 'Public Administration Education': 'Trình độ Quản lý nhà nước', 'Public Event': 'Sự kiện dành cho công chúng', 'Public and private transportation': 'Phương tiện vận chuyển công cộng và cá nhân', 'Public': 'Công khai', 'Purchase Data': 'Dữ liệu mua hàng', 'Purchase Date': 'Ngày mua hàng', 'Purchase': 'Mua hàng', 'Purpose': 'Mục đích', 'Pyroclastic Flow': 'Dòng dung nham', 'Pyroclastic Surge': 'Núi lửa phun trào', 'Python Serial module not available within the running Python - this needs installing to activate the Modem': 'Modun số liệu Python không sẵn có trong Python đang chạy - cần cài đặt để kích hoạt modem', 'Python needs the ReportLab module installed for PDF export': 'Chưa cài đặt kho báo cáo', 'Python needs the xlrd module installed for XLS export': 'Chạy Python cần xlrd module được cài đặt để chiết xuất định dạng XLS', 'Python needs the xlwt module installed for XLS export': 'Chạy Python cần xlwt module được cài đặt để chiết xuất định dạng XLS', 'Quantity Committed': 'Số lượng cam kết', 'Quantity Fulfilled': 'Số lượng đã được cung cấp', 'Quantity Received': 'Số lượng đã nhận được', 'Quantity Returned': 'Số lượng được trả lại', 'Quantity Sent': 'Số lượng đã gửi', 'Quantity in Transit': 'Số lượng đang được vận chuyển', 'Quantity': 'Số lượng', 'Quarantine': 'Cách ly để kiểm dịch', 'Queries': 'Thắc mắc', 'Query Feature': 'Đặc tính thắc mắc', 'Query': 'Yêu cầu', 'Queryable?': 'Có thể yêu cầu?', 'Question Details': 'Thông tin về câu hỏi', 'Question Meta-Data Details': 'Chi tiết lý lịch dữ liệu về câu hỏi', 'Question Meta-Data added': 'Lý lịch dữ liệu về câu hỏi được thêm vào', 'Question Meta-Data deleted': 'Lý lịch dữ liệu về câu hỏi đã xóa', 'Question Meta-Data updated': 'Lý lịch dữ liệu về câu hỏi được cập nhật', 'Question Meta-Data': 'Lý lịch dữ liệu về câu hỏi', 'Question Summary': 'Tóm tắt câu hỏi', 'Question': 'Câu hỏi', 'RC historical employment record': 'Quá trình công tác tại Hội', 'READ': 'ĐỌC', 'REPORTS': 'BÁO CÁO', 'RESET': 'THIẾT LẬP LẠI', 'RESILIENCE': 'AN TOÀN', 'REST Filter': 'Bộ lọc REST', 'RFA Priorities': 'Những ưu tiên RFA', 'RFA1: Governance-Organisational, Institutional, Policy and Decision Making Framework': 'RFA1: Quản trị - Về tổ chức, Về thể chế, Chính sách và Khung ra quyết định', 'RFA2: Knowledge, Information, Public Awareness and Education': 'RFA2: Kiến thức, Thông tin, Nhận thức của công chúng và Đào tạo', 'RFA3: Analysis and Evaluation of Hazards, Vulnerabilities and Elements at Risk': 'RFA3: Phân tích và Đánh giá Hiểm họa, Tình trạng dễ bị tổn thương và Những yếu tố dễ gặp rủi ro', 'RFA4: Planning for Effective Preparedness, Response and Recovery': 'RFA4: Lập kế hoạch cho Chuẩn bị, Ứng phó và Phục hồi hiệu quả', 'RFA5: Effective, Integrated and People-Focused Early Warning Systems': 'RFA5: Hệ thống cảnh báo sớm hiệu quả, tích hợp và chú trọng vào con người', 'RFA6: Reduction of Underlying Risk Factors': 'RFA6: Giảm thiểu những nhân tố rủi ro cơ bản', 'Race': 'Chủng tộc', 'Radio Callsign': 'Tín hiệu điện đàm', 'Radiological Hazard': 'Hiểm họa phóng xạ', 'Railway Accident': 'Tai nạn đường sắt', 'Railway Hijacking': 'Cướp tàu hỏa', 'Rain Fall': 'Mưa lớn', 'Rapid Assessments': 'Đánh giá nhanh', 'Rapid Close Lead': 'Nhanh chóng đóng lại', 'Rapid Data Entry': 'Nhập dữ liệu nhanh', 'Raw Database access': 'Truy cập cơ sở dữ liệu gốc', 'Ready': 'Sẵn sàng', 'Reason': 'Lý do', 'Receive %(opt_in)s updates:': 'Nhận %(opt_in)s cập nhật', 'Receive New Shipment': 'Nhận lô hàng mới', 'Receive Shipment': 'Nhận lô hàng', 'Receive updates': 'Nhập cập nhật', 'Receive': 'Nhận', 'Receive/Incoming': 'Nhận/ Đến', 'Received By': 'Nhận bởi', 'Received Shipment Details': 'Thông tin về lô hàng nhận', 'Received Shipment canceled': 'Lô hàng nhận đã bị hoãn', 'Received Shipment updated': 'Lô hàng nhận đã được cập nhật', 'Received Shipments': 'Hàng nhận', 'Received date': 'Ngày nhận', 'Received': 'Đã được nhận', 'Received/Incoming Shipments': 'Lô hàng nhận/đến', 'Receiving Inventory': 'Nhận hàng tồn kho', 'Reception': 'Nhận', 'Recipient': 'Người nhận', 'Recipient(s)': 'Người nhận', 'Recipients': 'Những người nhận', 'Record Deleted': 'Hồ sơ bị xóa', 'Record Details': 'Chi tiết hồ sơ', 'Record added': 'Hồ sơ được thêm', 'Record already exists': 'Bản lưu đã tồn tại', 'Record approved': 'Hồ sơ được chấp thuân', 'Record could not be approved.': 'Hồ sơ không được chấp thuận', 'Record could not be deleted.': 'Hồ sơ không thể xóa', 'Record deleted': 'Hồ sơ bị xóa', 'Record not found!': 'Không tìm thấy bản lưu!', 'Record not found': 'Không tìm thấy hồ sơ', 'Record updated': 'Hồ sơ được cập nhật', 'Record': 'Hồ sơ', 'Records': 'Các hồ sơ', 'Recovery Request added': 'Đã thêm yêu cầu phục hồi', 'Recovery Request deleted': 'phục hồi các yêu cầu bị xóa', 'Recovery Request updated': 'Cập nhật Yêu cầu phục hồi', 'Recovery Request': 'Phục hồi yêu cầu', 'Recovery Requests': 'Phục hồi yêu cầu', 'Recovery': 'Phục hồi', 'Recurring costs': 'Chi phí định kỳ', 'Recurring': 'Định kỳ', 'Red Cross & Red Crescent National Societies': 'Các Hội Chữ thập đỏ & Trăng lưỡi liềm đỏ Quốc gia', 'Red Cross Employment History': 'Quá trình công tác trong Chữ thập đỏ', 'Refresh Rate (seconds)': 'Tỉ lệ làm mới (giây)', 'Region Location': 'Địa điểm vùng', 'Region': 'Vùng', 'Regional': 'Địa phương', 'Register As': 'Đăng ký là', 'Register Person into this Shelter': 'Đăng ký cá nhân vào nơi cư trú', 'Register Person': 'Đăng ký Cá nhân', 'Register for Account': 'Đăng ký tài khoản', 'Register': 'Đăng ký', 'Registered People': 'Những người đã đăng ký', 'Registered users can %(login)s to access the system': 'Người sử dụng đã đăng ký có thể %(đăng nhập)s để truy cập vào hệ thống', 'Registered users can': 'Người dùng đã đăng ký có thể', 'Registration Details': 'Chi tiết đăng ký', 'Registration added': 'Bản đăng ký đã được thêm', 'Registration not permitted': 'Việc đăng ký không được chấp thuận', 'Reject request submitted': 'Đề nghị từ chối đã được gửi đi', 'Reject': 'Từ chối', 'Relationship': 'Mối quan hệ', 'Relief Team': 'Đội cứu trợ', 'Religion': 'Tôn giáo', 'Reload': 'Tải lại', 'Remarks': 'Những nhận xét', 'Remember Me': 'Duy trì đăng nhập', 'Remote Error': 'Lỗi từ xa', 'Remove Feature: Select the feature you wish to remove & press the delete key': 'Chức năng gỡ bỏ: Lựa chọn chức năng bạn muốn gõ bỏ và ấn phím xóa', 'Remove Human Resource from this incident': 'Xóa nguồn Nhân lực khỏi sự việc này', 'Remove Layer from Profile': 'Xóa Lớp khỏi Hồ sơ', 'Remove Layer from Symbology': 'Xóa Lớp khỏi Biểu tượng', 'Remove Organization from Project': 'Xóa Tổ chức khỏi Dự án', 'Remove Person from Commitment': 'Xóa Người khỏi Cam kết', 'Remove Person from Group': 'Xóa Người khỏi Nhóm', 'Remove Person from Team': 'Xóa Người khỏi Đội', 'Remove Profile Configuration for Layer': 'Xóa Cấu hình hồ sơ cho Lớp', 'Remove Skill from Request': 'Xóa Kỹ năng khỏi Đề nghị', 'Remove Skill': 'Xóa Kỹ năng', 'Remove Stock from Warehouse': 'Xóa Hàng hóa khỏi Nhà kho', 'Remove Symbology from Layer': 'Xóa Biểu tượng khỏi Lớp', 'Remove Vehicle from this incident': 'Xóa Phương tiện khỏi sự việc này', 'Remove all log entries': 'Xóa toàn bộ ghi chép nhật ký', 'Remove all': 'Gỡ bỏ toàn bộ', 'Remove existing data before import': 'Xóa dữ liệu đang tồn tại trước khi nhập', 'Remove selection': 'Gỡ bỏ có lựa chọn', 'Remove this entry': 'Gỡ bỏ hồ sơ này', 'Remove': 'Gỡ bỏ', 'Reopened': 'Được mở lại', 'Repacked By': 'Được đóng gói lại bởi', 'Repair': 'Sửa chữa', 'Repaired': 'Được sửa chữa', 'Repeat your password': 'Nhập lại mật khẩu', 'Repeat': 'Lặp lại', 'Replace if Newer': 'Thay thế nếu mới hơn', 'Replace': 'Thay thế', 'Replacing or Provisioning Livelihoods': 'Thay thế hoặc Cấp phát sinh kế', 'Replies': 'Trả lời', 'Reply Message': 'Trả lời tin nhắn', 'Reply': 'Trả lời', 'Report Date': 'Ngày báo cáo', 'Report Details': 'Chi tiết báo cáo', 'Report Options': 'Lựa chọn yêu cầu báo cáo', 'Report To': 'Báo cáo cho', 'Report Type': 'Loại báo cáo', 'Report a Problem with the Software': 'báo cáo lỗi bằng phần mềm', 'Report added': 'Đã thêm báo cáo', 'Report by Age/Gender': 'Báo cáo theo tuổi/ giới tính', 'Report deleted': 'Đã xóa báo cáo', 'Report my location': 'Báo cáo vị trí ', 'Report of': 'Báo cáo theo', 'Report on Annual Budgets': 'Báo cáo về Ngân sách năm', 'Report on Themes': 'Báo cáo về Chủ đề', 'Report the contributing factors for the current EMS status.': 'Báo cáo các nhân tố đóng góp cho tình trạng EMS hiện tại.', 'Report': 'Báo cáo', 'Report': 'Báo cáo', 'Reported By (Not Staff)': 'Được báo cáo bởi (không phải nhân viên)', 'Reported By (Staff)': 'Được báo cáo bởi (nhân viên)', 'Reported To': 'Được báo cáo tới', 'Reported': 'Được báo cáo', 'Reportlab not installed': 'Chưa cài đặt kho báo cáo', 'Reports': 'Báo cáo', 'Repositories': 'Nơi lưu trữ', 'Repository Base URL': 'Nơi lưu trữ cơ bản URL', 'Repository Configuration': 'Cấu hình nơi lưu trữ', 'Repository Name': 'Tên nơi lưu trữ', 'Repository UUID': 'Lưu trữ UUID', 'Repository configuration deleted': 'Cấu hình nơi lưu trữ đã xóa', 'Repository configuration updated': 'Cấu hình nơi lưu trữ được cập nhật', 'Repository configured': 'Nơi lưu trữ đã được cấu hình', 'Repository': 'Nơi lưu trữ', 'Request Added': 'Đề nghị được thêm vào', 'Request Canceled': 'Đề nghị đã bị hủy', 'Request Details': 'Yêu cầu thông tin chi tiết', 'Request From': 'Đề nghị từ', 'Request Item Details': 'Chi tiết mặt hàng đề nghị', 'Request Item added': 'Đã thêm yêu cầu hàng hóa', 'Request Item deleted': 'Xóa yêu cầu hàng hóa', 'Request Item updated': 'Đã cập nhật hàng hóa yêu cầu', 'Request Item': 'Mặt hàng yêu cầu', 'Request Items': 'Mặt hàng yêu cầu', 'Request New People': 'Yêu cầu cán bộ mới', 'Request Status': 'Tình trạng lời đề nghị', 'Request Stock from Available Warehouse': 'Đề nghị Hàng từ Kho hàng đang có', 'Request Type': 'Loại hình đề nghị', 'Request Updated': 'Đề nghị được cập nhật', 'Request added': 'Yêu cầu được thêm', 'Request deleted': 'Yêu cầu được xóa', 'Request for Role Upgrade': 'yêu cầu nâng cấp vai trò', 'Request from Facility': 'Đề nghị từ bộ phận', 'Request updated': 'Yêu cầu được cập nhật', 'Request': 'Yêu cầu', 'Request, Response & Session': 'Yêu cầu, Phản hồi và Tương tác', 'Requested By': 'Đã được đề nghị bởi', 'Requested For Facility': 'Được yêu cầu cho bộ phận', 'Requested For': 'Đã được đề nghị cho', 'Requested From': 'Đã được đề nghị từ', 'Requested Items': 'Yêu cầu mặt hàng', 'Requested Skill Details': 'Chi tiết kỹ năng đã đề nghị', 'Requested Skill updated': 'Kỹ năng được đề nghị đã được cập nhật', 'Requested Skills': 'Những kỹ năng được đề nghị', 'Requested by': 'Yêu cầu bởi', 'Requested': 'Đã được đề nghị', 'Requester': 'Người đề nghị', 'Requestor': 'Người yêu cầu', 'Requests Management': 'Quản lý những đề nghị', 'Requests for Item': 'Yêu cầu hàng hóa', 'Requests': 'Yêu cầu', 'Required Skills': 'Những kỹ năng cần có ', 'Requires Login!': 'Đề nghị đăng nhập!', 'Requires Login': 'Đề nghị đăng nhập', 'Reset Password': 'Cài đặt lại mật khẩu', 'Reset all filters': 'Tái thiết lập tất cả lựa chọn lọc', 'Reset filter': 'Tái thiết lập lựa chọn lọc', 'Reset form': 'Đặt lại mẫu', 'Reset': 'Thiết lập lại', 'Resolution': 'Nghị quyết', 'Resource Configuration': 'Cấu hình nguồn lực', 'Resource Management System': 'Hệ thống quản lý nguồn lực', 'Resource Mobilization': 'Huy động nguồn lực', 'Resource Name': 'Tên nguồn lực', 'Resource configuration deleted': 'Cấu hình nguồn lực đã xóa', 'Resource configuration updated': 'Cầu hình nguồn lực được cập nhật', 'Resource configured': 'Nguồn lực đã được cấu hình', 'Resources': 'Những nguồn lực', 'Responder(s)': 'Người ứng phó', 'Response deleted': 'Xóa phản hồi', 'Response': 'Ứng phó', 'Responses': 'Các đợt ứng phó', 'Restarting Livelihoods': 'Tái khởi động nguồn sinh kế', 'Results': 'Kết quả', 'Retail Crime': 'Chiếm đoạt tài sản để bán', 'Retrieve Password': 'Khôi phục mật khẩu', 'Return to Request': 'Trở về Đề nghị', 'Return': 'Trở về', 'Returned From': 'Được trả lại từ', 'Returned': 'Đã được trả lại', 'Returning': 'Trả lại', 'Review Incoming Shipment to Receive': 'Rà soát Lô hàng đến để Nhận', 'Review next': 'Rà soát tiếp', 'Review': 'Rà soát', 'Revised Quantity': 'Số lượng đã được điều chỉnh', 'Revised Status': 'Tình trạng đã được điều chỉnh', 'Revised Value per Pack': 'Giá trị mỗi Gói đã được điều chỉnh', 'Riot': 'Bạo động', 'Risk Identification & Assessment': 'Đánh giá và Xác định rủi ro', 'Risk Transfer & Insurance': 'Bảo hiểm và hỗ trợ tài chính nhằm ứng phó với rủi ro', 'Risk Transfer': 'Hỗ trợ tài chính nhằm ứng phó với rủi ro', 'River Details': 'Chi tiết Sông', 'River': 'Sông', 'Road Accident': 'Tai nạn đường bộ', 'Road Closed': 'Đường bị chặn', 'Road Delay': 'Cản trở giao thông đường bộ', 'Road Hijacking': 'Tấn công trên đường', 'Road Safety': 'An toàn đường bộ', 'Road Usage Condition': 'Tình hình sử dụng đường sá', 'Role Details': 'Chi tiết về vai trò', 'Role Name': 'Tên chức năng', 'Role Required': 'Chức năng được yêu cầu', 'Role added': 'Vai trò được thêm vào', 'Role assigned to User': 'Chức năng được cấp cho người sử dụng này', 'Role deleted': 'Vai trò đã xóa', 'Role updated': 'Vai trò được cập nhật', 'Role': 'Vai trò', 'Roles Permitted': 'Các chức năng được cho phép', 'Roles currently assigned': 'Các chức năng được cấp hiện tại', 'Roles of User': 'Các chức năng của người sử dụng', 'Roles updated': 'Các chức năng được cập nhật', 'Roles': 'Vai trò', 'Room Details': 'Chi tiết về phòng', 'Room added': 'Phòng được thêm vào', 'Room deleted': 'Phòng đã xóa', 'Room updated': 'Phòng được cập nhật', 'Room': 'Phòng', 'Rooms': 'Những phòng', 'Rotation': 'Sự luân phiên', 'Rows in table': 'Các hàng trong bảng', 'Rows selected': 'Các hàng được chọn', 'Rows': 'Các dòng', 'Run Functional Tests': 'Kiểm thử chức năng', 'Run every': 'Khởi động mọi hàng', 'S3Pivottable unresolved dependencies': 'Các phụ thuộc không được xử lý S3pivottable', 'SMS Modems (Inbound & Outbound)': 'Modem SMS (gửi ra & gửi đến)', 'SMS Outbound': 'SMS gửi ra', 'SMS Settings': 'Cài đặt tin nhắn', 'SMS settings updated': 'Cập nhật cài đặt SMS', 'SMTP to SMS settings updated': 'Cập nhật cài đặt SMTP to SMS', 'SOPS and Guidelines Development': 'Xây dựng Hướng dẫn và Quy trình chuẩn', 'STRONG': 'MẠNH', 'SUBMIT DATA': 'GỬI DỮ LIỆU', 'Sahana Administrator': 'Quản trị viên Sahana', 'Sahana Community Chat': 'Nói chuyện trên cộng đồng Sahana', 'Sahana Eden Humanitarian Management Platform': 'Diễn đàn Quản lý nhân đạo Sahana Eden', 'Sahana Eden Website': 'Trang thông tin Sahana Eden', 'Sahana Eden portable application generator': 'Bộ sinh ứng dụng cầm tay Sahana Eden', 'Sahana Login Approval Pending': 'Chờ chấp nhận đăng nhập vào Sahana', 'Salary': 'Lương', 'Salary Coefficient': 'Hệ số', 'Sale': 'Bán hàng', 'Satellite': 'Vệ tinh', 'Save and add Items': 'Lưu và thêm Hàng hóa', 'Save and add People': 'Lưu và thêm Người', 'Save any Changes in the one you wish to keep': 'Lưu mọi thay đổi ở bất kỳ nơi nào bạn muốn', 'Save search': 'Lưu tìm kiếm', 'Save this search': 'Lưu tìm kiếm này', 'Save': 'Lưu', 'Save: Default Lat, Lon & Zoom for the Viewport': 'Lưu: Mặc định kinh độ, vĩ độ & phóng ảnh cho cổng nhìn', 'Saved Queries': 'Các thắc mắc được lưu', 'Saved Searches': 'Những tìm kiếm đã lưu', 'Saved search added': 'Tìm kiếm đã lưu đã được thêm vào', 'Saved search deleted': 'Tìm kiếm được lưu đã xóa', 'Saved search details': 'Chi tiết về tìm kiếm đã lưu', 'Saved search updated': 'Tìm kiếm đã lưu đã được cập nhật', 'Saved searches': 'Những tìm kiếm đã lưu', 'Scale of Results': 'Phạm vi của kết quả', 'Scale': 'Kích thước', 'Scanned Copy': 'Bản chụp điện tử', 'Scanned Forms Upload': 'Tải lên mẫu đã quyét', 'Scenarios': 'Các kịch bản', 'Schedule synchronization jobs': 'Các công việc được điều chỉnh theo lịch trình', 'Schedule': 'Lịch trình', 'Scheduled Jobs': 'Công việc đã được lập kế hoạch', 'Schema': 'Giản đồ', 'School Closure': 'Đóng cửa trường học', 'School Health': 'CSSK trong trường học', 'School Lockdown': 'Đóng cửa trường học', 'School tents received': 'Đã nhận được lều gửi cho trường học ', 'School/studying': 'Trường học', 'Seaport': 'Cảng biển', 'Seaports': 'Các cảng biển', 'Search & List Catalog': 'Tìm kiếm và liệt kê các danh mục', 'Search & List Category': 'Tìm và liệt kê danh mục', 'Search & List Items': 'Tìm kiếm và hiển thị danh sách hàng hóa', 'Search & List Locations': 'Tìm và liệt kê các địa điểm', 'Search & List Sub-Category': 'Tìm kiếm và lên danh sách Tiêu chí phụ', 'Search & Subscribe': 'Tìm kiếm và Đặt mua', 'Search Activities': 'Tìm kiếm hoạt động', 'Search Addresses': 'Tìm kiếm địa chỉ', 'Search Affiliations': 'Tìm kiếm chi nhánh', 'Search Aid Requests': 'Tìm kiếm Yêu cầu cứu trợ', 'Search Alternative Items': 'Tìm kiếm mục thay thế', 'Search Annual Budgets': 'Tìm kiếm các ngân sách năm', 'Search Assessments': 'Tìm kiếm các đánh giá', 'Search Asset Log': 'Tìm kiếm nhật ký tài sản', 'Search Assets': 'Tìm kiếm tài sản', 'Search Assigned Human Resources': 'Tìm kiếm người được phân công', 'Search Beneficiaries': 'Tìm kiếm những người hưởng lợi', 'Search Beneficiary Types': 'Tìm kiếm những nhóm người hưởng lợi', 'Search Branch Organizations': 'Tìm kiếm tổ chức chi nhánh', 'Search Brands': 'Tìm kiếm nhãn hàng', 'Search Budgets': 'Tìm kiếm các ngân sách', 'Search Catalog Items': 'Tìm kiếm mặt hàng trong danh mục', 'Search Catalogs': 'Tìm kiếm danh mục', 'Search Certificates': 'Tìm kiếm chứng chỉ', 'Search Certifications': 'Tìm kiếm bằng cấp', 'Search Checklists': 'Tìm kiếm Checklist', 'Search Clusters': 'Tìm kiếm nhóm', 'Search Commitment Items': 'Tìm kiếm mục cam kết', 'Search Commitments': 'Tìm kiếm cam kết', 'Search Committed People': 'Tìm kiếm người được cam kết', 'Search Community Contacts': 'Tìm kiếm thông tin liên lạc của cộng đồng', 'Search Community': 'Tìm kiếm cộng đồng', 'Search Competency Ratings': 'Tìm kiếm đánh giá năng lực', 'Search Contact Information': 'Tìm kiếm thông tin liên hệ', 'Search Contacts': 'Tìm kiếm liên lạc', 'Search Course Certificates': 'Tìm kiếm chứng chỉ đào tạo', 'Search Courses': 'Tìm kiếm khóa đào tạo', 'Search Credentials': 'Tìm kiếm giấy chứng nhận', 'Search Demographic Data': 'Tìm kiếm dữ liệu nhân khẩu học', 'Search Demographic Sources': 'Tìm kiếm nguồn dữ liệu dân số', 'Search Demographics': 'Tìm kiếm số liệu thống kê dân số', 'Search Departments': 'Tìm kiếm phòng/ban', 'Search Distributions': 'Tìm kiếm Quyên góp', 'Search Documents': 'Tìm kiếm tài liệu', 'Search Donors': 'Tìm kiếm nhà tài trợ', 'Search Education Details': 'Tìm kiếm thông tin đào tạo', 'Search Email InBox': 'Tìm kiếm thư trong hộp thư đến', 'Search Entries': 'Tìm kiếm hồ sơ', 'Search Facilities': 'Tìm kiếm trang thiết bị', 'Search Facility Types': 'Tìm kiếm loại hình bộ phận', 'Search Feature Layers': 'Tìm kiếm lớp tính năng', 'Search Flood Reports': 'Tìm các báo cáo về lũ lụt', 'Search Frameworks': 'Tìm kiếm khung chương trình', 'Search Groups': 'Tìm kiếm nhóm', 'Search Hospitals': 'Tìm kếm các bệnh viện', 'Search Hours': 'Tìm kiếm theo thời gian hoạt động', 'Search Identity': 'Tìm kiếm nhận dạng', 'Search Images': 'Tìm kiếm hình ảnh', 'Search Incident Reports': 'Tìm kiếm báo cáo sự việc', 'Search Item Catalog(s)': 'Tìm kiếm Catalog hàng hóa', 'Search Item Categories': 'Tìm kiếm nhóm mặt hàng', 'Search Item Packs': 'Tìm kiếm gói hàng', 'Search Items in Request': 'Tìm kiếm mặt hàng đang đề nghị', 'Search Items': 'Tìm kiếm mặt hàng', 'Search Job Roles': 'Tìm kiếm vai trò của công việc', 'Search Job Titles': 'Tìm kiếm chức danh công việc', 'Search Keys': 'Tìm kiếm mã', 'Search Kits': 'Tìm kiếm bộ dụng cụ', 'Search Layers': 'Tìm kiếm lớp', 'Search Location Hierarchies': 'Tìm kiếm thứ tự địa điểm', 'Search Location': 'Tìm kiếm địa điểm', 'Search Locations': 'Tìm kiếm địa điểm', 'Search Log Entry': 'Tìm kiếm ghi chép nhật ký', 'Search Logged Time': 'Tìm kiếm thời gian đăng nhập', 'Search Mailing Lists': 'Tìm kiếm danh sách gửi thư', 'Search Map Profiles': 'Tìm kiếm cấu hình bản đồ', 'Search Markers': 'Tìm kiếm đánh dấu', 'Search Members': 'Tìm kiếm thành viên', 'Search Membership Types': 'Tìm kiếm loại hình hội viên', 'Search Membership': 'Tìm kiếm hội viên', 'Search Memberships': 'Tim kiếm thành viên', 'Search Metadata': 'Tìm kiếm dữ liệu', 'Search Milestones': 'Tìm kiếm mốc quan trọng', 'Search Office Types': 'Tìm kiếm loại hình văn phòng', 'Search Offices': 'Tìm kiếm văn phòng', 'Search Open Tasks for %(project)s': 'Tìm kiếm Công việc Chưa được xác định cho %(project)s', 'Search Orders': 'Tìm kiếm đơn hàng', 'Search Organization Domains': 'Tìm kiếm lĩnh vực hoạt động của tổ chức', 'Search Organization Types': 'Tìm kiếm loại hình tổ chức', 'Search Organizations': 'Tìm kiếm tổ chức', 'Search Participants': 'Tìm kiếm người tham dự', 'Search Partner Organizations': 'Tìm kiếm tổ chức thành viên', 'Search Persons': 'Tìm kiếm người', 'Search Photos': 'Tìm kiếm hình ảnh', 'Search Professional Experience': 'Tìm kiếm kinh nghiệm nghề nghiệp', 'Search Programs': 'Tìm kiếm chương trình', 'Search Project Organizations': 'Tìm kiếm tổ chức dự án', 'Search Projections': 'Tìm kiếm dự đoán', 'Search Projects': 'Tìm kiếm dự án', 'Search Received/Incoming Shipments': 'Tìm kiếm lô hàng đến/nhận', 'Search Records': 'Tìm kiếm hồ sơ', 'Search Red Cross & Red Crescent National Societies': 'Tìm kiếm Hội Chữ thập đỏ và Trăng lưỡi liềm đỏ Quốc gia', 'Search Registations': 'Tìm kiếm các đăng ký', 'Search Registration Request': 'Tìm kiếm Yêu cầu Đăng ký', 'Search Report': 'Tìm kiếm báo cáo', 'Search Reports': 'Tìm kiếm Báo cáo', 'Search Request Items': 'Tìm kiếm Yêu cầu hàng hóa', 'Search Request': 'Tìm kiếm yêu cầu', 'Search Requested Skills': 'Tìm kiếm kỹ năng được đề nghị', 'Search Requests': 'Tìm kiếm đề nghị', 'Search Resources': 'Tìm kiếm các nguồn lực', 'Search Results': 'Tìm kiếm kết quả', 'Search Roles': 'Tìm kiếm vai trò', 'Search Rooms': 'Tìm kiếm phòng', 'Search Sectors': 'Tìm kiếm lĩnh vực', 'Search Sent Shipments': 'Tìm kiếm lô hàng đã gửi', 'Search Shelter Services': 'Tìm kiếm dịch vụ cư trú', 'Search Shelter Types': 'Tìm kiếm Loại Cư trú', 'Search Shipment Items': 'Tìm kiếm mặt hàng của lô hàng', 'Search Shipment/Way Bills': 'Tìm kiếm đơn hàng/hóa đơn vận chuyển', 'Search Shipped Items': 'Tìm kiếm mặt hàng được chuyển', 'Search Skill Equivalences': 'Tìm kiếm kỹ năng tương ứng', 'Search Skill Types': 'Tìm kiếm nhóm kỹ năng', 'Search Skills': 'Tìm kiếm kỹ năng', 'Search Staff & Volunteers': 'Tìm kiếm nhân viên & tình nguyện viên', 'Search Staff Assignments': 'Tìm kiếm công việc của nhân viên', 'Search Staff': 'Tìm kiếm nhân viên', 'Search Stock Adjustments': 'Tìm kiếm điều chỉnh về kho hàng', 'Search Stock Items': 'Tìm kiếm mặt hàng trong kho', 'Search Storage Location(s)': 'Tìm kiếm kho lưu trữ', 'Search Subscriptions': 'Tìm kiếm danh sách, số tiền quyên góp', 'Search Suppliers': 'Tìm kiếm nhà cung cấp', 'Search Support Requests': 'Tìm kiếm yêu cầu được hỗ trợ', 'Search Symbologies': 'Tìm kiếm biểu tượng', 'Search Tasks': 'Tìm kiếm nhiệm vụ', 'Search Teams': 'Tìm kiếm Đội/Nhóm', 'Search Theme Data': 'Tìm kiếm dữ liệu chủ đề', 'Search Themes': 'Tìm kiếm chủ đề', 'Search Tracks': 'Tìm kiếm dấu vết', 'Search Training Events': 'Tìm kiếm khóa tập huấn', 'Search Training Participants': 'Tìm kiếm học viên', 'Search Twilio SMS Inbox': 'Tìm kiếm hộp thư đến SMS Twilio', 'Search Twitter Tags': 'Tìm kiếm liên kết với Twitter', 'Search Units': 'Tìm kiếm đơn vị', 'Search Users': 'Tìm kiếm người sử dụng', 'Search Vehicle Assignments': 'Tìm kiếm việc điều động phương tiện', 'Search Volunteer Cluster Positions': 'Tìm kiếm vị trí của nhóm tình nguyện viên', 'Search Volunteer Cluster Types': 'Tìm kiếm loại hình nhóm tình nguyện viên', 'Search Volunteer Clusters': 'Tìm kiếm nhóm tình nguyện viên', 'Search Volunteer Registrations': 'Tìm kiếm Đăng ký tình nguyện viên', 'Search Volunteer Roles': 'Tìm kiếm vai trò của tình nguyện viên', 'Search Volunteers': 'Tìm kiếm tình nguyện viên', 'Search Vulnerability Aggregated Indicators': 'Tìm kiếm chỉ số theo tình trạng dễ bị tổn thương', 'Search Vulnerability Data': 'Tìm kiếm dữ liệu về tình trạng dễ bị tổn thương', 'Search Vulnerability Indicator Sources': 'Tìm kiếm nguồn chỉ số về tình trạng dễ bị tổn thương', 'Search Vulnerability Indicators': 'Tìm kiếm chỉ số về tình trạng dễ bị tổn thương', 'Search Warehouse Stock': 'Tìm kiếm Hàng trữ trong kho', 'Search Warehouses': 'Tìm kiếm Nhà kho', 'Search and Edit Group': 'Tìm và sửa thông tin nhóm', 'Search and Edit Individual': 'Tìm kiếm và chỉnh sửa cá nhân', 'Search for Activity Type': 'Tìm kiếm nhóm hoạt động', 'Search for Job': 'Tìm kiếm công việc', 'Search for Repository': 'Tìm kiếm Nơi lưu trữ', 'Search for Resource': 'Tìm kiếm nguồn lực', 'Search for a Hospital': 'Tìm kiếm bệnh viện', 'Search for a Location': 'Tìm một địa điểm', 'Search for a Person': 'Tìm kiếm theo tên', 'Search for a Project Community by name.': 'Tìm kiếm cộng đồng dự án theo tên.', 'Search for a Project by name, code, location, or description.': 'Tìm kiếm dự án theo tên, mã, địa điểm, hoặc mô tả.', 'Search for a Project by name, code, or description.': 'Tìm kiếm dự án theo tên, mã, hoặc mô tả.', 'Search for a Project': 'Tìm kiếm dự án', 'Search for a Request': 'Tìm kiếm một yêu cầu', 'Search for a Task by description.': 'Tìm kiếm nhiệm vụ theo mô tả.', 'Search for a shipment by looking for text in any field.': 'Tìm kiếm lô hàng bằng cách nhập từ khóa vào các ô.', 'Search for a shipment received between these dates': 'Tìm kiếm lô hàng đã nhận trong những ngày gần đây', 'Search for an Organization by name or acronym': 'Tìm kiếm tổ chức theo tên hoặc chữ viết tắt', 'Search for an item by Year of Manufacture.': 'Tìm kiếm mặt hàng theo năm sản xuất.', 'Search for an item by brand.': 'Tìm kiếm mặt hàng theo nhãn hàng.', 'Search for an item by catalog.': 'Tìm kiếm mặt hàng theo danh mục.', 'Search for an item by category.': 'Tìm kiếm mặt hàng theo nhóm.', 'Search for an item by its code, name, model and/or comment.': 'Tìm kiếm mặt hàng theo mã, tên, kiểu và/hoặc nhận xét.', 'Search for an item by text.': 'Tìm kiếm mặt hàng theo từ khóa.', 'Search for an order by looking for text in any field.': 'Tìm kiếm đơn đặt hàng bằng cách nhập từ khóa vào các ô.', 'Search for an order expected between these dates': 'Tìm kiếm một đơn hàng dự kiến trong những ngày gần đây', 'Search for office by organization.': 'Tìm kiếm văn phòng theo tổ chức.', 'Search for office by text.': 'Tìm kiếm văn phòng theo từ khóa.', 'Search for warehouse by organization.': 'Tìm kiếm nhà kho theo tổ chức.', 'Search for warehouse by text.': 'Tìm kiếm nhà kho theo từ khóa.', 'Search location in Geonames': 'Tìm kiếm địa điểm theo địa danh', 'Search messages': 'Tìm kiếm tin nhắn', 'Search saved searches': 'Tìm kiếm tìm kiếm được lưu', 'Search': 'Tìm kiếm', 'Secondary Server (Optional)': 'Máy chủ thứ cấp', 'Seconds must be a number between 0 and 60': 'Giây phải là số từ 0 đến 60', 'Seconds must be a number.': 'Giây phải bằng số', 'Seconds must be less than 60.': 'Giây phải nhỏ hơn 60', 'Section Details': 'Chi tiết khu vực', 'Section': 'Lĩnh vực', 'Sections that are part of this template': 'Các lĩnh vực là bộ phận của mẫu này', 'Sector Details': 'Chi tiết lĩnh vực', 'Sector added': 'Thêm Lĩnh vực', 'Sector deleted': 'Xóa Lĩnh vực', 'Sector updated': 'Cập nhật Lĩnh vực', 'Sector': 'Lĩnh vực', 'Sector(s)': 'Lĩnh vực', 'Sectors to which this Theme can apply': 'Lựa chọn Lĩnh vực phù hợp với Chủ đề này', 'Sectors': 'Lĩnh vực', 'Security Policy': 'Chính sách bảo mật', 'Security Required': 'An ninh được yêu cầu', 'Security Staff Types': 'Loại cán bộ bảo vệ', 'See All Entries': 'Xem tất cả hồ sơ', 'See a detailed description of the module on the Sahana Eden wiki': 'Xem chi tiết mô tả Modun trên Sahana Eden wiki', 'See the universally unique identifier (UUID) of this repository': 'Xem Định dạng duy nhất toàn cầu (UUID) của thư mục lưu này', 'Seen': 'Đã xem', 'Select %(location)s': 'Chọn %(location)s', 'Select %(up_to_3_locations)s to compare overall resilience': 'Chọn %(up_to_3_locations)s để so sánh tổng thể Sự phục hồi nhanh', 'Select All': 'Chọn tất cả', 'Select Existing Location': 'Lựa chọn vị trí đang có', 'Select Items from the Request': 'Chọn Hàng hóa từ Yêu cầu', 'Select Label Question': 'Chọn nhãn câu hỏi', 'Select Modules for translation': 'Lựa chọn các Module để dịch', 'Select Modules which are to be translated': 'Chọn Modun cần dịch', 'Select Numeric Questions (one or more):': 'Chọn câu hỏi về lượng (một hay nhiều hơn)', 'Select Stock from this Warehouse': 'Chọn hàng hóa lưu kho từ một Kho hàng', 'Select This Location': 'Lựa chọn vị trí này', 'Select a Country': 'Chọn nước', 'Select a commune to': 'Chọn xã đến', 'Select a label question and at least one numeric question to display the chart.': 'Chọn nhãn câu hỏi và ít nhất 1 câu hỏi về lượng để thể hiện biểu đồ', 'Select a location': 'Lựa chọn Quốc gia', 'Select a question from the list': 'Chọn một câu hỏi trong danh sách', 'Select all modules': 'Chọn mọi Modun', 'Select all that apply': 'Chọn tất cả các áp dụng trên', 'Select an Organization to see a list of offices': 'Chọn một Tổ chức để xem danh sách văn phòng', 'Select an existing bin': 'Lựa chọn ngăn có sẵn', 'Select an office': 'Chọn một văn phòng', 'Select any one option that apply': 'Lựa chọn bất cứ một lựa chọn được áp dụng', 'Select data type': 'Chọn loại dữ liệu', 'Select from Registry': 'Chọn từ danh sách đã đăng ký', 'Select language code': 'Chọn mã ngôn ngữ', 'Select one or more option(s) that apply': 'Lựa một hoặc nhiều lựa chọn được áp dụng', 'Select the default site.': 'Lựa chọn trang mặc định', 'Select the language file': 'Chọn tệp ngôn ngữ', 'Select the overlays for Assessments and Activities relating to each Need to identify the gap.': 'Lựa chọn lớp dữ liệu phủ cho Đánh giá và Hoạt động liên quan đến mỗi nhu cầu để xác định khoảng thiếu hụt.', 'Select the person assigned to this role for this project.': 'Chọn người được bổ nhiệm cho vai trò này trong dự án', 'Select the required modules': 'Chọn Modun cần thiết', 'Select': 'Chọn', 'Selected Questions for all Completed Assessment Forms': 'Câu hỏi được chọn cho tất cả các mẫu Đánh giá đã hoàn thành', 'Selects what type of gateway to use for outbound SMS': 'Chọn loại cổng để sử dụng tin nhắn gửi ra', 'Send Alerts using Email &/or SMS': 'Gửi Cảnh báo sử dụng thư điện từ &/hay SMS', 'Send Commitment': 'Gửi Cam kết', 'Send Dispatch Update': 'Gửi cập nhật ', 'Send Message': 'Gửi tin', 'Send New Shipment': 'Gửi Lô hàng Mới', 'Send Notification': 'Gửi thông báo', 'Send Shipment': 'Gửi Lô hàng', 'Send Task Notification': 'Gửi Thông báo Nhiệm vụ', 'Send a message to this person': 'Gửi tin nhắn cho người này', 'Send a message to this team': 'Gửi tin nhắn cho đội này', 'Send batch': 'Gửi hàng loạt', 'Send from %s': 'Gửi từ %s', 'Send message': 'Gửi tin nhắn', 'Send new message': 'Gửi tin nhắn mới', 'Send': 'Gửi', 'Sender': 'Người gửi', 'Senders': 'Người gửi', 'Senior (50+)': 'Người già (50+)', 'Senior Officer': 'Chuyên viên cao cấp', 'Sensitivity': 'Mức độ nhạy cảm', 'Sent By Person': 'Được gửi bởi Ai', 'Sent By': 'Được gửi bởi', 'Sent Shipment Details': 'Chi tiết lô hàng đã gửi', 'Sent Shipment canceled and items returned to Warehouse': 'Hủy lô hàng đã gửi và trả lại hàng hóa về kho Hàng', 'Sent Shipment canceled': 'Hủy lô hàng đã gửi', 'Sent Shipment has returned, indicate how many items will be returned to Warehouse.': 'Lô hàng được gửi đã được trả lại, nêu rõ bao nhiêu mặt hàng sẽ được trả lại kho hàng', 'Sent Shipment updated': 'Cập nhật Lô hàng đã gửi', 'Sent Shipments': 'Hàng chuyển', 'Sent date': 'Thời điểm gửi', 'Sent': 'đã được gửi', 'Separated': 'Ly thân', 'Serial Number': 'Số se ri', 'Series details missing': 'Chi tiết Se ri đang mất tích', 'Series': 'Se ri', 'Server': 'Máy chủ', 'Service Record': 'Hồ sơ hoạt động', 'Service or Facility': 'Dịch vụ hay Bộ phận', 'Service profile added': 'Đã thêm thông tin dịch vụ', 'Services Available': 'Các dịch vụ đang triển khai', 'Services': 'Dịch vụ', 'Set Base Facility/Site': 'Thiết lập Bộ phận/Địa bàn cơ bản', 'Set By': 'Thiết lập bởi', 'Set True to allow editing this level of the location hierarchy by users who are not MapAdmins.': 'Thiết lập Đúng để cho phép chỉnh sửa mức này của hệ thống hành chính địa điểm bởi người sử dụng không thuộc quản trị bản đồ', 'Setting Details': 'Chi tiết cài đặt', 'Setting added': 'Thêm cài đặt', 'Setting deleted': 'Xóa cài đặt', 'Settings were reset because authenticating with Twitter failed': 'Cài đặt được làm lại vì sự xác minh với Twitter bị lỗi', 'Settings which can be configured through the web interface are available here.': 'Cài đặt có thể được cấu hình thông quan tương tác với trang web có thể làm ở đây.', 'Settings': 'Các Cài đặt', 'Sex (Count)': 'Giới tính (Số lượng)', 'Sex': 'Giới tính', 'Sexual and Reproductive Health': 'Sức khỏe sinh sản và Sức khỏe tình dục', 'Share a common Marker (unless over-ridden at the Feature level)': 'Chia sẻ Đèn hiệu chung(nếu không vượt mức tính năng)', 'Shelter Registry': 'Đăng ký tạm trú', 'Shelter Repair Kit': 'Bộ dụng cụ sửa nhà', 'Shelter Service Details': 'Chi tiết dịch vụ cư trú', 'Shelter Services': 'Dịch vụ cư trú', 'Shelter added': 'Đã thêm Thông tin cư trú', 'Shelter deleted': 'Đã xóa nơi cư trú', 'Shelter': 'Nhà', 'Shelters': 'Địa điểm cư trú', 'Shipment Created': 'Tạo Lô hàng', 'Shipment Item Details': 'Chi tiết hàng hóa trong lô hàng', 'Shipment Item deleted': 'Xóa hàng hóa trong lô hàng', 'Shipment Item updated': 'Cập nhật hàng hóa trong lô hàng', 'Shipment Items Received': 'Hàng hóa trong lô hàng đã nhận được', 'Shipment Items sent from Warehouse': 'Hàng hóa trong lô hàng được gửi từ Kho hàng', 'Shipment Items': 'Hàng hóa trong lô hàng', 'Shipment Type': 'Loại Lô hàng', 'Shipment received': 'Lô hàng đã nhận được', 'Shipment to Receive': 'Lô hàng sẽ nhận được', 'Shipment to Send': 'Lô hàng sẽ gửi', 'Shipment': 'Lô hàng', 'Shipment/Way Bills': 'Đơn hàng/Hóa đơn vận chuyển', 'Shipment<>Item Relation added': 'Đã thêm đơn hàng <>hàng hóa liên quan', 'Shipment<>Item Relation deleted': 'Đã xóa dơn hàng <>Hàng hóa liên quan', 'Shipment<>Item Relation updated': 'Đã cập nhật Đơn hàng<>hàng hóa liên qua', 'Shipment<>Item Relations Details': 'Đơn hàng<>Chi tiết hàng hóa liên quan', 'Shipments': 'Các loại lô hàng', 'Shipping Organization': 'Tổ chức hàng hải', 'Shooting': 'Bắn', 'Short Description': 'Miêu tả ngắn gọn', 'Short Text': 'Đoạn văn bản ngắn', 'Short Title / ID': 'Tên viết tắt/ Mã dự án', 'Short-term': 'Ngắn hạn', 'Show Details': 'Hiển thị chi tiết', 'Show %(number)s entries': 'Hiển thị %(number)s hồ sơ', 'Show less': 'Thể hiện ít hơn', 'Show more': 'Thể hiện nhiều hơn', 'Show on Map': 'Thể hiện trên bản đồ', 'Show on map': 'Hiển thị trên bản đồ', 'Show totals': 'Hiển thị tổng', 'Show': 'Hiển thị', 'Showing 0 to 0 of 0 entries': 'Hiển thị 0 tới 0 của 0 hồ sơ', 'Showing _START_ to _END_ of _TOTAL_ entries': 'Hiển thị _START_ tới _END_ của _TOTAL_ hồ sơ', 'Showing latest entries first': 'Hiển thị hồ sơ mới nhất trước', 'Signature / Stamp': 'Chữ ký/dấu', 'Signature': 'Chữ ký', 'Simple Search': 'Tìm kiếm cơ bản', 'Single PDF File': 'File PDF', 'Single': 'Độc thân', 'Site Address': 'Địa chỉ trang web ', 'Site Administration': 'Quản trị Site', 'Site Manager': 'Quản trị website ', 'Site Name': 'Tên địa điểm', 'Site updated': 'Đã cập nhật site', 'Site': 'Địa điểm', 'Sitemap': 'Bản đồ địa điểm', 'Sites': 'Trang web', 'Situation Awareness & Geospatial Analysis': 'Nhận biết tình huống và phân tích tọa độ địa lý', 'Situation': 'Tình hình', 'Skeleton Example': 'Ví dụ khung', 'Sketch': 'Phác thảo', 'Skill Catalog': 'Danh mục kỹ năng', 'Skill Details': 'Chi tiết kỹ năng', 'Skill Equivalence Details': 'Chi tiết Kỹ năng tương ứng', 'Skill Equivalence added': 'Thêm Kỹ năng tương ứng', 'Skill Equivalence deleted': 'Xóa Kỹ năng tương ứng', 'Skill Equivalence updated': 'Cập nhật Kỹ năng tương ứng', 'Skill Equivalence': 'Kỹ năng tương ứng', 'Skill Equivalences': 'các Kỹ năng tương ứng', 'Skill Type Catalog': 'Danh mục Loại Kỹ năng', 'Skill Type added': 'Thêm Loại Kỹ năng', 'Skill Type deleted': 'Xóa Loại Kỹ năng', 'Skill Type updated': 'Cập nhật Loại Kỹ năng', 'Skill Type': 'Loại Kỹ năng', 'Skill added to Request': 'Thêm Kỹ năng vào Yêu cầu', 'Skill added': 'Thêm Kỹ năng', 'Skill deleted': 'Xóa kỹ năng', 'Skill removed from Request': 'Bỏ kỹ năng khỏi yêu cầu', 'Skill removed': 'Bỏ kỹ năng', 'Skill updated': 'Cập nhật kỹ năng', 'Skill': 'Kỹ năng', 'Skills': 'Kỹ năng', 'Smoke': 'Khói', 'Snapshot': 'Chụp ảnh', 'Snow Fall': 'Tuyết rơi', 'Snow Squall': 'Tiếng tuyết rơi', 'Social Impact & Resilience': 'Khả năng phục hồi và Tác động xã hội', 'Social Inclusion & Diversity': 'Đa dạng hóa/ Tăng cường hòa nhập xã hội', 'Social Insurance Number': 'Số sổ BHXH', 'Social Insurance': 'Bảo hiểm xã hội', 'Social Mobilization': 'Huy động xã hội', 'Solid Waste Management': 'Quản lý chất thải rắn', 'Solution added': 'Đã thêm giải pháp', 'Solution deleted': 'Đã xóa giải pháp', 'Solution updated': 'Đã cập nhật giải pháp', 'Sorry - the server has a problem, please try again later.': 'Xin lỗi - Máy chủ có sự cố, vui lòng thử lại sau.', 'Sorry location %(location)s appears to be outside the area of parent %(parent)s.': 'Xin lỗi địa điểm %(location)s có vẻ như ngoài vùng của lớp trên %(parent)s', 'Sorry location %(location)s appears to be outside the area supported by this deployment.': 'Xin lỗi địa điểm %(location)s có vẻ như ngoài vùng hỗ trợ bởi đợt triển khai này', 'Sorry location appears to be outside the area of parent %(parent)s.': 'Xin lỗi địa điểm có vẻ như ngoài vùng của lớp trên %(parent)s', 'Sorry location appears to be outside the area supported by this deployment.': 'Xin lỗi địa điểm có vẻ như ngoài vùng hỗ trợ bởi đợt triển khai này', 'Sorry, I could not understand your request': 'Xin lỗi, tôi không thể hiểu yêu cầu của bạn', 'Sorry, only users with the MapAdmin role are allowed to edit these locations': 'Xin lỗi, chỉ người sử dụng có chức năng quản trị bản đồ được phép chỉnh sửa các địa điểm này', 'Sorry, something went wrong.': 'Xin lỗi, có sự cố.', 'Sorry, that page is forbidden for some reason.': 'Xin lỗi, vì một số lý do trang đó bị cấm.', 'Sorry, that service is temporary unavailable.': 'Xin lỗi, dịch vụ đó tạm thời không có', 'Sorry, there are no addresses to display': 'Xin lỗi, Không có địa chỉ để hiện thị', 'Source Type': 'Loại nguồn', 'Source not specified!': 'Nguồn không xác định', 'Source': 'Nguồn', 'Space Debris': 'Rác vũ trụ', 'Spanish': 'Người Tây Ban Nha', 'Special Ice': 'Băng tuyết đặc biệt', 'Special Marine': 'Thủy quân đặc biệt', 'Special needs': 'Nhu cầu đặc biệt', 'Specialized Hospital': 'Bệnh viện chuyên khoa', 'Specific Area (e.g. Building/Room) within the Location that this Person/Group is seen.': 'Khu vực cụ thể (ví dụ Tòa nhà/Phòng) trong khu vực mà người/Nhóm đã xem', 'Specific locations need to have a parent of level': 'Các địa điểm cụ thể cần có lớp trên', 'Specify a descriptive title for the image.': 'Chỉ định một tiêu đề mô tả cho ảnh', 'Spherical Mercator (900913) is needed to use OpenStreetMap/Google/Bing base layers.': 'Spherical Mercator (900913) cần thiết để sử dụng OpenStreetMap/Google/Bing như là lớp bản đồ cơ sở.', 'Spreadsheet': 'Bảng tính', 'Squall': 'tiếng kêu', 'Staff & Volunteers (Combined)': 'Cán bộ & TNV', 'Staff & Volunteers': 'Cán bộ & Tình nguyện viên', 'Staff Assigned': 'Cán bộ được bộ nhiệm', 'Staff Assignment Details': 'Chi tiết bổ nhiệm cán bộ', 'Staff Assignment removed': 'Bỏ bổ nhiệm cán bộ', 'Staff Assignment updated': 'Cập nhật bổ nhiệm cán bộ', 'Staff Assignments': 'Các bổ nhiệm cán bộ', 'Staff ID': 'Định danh cán bộ', 'Staff Level': 'Ngạch công chức', 'Staff Management': 'Quản lý cán bộ', 'Staff Member Details updated': 'Cập nhật chi tiết cán bộ', 'Staff Member Details': 'Chi tiết cán bộ', 'Staff Member deleted': 'Xóa Cán bộ', 'Staff Record': 'Hồ sơ cán bộ', 'Staff Report': 'Cán bộ', 'Staff Type Details': 'Chi tiết bộ phận nhân viên', 'Staff deleted': 'Xóa tên nhân viên', 'Staff member added': 'Thêm cán bộ', 'Staff with Contracts Expiring in the next Month': 'Cán bộ hết hạn hợp đồng tháng tới', 'Staff': 'Cán bộ', 'Staff/Volunteer Record': 'Hồ sơ Cán bộ/Tình nguyện viên', 'Staff/Volunteer': 'Cán bộ/Tình nguyện viên', 'Start Date': 'Ngày bắt đầu', 'Start date': 'Ngày bắt đầu', 'Start of Period': 'Khởi đầu chu kỳ', 'Start': 'Bắt đầu', 'State / Province (Count)': 'Tỉnh / Thành phố (Số lượng)', 'State / Province': 'Tỉnh', 'State Management Education': 'Quản lý nhà nước', 'Station Parameters': 'Thông số trạm', 'Statistics Parameter': 'Chỉ số thống kê', 'Statistics': 'Thống kê', 'Stats Group': 'Nhóm thống kê', 'Status Details': 'Chi tiết Tình trạng', 'Status Report': 'Báo cáo tình trạng ', 'Status Updated': 'Cập nhật Tình trạng', 'Status added': 'Thêm Tình trạng', 'Status deleted': 'Xóa Tình trạng', 'Status of adjustment': 'Điều chỉnh Tình trạng', 'Status of operations of the emergency department of this hospital.': 'Tình trạng hoạt động của phòng cấp cứu tại bệnh viện này', 'Status of security procedures/access restrictions in the hospital.': 'Trạng thái của các giới hạn thủ tục/truy nhập an ninh trong bệnh viện', 'Status of the operating rooms of this hospital.': 'Trạng thái các phòng bệnh trong bệnh viện này', 'Status updated': 'Cập nhật Tình trạng', 'Status': 'Tình trạng', 'Statuses': 'Các tình trạng', 'Stock Adjustment Details': 'Chi tiết điều chỉnh hàng lưu kho', 'Stock Adjustments': 'Điều chỉnh Hàng lưu kho', 'Stock Expires %(date)s': 'Hàng lưu kho hết hạn %(date)s', 'Stock added to Warehouse': 'Hàng hóa lưu kho được thêm vào Kho hàng', 'Stock in Warehouse': 'Hàng lưu kho', 'Stock removed from Warehouse': 'Hàng lưu kho được lấy ra khỏi Kho hàng', 'Stock': 'Hàng lưu kho', 'Stockpiling, Prepositioning of Supplies': 'Dự trữ hàng hóa', 'Stocks and relief items.': 'Kho hàng và hàng cứu trợ.', 'Stolen': 'Bị mất cắp', 'Store spreadsheets in the Eden database': 'Lưu trữ bảng tính trên cơ sở dữ liệu của Eden', 'Storm Force Wind': 'Sức mạnh Gió bão', 'Storm Surge': 'Bão biển gây nước dâng', 'Stowaway': 'Đi tàu lậu', 'Strategy': 'Chiến lược', 'Street Address': 'Địa chỉ', 'Street View': 'Xem kiểu đường phố', 'Strengthening Livelihoods': 'Cải thiện nguồn sinh kế', 'Strong Wind': 'Gió bão', 'Strong': 'Mạnh', 'Structural Safety': 'An toàn kết cấu trong xây dựng', 'Style Field': 'Kiểu trường', 'Style Values': 'Kiểu giá trị', 'Style': 'Kiểu', 'Subject': 'Tiêu đề', 'Submission successful - please wait': 'Gửi thành công - vui lòng đợi', 'Submit Data': 'Gửi dữ liệu', 'Submit New (full form)': 'Gửi mới (mẫu đầy đủ)', 'Submit New (triage)': 'Gửi mới (cho nhóm 3 người)', 'Submit New': 'Gửi mới', 'Submit all': 'Gửi tất cả', 'Submit data to the region': 'Gửi dữ liệu cho vùng', 'Submit more': 'Gửi thêm', 'Submit online': 'Gửi qua mạng', 'Submit': 'Gửi', 'Submitted by': 'Được gửi bởi', 'Subscription deleted': 'Đã xóa đăng ký', 'Subscriptions': 'Quyên góp', 'Subsistence Cost': 'Mức sống tối thiểu', 'Successfully registered at the repository.': 'Đã đăng ký thành công vào hệ thống', 'Suggest not changing this field unless you know what you are doing.': 'Khuyến nghị bạn không thay đổi trường này khi chưa chắc chắn', 'Sum': 'Tổng', 'Summary Details': 'Thông tin tổng hợp', 'Summary by Question Type - (The fewer text questions the better the analysis can be)': 'Tổng hợp theo loại câu hỏi - (Phân tích dễ dàng hơn nếu có ít câu hỏi bằng chữ)', 'Summary of Completed Assessment Forms': 'Tổng hợp biểu mẫu đánh giá đã hoàn thành', 'Summary of Incoming Supplies': 'Tổng hợp mặt hàng đang đến', 'Summary of Releases': 'Tổng hợp bản tin báo chí', 'Summary': 'Tổng hợp', 'Supplier Details': 'Thông tin nhà cung cấp', 'Supplier added': 'Nhà cung cấp đã được thêm', 'Supplier deleted': 'Nhà cung cấp đã được xóa', 'Supplier updated': 'Nhà cung cấp đã được cập nhật', 'Supplier': 'Nhà cung cấp', 'Supplier/Donor': 'Nhà cung cấp/Nhà tài trợ', 'Suppliers': 'Nhà cung cấp', 'Supply Chain Management': 'Quản lý dây chuyền cung cấp', 'Support Request': 'Hỗ trợ yêu cầu', 'Support Requests': 'Yêu cầu hỗ trợ', 'Support': 'Trợ giúp', 'Surplus': 'Thặng dư', 'Survey Answer Details': 'Chi tiết trả lời câu hỏi khảo sát', 'Survey Answer added': 'Đã thêm trả lời khảo sát', 'Survey Name': 'Tên khảo sát', 'Survey Question Display Name': 'Tên trên bảng câu hỏi khảo sát', 'Survey Question updated': 'cập nhật câu hỏi khảo sát', 'Survey Section added': 'Đã thêm khu vực khảo sát', 'Survey Section updated': 'Cập nhật khu vực khảo sát', 'Survey Series added': 'Đã thêm chuỗi khảo sát', 'Survey Series deleted': 'Đã xóa chuỗi khảo sát', 'Survey Series updated': 'Đã cập nhật serie khảo sát', 'Survey Series': 'Chuỗi khảo sát', 'Survey Template added': 'Thêm mẫu Khảo sát', 'Survey Templates': 'Mẫu khảo sát', 'Swiss Francs': 'Frăng Thụy Sỹ', 'Switch to 3D': 'Chuyển sang 3D', 'Symbologies': 'Các biểu tượng', 'Symbology Details': 'Chi tiết biểu tượng', 'Symbology added': 'Thêm biểu tượng', 'Symbology deleted': 'Xóa biểu tượng', 'Symbology removed from Layer': 'Bỏ biểu tượng khỏi lớp', 'Symbology updated': 'Cập nhật biểu tượng', 'Symbology': 'Biểu tượng', 'Sync Conflicts': 'Xung đột khi đồng bộ hóa', 'Sync Now': 'Đồng bộ hóa ngay bây giờ', 'Sync Partners': 'Đối tác đồng bộ', 'Sync Schedule': 'Lịch đồng bộ', 'Sync process already started on ': 'Quá trinh đồng bộ đã bắt đầu lúc ', 'Synchronization Job': 'Chức năng Đồng bộ hóa', 'Synchronization Log': 'Danh mục Đồng bộ hóa', 'Synchronization Schedule': 'Kế hoạch Đồng bộ hóa', 'Synchronization Settings': 'Các cài đặt Đồng bộ hóa', 'Synchronization allows you to share data that you have with others and update your own database with latest data from other peers. This page provides you with information about how to use the synchronization features of Sahana Eden': 'Đồng bộ hóa cho phép bạn chia sẻ dữ liệu và cập nhật cơ sở dữ liệu với các máy khác.Trang này hường dẫn bạn cách sử dụng các tính năng đồng bộ của Sahana Eden', 'Synchronization currently active - refresh page to update status.': 'Đồng bộ hóa đang chạy - làm mới trang để cập nhật tình trạng', 'Synchronization mode': 'Chế độ đồng bộ hóa', 'Synchronization not configured.': 'Chưa thiết đặt đồng bộ hóa', 'Synchronization settings updated': 'Các cài đặt đồng bộ hóa được cập nhật', 'Synchronization': 'Đồng bộ hóa', 'Syncronization History': 'Lịch sử đồng bộ hóa', 'System keeps track of all Volunteers working in the disaster region. It captures not only the places where they are active, but also captures information on the range of services they are providing in each area.': 'Hệ thống theo sát quá trình làm việc của các tình nguyện viên trong khu vực thiên tai.Hệ thống nắm bắt không chỉ vị trí hoạt động mà còn cả thông tin về các dịch vụ đang cung cấp trong mỗi khu vực', 'THOUSAND_SEPARATOR': 'Định dạng hàng nghìn', 'TMS Layer': 'Lớp TMS', 'TO': 'TỚI', 'Table Permissions': 'Quyền truy cập bảng', 'Table name of the resource to synchronize': 'Bảng tên nguồn lực để đồng bộ hóa', 'Table': 'Bảng thông tin', 'Tablename': 'Tên bảng', 'Tags': 'Các bảng tên', 'Task Details': 'Các chi tiết nhiệm vụ', 'Task List': 'Danh sách Nhiệm vụ', 'Task added': 'Nhiệm vụ được thêm vào', 'Task deleted': 'Nhiệm vụ đã xóa', 'Task updated': 'Nhiệm vụ được cập nhật', 'Task': 'Nhiệm vụ', 'Tasks': 'Nhiệm vụ', 'Team Description': 'Mô tả về Đội/Nhóm', 'Team Details': 'Thông tin về Đội/Nhóm', 'Team ID': 'Mã Đội/Nhóm', 'Team Leader': 'Đội trưởng', 'Team Members': 'Thành viên Đội/Nhóm', 'Team Name': 'Tên Đội/Nhóm', 'Team Type': 'Loại hình Đội/Nhóm', 'Team added': 'Đội/ Nhóm đã thêm', 'Team deleted': 'Đội/ Nhóm đã xóa', 'Team updated': 'Đội/ Nhóm đã cập nhật', 'Team': 'Đội', 'Teams': 'Đội/Nhóm', 'Technical Disaster': 'Thảm họa liên quan đến công nghệ', 'Telephony': 'Đường điện thoại', 'Tells GeoServer to do MetaTiling which reduces the number of duplicate labels.': 'Yêu cầu GeoServer làm MetaTiling để giảm số nhãn bị lặp', 'Template Name': 'Tên Biểu mẫu', 'Template Section Details': 'Chi tiết Mục Biểu mẫu', 'Template Section added': 'Mục Biểu mẫu được thêm', 'Template Section deleted': 'Mục Biểu mẫu đã xóa', 'Template Section updated': 'Mục Biểu mẫu được cập nhật', 'Template Sections': 'Các Mục Biểu mẫu', 'Template Summary': 'Tóm tắt Biểu mẫu', 'Template': 'Biểu mẫu', 'Templates': 'Biểu mẫu', 'Term for the fifth-level within-country administrative division (e.g. a voting or postcode subdivision). This level is not often used.': 'Khái niệm về sự phân chia hành chính trong nước cấp thứ năm (ví dụ như sự phân chia bầu cử hay mã bưu điện). Mức này thường ít được dùng', 'Term for the fourth-level within-country administrative division (e.g. Village, Neighborhood or Precinct).': 'Khái niệm về sự phân chia hành chính cấp thứ tư bên trong quốc gia (ví dụ như làng, hàng xóm hay bản)', 'Term for the primary within-country administrative division (e.g. State or Province).': 'Khái niệm về sự phân chia hành chính trong nước cấp một (ví dụ như Bang hay Tỉnh)', 'Term for the secondary within-country administrative division (e.g. District or County).': 'Khái niệm về sự phân chia hành chính trong nước cấp thứ hai (ví dụ như quận huyện hay thị xã)', 'Term for the third-level within-country administrative division (e.g. City or Town).': 'Khái niệm về sự phân chia hành chính trong nước cấp thứ ba (ví dụ như thành phố hay thị trấn)', 'Term': 'Loại hợp đồng', 'Terms of Service:': 'Điều khoản Dịch vụ:', 'Terrorism': 'Khủng bố', 'Tertiary Server (Optional)': 'Máy chủ Cấp ba (Tùy chọn)', 'Text Color for Text blocks': 'Màu vản bản cho khối văn bản', 'Text': 'Từ khóa', 'Thank you for your approval': 'Cảm ơn bạn vì sự phê duyệt', 'Thank you, the submission%(br)shas been declined': 'Cảm ơn bạn, lời đề nghị %(br)s đã bị từ chối', 'Thanks for your assistance': 'Cám ơn sự hỗ trợ của bạn', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1 == db.table2.field2" results in a SQL JOIN.': '"Câu hỏi" là một điều kiện có dạng "db.bảng1.trường1==\'giá trị\'". Bất kỳ cái gì có dạng "db.bảng1.trường1 == db.bảng2.trường2" đều có kết quả là một SQL THAM GIA.', 'The Area which this Site is located within.': 'Khu vực có chứa Địa điểm này', 'The Assessment Module stores assessment templates and allows responses to assessments for specific events to be collected and analyzed': 'Mô đun Khảo sát Đánh giá chứa các biểu mẫu khảo sát đánh giá và cho phép thu thập và phân tích các phản hồi đối với khảo sát đánh giá cho các sự kiện cụ thể', 'The Author of this Document (optional)': 'Tác giá của Tài liệu này (tùy chọn)', 'The Bin in which the Item is being stored (optional).': 'Ngăn/ Khu vực chứa hàng (tùy chọn)', 'The Current Location of the Person/Group, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'Địa điểm hiện tại của Người/ Nhóm, có thể là chung chung (dùng để Báo cáo) hoặc chính xác (dùng để thể hiện trên Bản đồ). Nhập các ký tự để tìm kiếm từ các địa điểm hiện có.', 'The Email Address to which approval requests are sent (normally this would be a Group mail rather than an individual). If the field is blank then requests are approved automatically if the domain matches.': 'Địa chỉ thư điện tử để gửi các yêu cầu phê duyệt (thông thường địa chỉ này là một nhóm các địa chỉ chứ không phải là các địa chỉ đơn lẻ). Nếu trường này bị bỏ trống thì các yêu cầu sẽ được tự động chấp thuận nếu miền phù hợp.', 'The Incident Reporting System allows the General Public to Report Incidents & have these Tracked.': 'Hệ thống Báo cáo Sự kiện cho phép ', 'The Location the Person has come from, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'Địa điểm xuất phát của Người, có thể chung chung (dùng cho Báo cáo) hay chính xác (dùng để thể hiện trên Bản đồ). Nhập một số ký tự để tìm kiếm từ các địa điểm đã có.', 'The Location the Person is going to, which can be general (for Reporting) or precise (for displaying on a Map). Enter a few characters to search from available locations.': 'Địa điểm mà Người chuẩn bị đến, có thể là chung chung (dùng cho Báo cáo) hay chính xác (dùng để thể hiện trên Bản đồ). Nhập một số ký tự để tìm kiếm từ các địa điểm đã có.', 'The Media Library provides a catalog of digital media.': 'Thư viện Đa phương tiện cung cấp một danh mục các phương tiện số.', 'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': 'Chức năng nhắn tin là trung tâm thông tin chính của hệ thống Sahana. Chức năng này được sử dụng để gửi cảnh báo và/ hoặc tin nhắn dạng SMS và email tới các nhóm và cá nhân trước, trong và sau thảm họa.', 'The Organization Registry keeps track of all the relief organizations working in the area.': 'Cơ quan đăng ký Tổ chức theo dõi tất cả các tổ chức cứu trợ đang hoạt động trong khu vực.', 'The Organization this record is associated with.': 'Tổ chức được ghi liên kết với.', 'The Role this person plays within this hospital.': 'Vai trò của người này trong bệnh viện', 'The Tracking Number %s is already used by %s.': 'Số Theo dõi %s đã được sử dụng bởi %s.', 'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': 'URL cho trang GetCapabilities của một Dịch vụ Bản đồ Mạng (WMS) có các lớp mà bạn muốn có thông qua bảng Trình duyệt trên Bản đồ.', 'The URL of your web gateway without the post parameters': 'URL của cổng mạng của bạn mà không có các thông số điện tín', 'The URL to access the service.': 'URL để truy cập dịch vụ.', 'The answers are missing': 'Chưa có các câu trả lời', 'The area is': 'Khu vực là', 'The attribute which is used for the title of popups.': 'Thuộc tính được sử dụng cho tiêu đề của các cửa sổ tự động hiển thị.', 'The attribute within the KML which is used for the title of popups.': 'Thuộc tính trong KML được sử dụng cho tiêu đề của các cửa sổ tự động hiển thị.', 'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)': '(Các) thuộc tính trong KML được sử dụng cho phần nội dung của các cửa sổ tự động hiển thị. (Sử dụng dấu cách giữa các thuộc tính)', 'The body height (crown to heel) in cm.': 'Chiều cao của phần thân (từ đầu đến chân) tính theo đơn vị cm.', 'The contact person for this organization.': 'Người chịu trách nhiệm liên lạc cho tổ chức này', 'The facility where this position is based.': 'Bộ phận mà vị trí này trực thuộc', 'The first or only name of the person (mandatory).': 'Tên (bắt buộc phải điền).', 'The following %s have been added': '%s dưới đây đã được thêm vào', 'The following %s have been updated': '%s dưới đây đã được cập nhật', 'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.': 'Dạng URL là http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.', 'The hospital this record is associated with.': 'Bệnh viện lưu hồ sơ này', 'The language you wish the site to be displayed in.': 'Ngôn ngữ bạn muốn đê hiển thị trên trang web', 'The length is': 'Chiều dài là', 'The list of Brands are maintained by the Administrators.': 'Danh sách các Chi nhánh do Những người quản lý giữ.', 'The list of Catalogs are maintained by the Administrators.': 'Danh sách các Danh mục do Những người quản lý giữ.', 'The list of Item categories are maintained by the Administrators.': 'Danh sách category hàng hóa được quản trị viên quản lý', 'The map will be displayed initially with this latitude at the center.': 'Bản đồ sẽ được thể hiện đầu tiên với vĩ độ này tại địa điểm trung tâm.', 'The map will be displayed initially with this longitude at the center.': 'Bản đồ sẽ được thể hiện đầu tiên với kinh độ này tại địa điểm trung tâm.', 'The minimum number of features to form a cluster.': 'Các đặc điểm tối thiểu để hình thành một nhóm.', 'The name to be used when calling for or directly addressing the person (optional).': 'Tên được sử dụng khi gọi người này (tùy chọn).', 'The number geographical units that may be part of the aggregation': 'Số đơn vị địa lý có thể là một phần của tổ hợp', 'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'Số Đơn vị Đo của Các mặt hàng thay thế bằng với Một Đơn vị Đo của Mặt hàng đó', 'The number of aggregated records': 'Số bản lưu đã được tổng hợp', 'The number of pixels apart that features need to be before they are clustered.': 'Số điểm ảnh ngoài mà các đặc điểm cần trước khi được nhóm', 'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.': 'Số lớp để tải về quanh bản đồ được thể hiện. Không có nghĩa là trang đầu tiên tải nhanh hơn, các con số cao hơn nghĩa là việc quét sau nhanh hơn.', 'The person reporting about the missing person.': 'Người báo cáo về người mất tích', 'The post variable containing the phone number': 'Vị trí có thể thay đổi đang chứa số điện thoại', 'The post variable on the URL used for sending messages': 'Vị trí có thể thay đổi trên URL được dùng để gửi tin nhắn', 'The post variables other than the ones containing the message and the phone number': 'Vị trí có thể thay đổi khác với các vị trí đang chứa các tin nhắn và số điện thoại', 'The serial port at which the modem is connected - /dev/ttyUSB0, etc on linux and com1, com2, etc on Windows': 'Chuỗi cổng kết nối mô đem - /dev/ttyUSB0, v.v. trên linux và com1, com2, v.v. trên Windows', 'The server did not receive a timely response from another server that it was accessing to fill the request by the browser.': 'Máy chủ không nhận được một phản hồi kịp thời từ một máy chủ khác khi đang truy cập để hoàn tất yêu cầu bằng bộ trình duyệt.', 'The server received an incorrect response from another server that it was accessing to fill the request by the browser.': 'Máy chủ đã nhận được một phản hồi sai từ một máy chủ khác khi đang truy cập để hoàn tất yêu cầu bằng bộ trình duyệt.', 'The simple policy allows anonymous users to Read & registered users to Edit. The full security policy allows the administrator to set permissions on individual tables or records - see models/zzz.py.': 'Các chính sách đơn giản cho phép người dùng ẩn danh đọc và đăng ký để chỉnh sửa. Các chính sách bảo mật đầy đủ cho phép quản trị viên thiết lập phân quyền trên các bảng cá nhân hay - xem mô hình / zzz.py.', 'The staff responsibile for Facilities can make Requests for assistance. Commitments can be made against these Requests however the requests remain open until the requestor confirms that the request is complete.': 'Cán bộ chịu trách nhiệm về Các cơ sở có thể đưa ra Yêu cầu trợ giúp. Các cam kết có thể được đưa ra đối với những Yêu cầu này tuy nhiên các yêu cầu này phải để mở cho đến khi người yêu cầu xác nhận yêu cầu đã hoàn tất.', 'The synchronization module allows the synchronization of data resources between Sahana Eden instances.': 'Mô đun đồng bộ hóa cho phép đồng bộ hóa nguồn dữ liệu giữa các phiên bản Sahana Eden.', 'The system supports 2 projections by default:': 'Hệ thống hỗ trợ 2 dự thảo bởi chế độ mặc định:', 'The token associated with this application on': 'Mã thông báo liên quan đến ứng dụng này trên', 'The unique identifier which identifies this instance to other instances.': 'Yếu tố khác biệt phân biệt lần này với các lần khác', 'The uploaded Form is unreadable, please do manual data entry.': 'Mẫu được tải không thể đọc được, vui lòng nhập dữ liệu thủ công', 'The weight in kg.': 'Trọng lượng tính theo đơn vị kg.', 'Theme Data deleted': 'Dữ liệu Chủ đề đã xóa', 'Theme Data updated': 'Dữ liệu Chủ đề đã cập nhật', 'Theme Data': 'Dữ liệu Chủ đề', 'Theme Details': 'Chi tiết Chủ đề', 'Theme Layer': 'Lớp Chủ đề', 'Theme Sectors': 'Lĩnh vực của Chủ đề', 'Theme added': 'Chủ đề được thêm vào', 'Theme deleted': 'Chủ đề đã xóa', 'Theme removed': 'Chủ đề đã loại bỏ', 'Theme updated': 'Chủ đề đã cập nhật', 'Theme': 'Chủ đề', 'Themes': 'Chủ đề', 'There are multiple records at this location': 'Có nhiều bản lưu tại địa điểm này', 'There is a problem with your file.': 'Có vấn đề với tệp tin của bạn.', 'There is insufficient data to draw a chart from the questions selected': 'Không có đủ dữ liệu để vẽ biểu đồ từ câu hỏi đã chọn', 'There is no address for this person yet. Add new address.': 'Chưa có địa chỉ về người này. Hãy thêm địa chỉ.', 'There was a problem, sorry, please try again later.': 'Đã có vấn đề, xin lỗi, vui lòng thử lại sau.', 'These are settings for Inbound Mail.': 'Đây là những cài đặt cho Hộp thư đến.', 'These are the Incident Categories visible to normal End-Users': 'Đây là những Nhóm Sự kiện hiển thị cho Người dùng Cuối cùng thông thường.', 'These are the filters being used by the search.': 'Đây là những bộ lọc sử dụng cho tìm kiếm.', 'These need to be added in Decimal Degrees.': 'Cần thêm vào trong Số các chữ số thập phân.', 'They': 'Người ta', 'This Group has no Members yet': 'Hiện không có hội viên nào được đăng ký', 'This Team has no Members yet': 'Hiện không có hội viên nào được đăng ký', 'This adjustment has already been closed.': 'Điều chỉnh này đã đóng.', 'This email-address is already registered.': 'Địa chỉ email này đã được đăng ký.', 'This form allows the administrator to remove a duplicate location.': 'Mẫu này cho phép quản trị viên xóa bỏ các địa điểm trùng', 'This is appropriate if this level is under construction. To prevent accidental modification after this level is complete, this can be set to False.': 'Lựa chọn này phù hợp nếu cấp độ này đang được xây dựng. Để không vô tình chỉnh sửa sau khi hoàn tất cấp độ này, lựa chọn này có thể được đặt ở giá trị Sai.', 'This is normally edited using the Widget in the Style Tab in the Layer Properties on the Map.': 'Điều này thông thường được chỉnh sửa sử dụng Công cụ trong Mục Kiểu dáng trong Các đặc trưng của Lớp trên Bản đồ.', 'This is the full name of the language and will be displayed to the user when selecting the template language.': 'Đây là tên đầy đủ của ngôn ngữ và sẽ được thể hiện với người dùng khi lựa chọn ngôn ngữ.', 'This is the name of the parsing function used as a workflow.': 'Đây là tên của chức năng phân tích cú pháp được sử dụng như là một chuỗi công việc.', 'This is the name of the username for the Inbound Message Source.': 'Đây là tên của người dùng cho Nguồn tin nhắn đến.', 'This is the short code of the language and will be used as the name of the file. This should be the ISO 639 code.': 'Đây là mã ngắn gọn của ngôn ngữ và sẽ được sử dụng làm tên của tệp tin. Mã này nên theo mã ISO 639.', 'This is the way to transfer data between machines as it maintains referential integrity.': 'Đây là cách truyền dữ liệu giữa các máy vì nó bảo toàn tham chiếu', 'This job has already been finished successfully.': 'Công việc đã được thực hiện thành công.', 'This level is not open for editing.': 'Cấp độ này không cho phép chỉnh sửa.', 'This might be due to a temporary overloading or maintenance of the server.': 'Điều này có lẽ là do máy chủ đang quá tải hoặc đang được bảo trì.', 'This module allows Warehouse Stock to be managed, requested & shipped between the Warehouses and Other Inventories': 'Chức năng này giúp việc quản lý, đặt yêu cầu và di chuyển hàng lưu trữ giữa các kho hàng và các vị trí lưu trữ khác trong kho', 'This resource cannot be displayed on the map!': 'Nguồn lực này không thể hiện trên bản đồ!', 'This resource is already configured for this repository': 'Nguồn lực này đã được thiết lập cấu hình cho kho hàng này', 'This role can not be assigned to users.': 'Chức năng không thể cấp cho người sử dụng', 'This screen allows you to upload a collection of photos to the server.': 'Màn hình này cho phép bạn đăng tải một bộ sưu tập hình ảnh lên máy chủ.', 'This shipment contains %s items': 'Lô hàng này chứa %s mặt hàng', 'This shipment contains one item': 'Lô hàng này chứa một mặt hàng', 'This shipment has already been received & subsequently canceled.': 'Lô hàng này đã được nhận & về sau bị hủy.', 'This shipment has already been received.': 'Lô hàng này đã được nhận.', 'This shipment has already been sent.': 'Lô hàng này đã được gửi.', 'This shipment has not been received - it has NOT been canceled because it can still be edited.': 'Lô hàng này chưa được nhận - KHÔNG bị hủy vì vẫn có thể điều chỉnh.', 'This shipment has not been returned.': 'Lô hàng này chưa được trả lại.', 'This shipment has not been sent - it cannot be returned because it can still be edited.': 'Lô hàng này chưa được gửi - không thể trả lại vì vẫn có thể điều chỉnh.', 'This shipment has not been sent - it has NOT been canceled because it can still be edited.': 'Lô hàng này chưa được gửi - KHÔNG bị hủy vì vẫn có thể điều chỉnh.', 'This should be an export service URL': 'Có thể đây là một dịch vụ xuất URL', 'Thunderstorm': 'Giông bão', 'Thursday': 'Thứ Năm', 'Ticket Details': 'Chi tiết Ticket', 'Ticket Viewer': 'Người kiểm tra vé', 'Ticket deleted': 'Đã xóa Ticket', 'Ticket': 'Vé', 'Tickets': 'Vé', 'Tiled': 'Lợp', 'Time Actual': 'Thời gian thực tế', 'Time Estimate': 'Ước lượng thời gian', 'Time Estimated': 'Thời gian dự đoán', 'Time Frame': 'Khung thời gian', 'Time In': 'Thời điểm vào', 'Time Log Deleted': 'Lịch trình thời gian đã xóa', 'Time Log Updated': 'Lịch trình thời gian đã cập nhật', 'Time Log': 'Lịch trình thời gian', 'Time Logged': 'Thời gian truy nhập', 'Time Out': 'Thời gian thoát', 'Time Question': 'Câu hỏi thời gian', 'Time Taken': 'Thời gian đã dùng', 'Time of Request': 'Thời gian yêu cầu', 'Time': 'Thời gian', 'Timeline': 'Nhật ký', 'Title to show for the Web Map Service panel in the Tools panel.': 'Tiêu đề thể hiện với bảng Dịch vụ Bản đồ Mạng trong bảng Công cụ.', 'Title': 'Tiêu đề', 'To Organization': 'Tới Tổ chức', 'To Person': 'Tới Người', 'To Warehouse/Facility/Office': 'Tới Nhà kho/Bộ phận/Văn phòng', 'To begin the sync process, click the button on the right => ': 'Nhấp chuột vào nút bên phải để kích hoạt quá trình đồng bộ', 'To edit OpenStreetMap, you need to edit the OpenStreetMap settings in your Map Config': 'Để chỉnh sửa OpenStreetMap, bạn cần chỉnh sửa cài đặt OpenStreetMap trong cài đặt cấu hình bản đồ của bạn.', 'To variable': 'Tới biến số', 'To': 'Tới', 'Tools and Guidelines Development': 'Xây dựng các hướng dẫn và công cụ', 'Tools': 'Công cụ', 'Tornado': 'Lốc xoáy', 'Total # of Target Beneficiaries': 'Tổng số # đối tượng hưởng lợi', 'Total Annual Budget': 'Tổng ngân sách hàng năm', 'Total Cost per Megabyte': 'Tổng chi phí cho mỗi Megabyte', 'Total Cost': 'Giá tổng', 'Total Funding Amount': 'Tổng số tiền hỗ trợ', 'Total Locations': 'Tổng các vị trí', 'Total Persons': 'Tổng số người', 'Total Recurring Costs': 'Tổng chi phí định kỳ', 'Total Value': 'Giá trị tổng', 'Total number of beds in this hospital. Automatically updated from daily reports.': 'Tổng số giường bệnh trong bệnh viện này. Tự động cập nhật từ các báo cáo hàng ngày.', 'Total number of houses in the area': 'Tổng số nóc nhà trong khu vực', 'Total number of schools in affected area': 'Số lượng trường học trong khu vực chịu ảnh hưởng thiên tai', 'Total': 'Tổng', 'Tourist Group': 'Nhóm khách du lịch', 'Tracing': 'Đang tìm kiếm', 'Track Shipment': 'Theo dõi lô hàng', 'Track with this Person?': 'Theo dõi Người này?', 'Track': 'Dấu viết', 'Trackable': 'Có thể theo dõi được', 'Tracking and analysis of Projects and Activities.': 'Giám sát và phân tích Dự án và Hoạt động', 'Traffic Report': 'Báo cáo giao thông', 'Training (Count)': 'Tập huấn (Số lượng)', 'Training Course Catalog': 'Danh mục khóa tập huấn', 'Training Courses': 'Danh mục khóa tập huấn', 'Training Details': 'Chi tiết về khóa tập huấn', 'Training Event Details': 'Chi tiết về khóa tập huấn', 'Training Event added': 'Khóa tập huấn được thêm vào', 'Training Event deleted': 'Khóa tập huấn đã xóa', 'Training Event updated': 'Khóa tập huấn đã cập nhật', 'Training Event': 'Khóa tập huấn', 'Training Events': 'Khóa tập huấn', 'Training Facility': 'Đơn vị đào tạo', 'Training Hours (Month)': 'Thời gian tập huấn (Tháng)', 'Training Hours (Year)': 'Thời gian tập huấn (Năm)', 'Training Report': 'Tập huấn', 'Training added': 'Tập huấn được thêm vào', 'Training deleted': 'Tập huấn đã xóa', 'Training of Master Trainers/ Trainers': 'Tập huấn Giảng viên/ Giảng viên nguồn', 'Training Sector': 'Lĩnh vực tập huấn', 'Training updated': 'Tập huấn đã cập nhật', 'Training': 'Tập huấn', 'Trainings': 'Tập huấn', 'Transfer Ownership To (Organization/Branch)': 'Chuyển Quyền sở hữu cho (Tổ chức/ Chi nhánh)', 'Transfer Ownership': 'Chuyển Quyền sở hữu', 'Transfer': 'Chuyển giao', 'Transit Status': 'Tình trạng chuyển tiếp', 'Transit': 'Chuyển tiếp', 'Transitional Shelter Construction': 'Xây dựng nhà tạm', 'Transitional Shelter': 'Nhà tạm', 'Translate': 'Dịch', 'Translated File': 'File được dịch', 'Translation Functionality': 'Chức năng Dịch', 'Translation': 'Dịch', 'Transparent?': 'Có minh bạch không?', 'Transportation Required': 'Cần vận chuyển', 'Transported By': 'Đơn vị vận chuyển', 'Tropical Storm': 'Bão nhiệt đới', 'Tropo Messaging Token': 'Mã thông báo tin nhắn Tropo', 'Tropo settings updated': 'Cài đặt Tropo được cập nhật', 'Truck': 'Xe tải', 'Try checking the URL for errors, maybe it was mistyped.': 'Kiểm tra đường dẫn URL xem có lỗi không, có thể đường dẫn bị gõ sai.', 'Try hitting refresh/reload button or trying the URL from the address bar again.': 'Thử nhấn nút làm lại/tải lại hoặc thử lại URL từ trên thanh địa chỉ.', 'Try refreshing the page or hitting the back button on your browser.': 'Thử tải lại trang hoặc nhấn nút trở lại trên trình duyệt của bạn.', 'Tsunami': 'Sóng thần', 'Twilio SMS InBox': 'Hộp thư đến SMS twilio', 'Twilio SMS Inbox empty. ': 'Hộp thư đến Twilio trống.', 'Twilio SMS Inbox': 'Hộp thư đến Twilio', 'Twilio SMS Settings': 'Cài đặt SMS twilio', 'Twilio SMS deleted': 'Tin nhắn Twilio đã xóa', 'Twilio SMS updated': 'Tin nhắn Twilio được cập nhật', 'Twilio SMS': 'Tin nhắn Twilio', 'Twilio Setting Details': 'Chi tiết cài đặt Twilio', 'Twilio Setting added': 'Cài đặt Twilio được thêm vào', 'Twilio Setting deleted': 'Cài đặt Twilio đã xóa', 'Twilio Settings': 'Cài đặt Twilio', 'Twilio settings updated': 'Cài đặt Twilio được cập nhật', 'Twitter ID or #hashtag': 'Tên đăng nhập Twitter hay từ hay chuỗi các ký tự bắt đầu bằng dấu # (#hashtag)', 'Twitter Settings': 'Cài đặt Twitter', 'Type of Transport': 'Loại phương tiện giao thông', 'Type of adjustment': 'Loại hình điều chỉnh', 'Type': 'Đối tượng', 'Types of Activities': 'Các loại hình Hoạt động', 'Types': 'Các loại', 'UPDATE': 'CẬP NHẬT', 'URL for the twilio API.': 'URL cho twilio API.', 'URL of the default proxy server to connect to remote repositories (if required). If only some of the repositories require the use of a proxy server, you can configure this in the respective repository configurations.': 'URL của máy chủ trung chuyển mặc định để kết nối với các kho hàng ở khu vực xa (nếu cần thiết). Nếu chỉ có một số kho hàng cần một máy chủ trung chuyển sử dụng thì bạn có thể tạo cấu hình cho máy này tương ứng với cấu hình của kho hàng.', 'URL of the proxy server to connect to the repository (leave empty for default proxy)': 'URL của máy chủ trung chuyển để kết nối với kho hàng (để trống với phần ủy nhiệm mặc định)', 'URL to a Google Calendar to display on the project timeline.': 'URL đến Lịch Google để thể hiện dòng thời gian của dự án.', 'UTC Offset': 'Độ xê dịch giờ quốc tế', 'Un-Repairable': 'Không-Sửa chữa được', 'Unable to find sheet %(sheet_name)s in uploaded spreadsheet': 'Không thể tìm thấy bảng %(sheet_name)s trong bảng tính đã đăng tải', 'Unable to open spreadsheet': 'Không thể mở được bảng tính', 'Unable to parse CSV file or file contains invalid data': 'Không thể cài đặt cú pháp cho file CSV hoặc file chức dữ liệu không hợp lệ', 'Unable to parse CSV file!': 'Không thể đọc file CSV', 'Unassigned': 'Chưa được điều động', 'Under 5': 'Dưới 5', 'Under which condition a local record shall be updated if it also has been modified locally since the last synchronization': 'Trong điều kiện nào thì một bản lưu nội bộ sẽ được cập nhật nếu bản lưu này cũng được điều chỉnh trong nội bộ kể từ lần đồng bộ hóa cuối cùng', 'Under which conditions local records shall be updated': 'Trong những điều kiện nào thì các bản lưu nội bộ sẽ được cập nhật', 'Unidentified': 'Không nhận dạng được', 'Unique Locations': 'Các địa điểm duy nhất', 'Unique identifier which THIS repository identifies itself with when sending synchronization requests.': 'Ký hiệu nhận dạng duy nhất để kho hàng NÀY nhận dạng chính nó khi gửi các đề nghị đồng bộ hóa.', 'Unit Cost': 'Đơn giá', 'Unit Short Code for e.g. m for meter.': 'Viết tắt các đơn vị, ví dụ m viết tắt của mét', 'Unit Value': 'Thành tiền', 'Unit added': 'Đã thêm đơn vị', 'Unit of Measure': 'Đơn vị đo', 'Unit updated': 'Đơn vị được cập nhật', 'Unit': 'Đơn vị', 'United States Dollars': 'Đô La Mỹ', 'Units': 'Các đơn vị', 'University / College': 'Trung cấp / Cao đẳng / Đại học', 'Unknown Locations': 'Địa điểm không xác định', 'Unknown question code': 'Mã câu hỏi chưa được biết đến', 'Unknown': 'Chưa xác định', 'Unloading': 'Đang gỡ ra', 'Unselect to disable the modem': 'Thôi chọn để tạm ngừng hoạt động của mô đem', 'Unselect to disable this API service': 'Thôi chọn để tạm ngừng dịch vụ API này', 'Unselect to disable this SMTP service': 'Thôi chọn để tạm ngừng dịch vụ SMTP này', 'Unsent': 'Chưa được gửi', 'Unspecified': 'Không rõ', 'Unsupported data format': 'Định dạng dữ liệu không được hỗ trợ', 'Unsupported method': 'Phương pháp không được hỗ trợ', 'Update Map': 'Cập nhật Bản đồ', 'Update Master file': 'Cập nhật tệp tin Gốc', 'Update Method': 'Cập nhật Phương pháp', 'Update Policy': 'Cập nhật Chính sách', 'Update Report': 'Cập nhật báo cáo', 'Update Request': 'Cập nhật Yêu cầu', 'Update Service Profile': 'Cập nhật hồ sơ đăng ký dịch vụ', 'Update Status': 'Cập nhật Tình trạng', 'Update Task Status': 'Cập nhật tình trạng công việc ', 'Update this entry': 'Cập nhật hồ sơ này', 'Updated By': 'Được cập nhật bởi', 'Upload .CSV': 'Tải lên .CSV', 'Upload Completed Assessment Form': 'Tải lên Mẫu đánh giá đã hoàn thiện', 'Upload Format': 'Tải định dạng', 'Upload Photos': 'Tải lên Hình ảnh', 'Upload Scanned OCR Form': 'Tải mẫu scan OCR', 'Upload Web2py portable build as a zip file': 'Tải lên Web2py như một tệp nén', 'Upload a Question List import file': 'Tải lên một tệp tin được chiết xuất chứa Danh sách các câu hỏi', 'Upload a Spreadsheet': 'Tải một bảng tính lên', 'Upload a file formatted according to the Template.': 'Nhập khẩu được định dạng theo mẫu', 'Upload a text file containing new-line separated strings:': 'Tải lên một tệp tin văn bản chứa các chuỗi được tách thành dòng mới:', 'Upload an Assessment Template import file': 'Tải lên một tệp tin được chiết xuất chứa Biểu mẫu Khảo sát đánh giá', 'Upload an image file (png or jpeg), max. 400x400 pixels!': 'Tải lên file hình ảnh (png hoặc jpeg) có độ phân giải tối đa là 400x400 điểm ảnh!', 'Upload demographic data': 'Tải lên dữ liệu nhân khẩu', 'Upload file': 'Tải file', 'Upload indicators': 'Tải lên các chỉ số', 'Upload successful': 'Tải lên thành công', 'Upload the (completely or partially) translated csv file': 'Tải lên (toàn bộ hoặc một phần) tệp tin csv đã được chuyển ngữ', 'Upload the Completed Assessment Form': 'Tải lên Mẫu đánh giá', 'Upload translated files': 'Tải file được dịch', 'Upload': 'Tải lên', 'Uploaded PDF file has more/less number of page(s) than required. Check if you have provided appropriate revision for your Form as well as check the Form contains appropriate number of pages.': '', 'Uploaded file is not a PDF file. Provide a Form in valid PDF Format.': 'File được tải không phải định dạng PDF. Cung cấp mẫu ở định dạng PDF', 'Uploading report details': 'Đang tải lên các chi tiết báo cáo', 'Urban Fire': 'Cháy trong thành phố', 'Urban Risk & Planning': 'Quy hoạch đô thị và Rủi ro đô thị', 'Urdu': 'Ngôn ngữ Urdu(một trong hai ngôn ngữ chính thức tại Pakistan', 'Urgent': 'Khẩn cấp', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Sử dụng (...)&(...) cho VÀ, (...)|(...) cho HOẶC, và ~(...) cho KHÔNG để tạo ra những câu hỏi phức tạp hơn.', 'Use Geocoder for address lookups?': 'Sử dụng Geocoder để tìm kiếm địa chỉ?', 'Use Translation Functionality': 'Sử dụng Chức năng Dịch', 'Use decimal': 'Sử dụng dấu phẩy', 'Use default': 'Sử dụng cài đặt mặc định', 'Use deg, min, sec': 'Sử dụng độ, phút, giây', 'Use these links to download data that is currently in the database.': 'Dùng liên kết này để tải dữ liệu hiện có trên cơ sở dữ liệu xuống', 'Use this space to add a description about the Bin Type.': 'Thêm thông tin mô tả loại Bin ở đây', 'Use this space to add a description about the warehouse/site.': 'Thêm mô tả nhà kho/site ở đây', 'Use this space to add additional comments and notes about the Site/Warehouse.': 'Viết bình luận và ghi chú về site/nhà kho ở đây', 'Use this to set the starting location for the Location Selector.': 'Sử dụng cái này để thiết lập địa điểm xuất phát cho Bộ chọn lọc Địa điểm.', 'Used in onHover Tooltip & Cluster Popups to differentiate between types.': 'Đã dùng trong onHover Tooltip & Cluster Popups để phân biệt các loại', 'Used to build onHover Tooltip & 1st field also used in Cluster Popups to differentiate between records.': 'Đã dùng để xây dựng onHover Tooltip & trường thứ nhất cũng đã sử dụng trong Cluster Popups phân biệt các hồ sơ.', 'Used to check that latitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Được sử dụng để kiểm tra vĩ độ của những địa điểm được nhập có chính xác không. Có thể được sử dụng để lọc danh sách các nguồn lực có địa điểm.', 'Used to check that longitude of entered locations is reasonable. May be used to filter lists of resources that have locations.': 'Được sử dụng để kiểm tra kinh độ của những địa điểm được nhập có chính xác không. Có thể được sử dụng để lọc danh sách các nguồn lực có địa điểm.', 'User Account has been Approved': 'Tài khoản của người sử dụng đã được duyệt', 'User Account has been Disabled': 'Tài khoản của người sử dụng đã bị ngưng hoạt động', 'User Account': 'Tài khoản của người sử dụng', 'User Details': 'Thông tin về người sử dụng', 'User Guidelines Synchronization': 'Đồng bộ hóa Hướng dẫn cho Người sử dụng', 'User Management': 'Quản lý người dùng', 'User Profile': 'Hồ sơ người sử dụng', 'User Requests': 'Yêu cầu của người dùng', 'User Roles': 'Vai trò của người sử dụng', 'User Updated': 'Đã cập nhât người dùng', 'User added to Role': 'Người sử dụng được thêm vào chức năng', 'User added': 'Người sử dụng được thêm vào', 'User deleted': 'Người sử dụng đã xóa', 'User has been (re)linked to Person and Human Resource record': 'Người sử dụng đã được liên kết thành công', 'User updated': 'Người sử dụng được cập nhật', 'User with Role': 'Người sử dụng có chức năng này', 'User': 'Người sử dụng', 'Username to use for authentication at the remote site.': 'Tên người sử dụng dùng để xác nhận tại khu vực ở xa.', 'Username': 'Tên người sử dụng', 'Users in my Organizations': 'Những người dùng trong tổ chức của tôi', 'Users removed': 'Xóa người dùng', 'Users with this Role': 'Những người sử dụng với chức năng này', 'Users': 'Danh sách người dùng', 'Uses the REST Query Format defined in': 'Sử dụng Định dạng câu hỏi REST đã được xác định trong', 'Ushahidi Import': 'Nhập Ushahidi', 'Utilization Details': 'Chi tiết về Việc sử dụng', 'Utilization Report': 'Báo cáo quá trình sử dụng', 'VCA (Vulnerability and Capacity Assessment': 'VCA (Đánh giá Tình trạng dễ bị tổn thương và Khả năng)', 'VCA REPORTS': 'BÁO CÁO VCA', 'VCA Report': 'Báo cáo VCA', 'Valid From': 'Có hiệu lực từ', 'Valid Until': 'Có hiệu lực đến', 'Valid': 'Hiệu lực', 'Validation error': 'Lỗi xác thực', 'Value per Pack': 'Giá trị mỗi gói', 'Value': 'Giá trị', 'Vector Control': 'Kiểm soát Vec-tơ', 'Vehicle Assignment updated': 'Việc điệu động xe được cập nhật', 'Vehicle Assignments': 'Các việc điều động xe', 'Vehicle Crime': 'Tội phạm liên quan đến xe', 'Vehicle Details': 'Thông tin về xe', 'Vehicle Plate Number': 'Biển số xe', 'Vehicle Types': 'Loại phương tiện di chuyển', 'Vehicle assigned': 'Xe được điều động', 'Vehicle unassigned': 'Xe chưa được điều động', 'Vehicle': 'Xe', 'Vehicles': 'Phương tiện di chuyển', 'Venue': 'Địa điểm tổ chức', 'Verified': 'Đã được thẩm định', 'Verified?': 'Đã được thẩm định?', 'Verify Password': 'Kiểm tra mật khẩu', 'Verify password': 'Kiểm tra mật khẩu', 'Version': 'Phiên bản', 'Very Good': 'Rất tốt', 'Very Strong': 'Rất mạnh', 'Vietnamese': 'Tiếng Việt', 'View Alerts received using either Email or SMS': 'Xem các Cảnh báo nhận được sử dụng thư điện tử hoặc tin nhắn', 'View All': 'Xem tất cả', 'View Email InBox': 'Xem hộp thư điện tử đến', 'View Email Settings': 'Xem cài đặt thư điện tử', 'View Error Tickets': 'Xem các vé lỗi', 'View Fullscreen Map': 'Xem bản đồ toàn màn hình', 'View Items': 'Xem các mặt hàng', 'View Location Details': 'Xem chi tiết vị trí', 'View Outbox': 'Xem hộp thư điện tử đi', 'View Reports': 'Xem báo cáo', 'View Requests for Aid': 'Xem Yêu cầu viện trợ', 'View Settings': 'Xem cài đặt', 'View Test Result Reports': 'Xem báo cáo kết quả kiểm tra', 'View Translation Percentage': 'Xem tỷ lệ phần trăm chuyển đổi', 'View Twilio SMS': 'Xem tin nhắn văn bản Twilio', 'View Twilio Settings': 'Xem các Cài đặt Twilio', 'View all log entries': 'Xem toàn bộ nhật ký ghi chép', 'View as Pages': 'Xem từng trang', 'View full size': 'Xem kích thước đầy đủ', 'View log entries per repository': 'Xem ghi chép nhật ký theo kho hàng', 'View on Map': 'Xem trên bản đồ', 'View or update the status of a hospital.': 'Xem hoặc cập nhật trạng thái của một bệnh viện', 'View the hospitals on a map.': 'Hiển thị bệnh viện trên bản đồ', 'View the module-wise percentage of translated strings': 'Xem phần trăm ', 'View': 'Xem', 'View/Edit the Database directly': 'Trực tiếp Xem/Sửa Cơ sở dữ liệu', 'Village / Suburb': 'Thôn / Xóm', 'Violence Prevention': 'Phòng ngừa bạo lực', 'Vocational School/ College': 'Trung cấp/ Cao đẳng', 'Volcanic Ash Cloud': 'Mây bụi núi lửa', 'Volcanic Event': 'Sự kiện phun trào núi lửa', 'Volcano': 'Núi lửa', 'Volume (m3)': 'Thể tích (m3)', 'Volunteer Cluster Position added': 'Vị trí Nhóm Tình nguyện viên được thêm vào', 'Volunteer Cluster Position deleted': 'Vị trí Nhóm Tình nguyện viên đã xóa', 'Volunteer Cluster Position updated': 'Vị trí Nhóm Tình nguyện viên được cập nhật', 'Volunteer Cluster Position': 'Vị trí Nhóm Tình nguyện viên', 'Volunteer Cluster Type added': 'Mô hình Nhóm Tình nguyện viên được thêm vào', 'Volunteer Cluster Type deleted': 'Mô hình Nhóm Tình nguyện viên đã xóa', 'Volunteer Cluster Type updated': 'Mô hình Nhóm Tình nguyện viên được cập nhật', 'Volunteer Cluster Type': 'Mô hình Nhóm Tình nguyện viên', 'Volunteer Cluster added': 'Nhóm Tình nguyện viên được thêm vào', 'Volunteer Cluster deleted': 'Nhóm Tình nguyện viên đã xóa', 'Volunteer Cluster updated': 'Nhóm Tình nguyện viên được cập nhật', 'Volunteer Cluster': 'Nhóm Tình nguyện viên', 'Volunteer Data': 'Dữ liệu tình nguyện viên', 'Volunteer Details updated': 'Thông tin về Tình nguyện viên được cập nhật', 'Volunteer Details': 'Thông tin về Tình nguyện viên', 'Volunteer Management': 'Quản lý tình nguyện viên', 'Volunteer Project': 'Dự án tình nguyện', 'Volunteer Record': 'Hồ sơ TNV', 'Volunteer Registration': 'Đăng ký tình nguyện viên', 'Volunteer Registrations': 'Đăng ksy tình nguyện viên', 'Volunteer Report': 'Tình nguyện viên', 'Volunteer Request': 'Đề nghị Tình nguyện viên', 'Volunteer Role (Count)': 'Chức năng nhiệm vụ TNV (Số lượng)', 'Volunteer Role Catalog': 'Danh mục về Vai trò của Tình nguyện viên', 'Volunteer Role Catalogue': 'Danh mục vai trò TNV', 'Volunteer Role Details': 'Chi tiết về Vai trò của Tình nguyện viên', 'Volunteer Role added': 'Vai trò của Tình nguyện viên được thêm vào', 'Volunteer Role deleted': 'Vai trò của Tình nguyện viên đã xóa', 'Volunteer Role updated': 'Vai trò của Tình nguyện viên được cập nhật', 'Volunteer Role': 'Chức năng nhiệm vụ TNV', 'Volunteer Roles': 'Chức năng nhiệm vụ TNV', 'Volunteer Service Record': 'Bản lưu Dịch vụ Tình nguyện viên', 'Volunteer added': 'Tình nguyện viên được thêm vào', 'Volunteer and Staff Management': 'Quản lý TNV và Cán bộ', 'Volunteer deleted': 'Tình nguyện viên đã xóa', 'Volunteer registration added': 'Đã thêm đăng ký tình nguyện viên', 'Volunteer registration deleted': 'Đã xóa đăng ký tình nguyện viên', 'Volunteer registration updated': 'Đã cập nhật đăng ký tình nguyện viên', 'Volunteer': 'Tình nguyện viên', 'Volunteers': 'Tình nguyện viên', 'Votes': 'Bình chọn', 'Vulnerability Aggregated Indicator Details': 'Chi tiết về chỉ số tổng hợp về Tình trạng dễ bị tổn thương', 'Vulnerability Aggregated Indicator added': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability Aggregated Indicator deleted': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability Aggregated Indicator updated': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability Aggregated Indicator': 'Chỉ số tổng hợp về Tình trạng dễ bị tổn thương', 'Vulnerability Aggregated Indicators': 'Các chỉ số tổng hợp về Tình trạng dễ bị tổn thương', 'Vulnerability Data Details': 'Dữ liệu chi tiết về Tình trạng dễ bị tổn thương', 'Vulnerability Data added': 'Dữ liệu về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability Data deleted': 'Dữ liệu về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability Data updated': 'Dữ liệu về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability Data': 'Dữ liệu về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator Details': 'Chỉ số chi tiết về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator Source Details': 'Chi tiết Nguồn Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator Sources': 'Các Nguồn Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Indicator added': 'Chỉ số về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability Indicator deleted': 'Chỉ số về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability Indicator updated': 'Chỉ số về Tình trạng dễ bị tổn thương được cập nhật', 'Vulnerability Indicator': 'Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Indicators': 'Các Chỉ số về Tình trạng dễ bị tổn thương', 'Vulnerability Mapping': 'Vẽ bản đồ về Tình trạng dễ bị tổn thương', 'Vulnerability indicator sources added': 'Các nguồn chỉ số về Tình trạng dễ bị tổn thương được thêm vào', 'Vulnerability indicator sources deleted': 'Các nguồn chỉ số về Tình trạng dễ bị tổn thương đã xóa', 'Vulnerability indicator sources updated': 'Các nguồn chỉ số về Tình trạng dễ bị tổn thương được cập nhật', #'Vulnerability': 'Tình trạng dễ bị tổn thương', 'Vulnerability': 'TTDBTT', 'Vulnerable Populations': 'Đối tượng dễ bị tổn thương', 'WARNING': 'CẢNH BÁO', 'WATSAN': 'NSVS', 'WAYBILL': 'VẬN ĐƠN', 'WFS Layer': 'Lớp WFS', 'WGS84 (EPSG 4236) is required for many WMS servers.': 'WGS84 (EPSG 4236) cần có cho nhiều máy chủ WMS.', 'WMS Layer': 'Lớp WMS', 'Warehouse Details': 'Thông tin về Nhà kho', 'Warehouse Management': 'Quản lý kho hàng', 'Warehouse Stock Details': 'Thông tin về Hàng hóa trong kho', 'Warehouse Stock Report': 'Báo cáo Hàng hóa trong Nhà kho', 'Warehouse Stock updated': 'Hàng hóa trong kho được cập nhật', 'Warehouse Stock': 'Hàng trong kho', 'Warehouse added': 'Nhà kho được thêm vào', 'Warehouse deleted': 'Nhà kho đã xóa', 'Warehouse updated': 'Nhà kho được cập nhật', 'Warehouse': 'Nhà kho', 'Warehouse/Facility/Office (Recipient)': 'Nhà kho/Bộ phận/Văn phòng (Bên nhận)', 'Warehouse/Facility/Office': 'Nhà kho/Bộ phận/Văn phòng', 'Warehouses': 'Nhà kho', 'Water Sources': 'Các nguồn nước', 'Water Supply': 'Cung cấp nước sạch', 'Water and Sanitation': 'Nước sạch và Vệ sinh', 'Water gallon': 'Ga-lông nước', 'Water': 'Nước', 'Waterspout': 'Máng xối nước', 'Way Bill(s)': 'Hóa đơn thu phí đường bộ', 'Waybill Number': 'Số Vận đơn', 'We have tried': 'Chúng tôi đã cố gắng', 'Weak': 'Yếu', 'Web API settings updated': 'Cài đặt API Trang thông tin được cập nhật', 'Web API': 'API Trang thông tin', 'Web Form': 'Kiểu Trang thông tin', 'Web Map Service Browser Name': 'Tên Trình duyệt Dịch vụ Bản đồ Trang thông tin', 'Web Map Service Browser URL': 'URL Trình duyệt Dịch vụ Bản đồ Trang thông tin', 'Web2py executable zip file found - Upload to replace the existing file': 'Tệp tin nén có thể thực hiện chức năng gián điệp - Đăng tải để thay thế tệp tin đang tồn tại', 'Web2py executable zip file needs to be uploaded to use this function.': 'Tệp tin nén có thể thực hiện chức năng gián điệp cần được đăng tải để sử dụng chức năng này.', 'Website': 'Trang thông tin', 'Week': 'Tuần', 'Weekly': 'Hàng tuần', 'Weight (kg)': 'Trọng lượng (kg)', 'Weight': 'Trọng lượng', 'Welcome to %(system_name)s': 'Chào mừng anh/chị truy cập %(system_name)s', 'Welcome to the': 'Chào mừng bạn tới', 'Well-Known Text': 'Từ khóa thường được dùng', 'What are you submitting?': 'Bạn đang gửi cái gì?', 'What order to be contacted in.': 'Đơn hàng nào sẽ được liên hệ trao đổi.', 'What the Items will be used for': 'Các mặt hàng sẽ được sử dụng để làm gì', 'When this search was last checked for changes.': 'Tìm kiếm này được kiểm tra lần cuối là khi nào để tìm ra những thay đổi.', 'Whether the Latitude & Longitude are inherited from a higher level in the location hierarchy rather than being a separately-entered figure.': 'Vĩ độ & Kinh độ có được chiết xuất từ một địa điểm có phân cấp hành chính cao hơn hay là một con số được nhập riêng lẻ.', 'Whether the resource should be tracked using S3Track rather than just using the Base Location': 'Nguồn lực nên được theo dõi sử dụng Dấu vết S3 hay chỉ sử dụng Địa điểm cơ bản', 'Which methods to apply when importing data to the local repository': 'Áp dụng phương pháp nào khi nhập dữ liệu vào kho dữ liệu nội bộ', 'Whiskers': 'Râu', 'Who is doing What Where': 'Ai đang làm Gì Ở đâu', 'Who usually collects water for the family?': 'Ai là người thường đi lấy nước cho cả gia đình', 'Widowed': 'Góa', 'Width (m)': 'Rộng (m)', 'Width': 'Độ rộng', 'Wild Fire': 'Cháy Lớn', 'Will be filled automatically when the Item has been Repacked': 'Sẽ được điền tự động khi Hàng hóa được Đóng gói lại', 'Will be filled automatically when the Shipment has been Received': 'Sẽ được điền tự động khi Lô hàng được Nhận', 'Wind Chill': 'Rét cắt da cắt thịt', 'Winter Storm': 'Bão Mùa đông', 'Women of Child Bearing Age': 'Phụ nữ trong độ tuổi sinh sản', 'Women who are Pregnant or in Labour': 'Phụ nữ trong thời kỳ thai sản', 'Work phone': 'Điện thoại công việc', 'Work': 'Công việc', 'Workflow not specified!': 'Chuỗi công việc chưa được xác định!', 'Workflow': 'Chuỗi công việc', 'Working hours end': 'Hết giờ làm việc', 'Working hours start': 'Bắt đầu giờ làm việc', 'X-Ray': 'Tia X', 'XML parse error': 'Lỗi phân tích cú pháp trong XML', 'XSLT stylesheet not found': 'Không tìm thấy kiểu bảng tính XSLT', 'XSLT transformation error': 'Lỗi chuyển đổi định dạng XSLT', 'XYZ Layer': 'Lớp XYZ', 'YES': 'CÓ', 'Year of Manufacture': 'Năm sản xuất', 'Year that the organization was founded': 'Năm thành lập tổ chức', 'Year': 'Năm', 'Yes': 'Có', 'Yes, No': 'Có, Không', 'You are about to submit indicator ratings for': 'Bạn chuẩn bị gửi đánh giá chỉ số cho', 'You are attempting to delete your own account - are you sure you want to proceed?': 'Bạn đang cố gắng xóa tài khoản của bạn - bạn có chắc chắn muốn tiếp tục không?', 'You are currently reported missing!': 'Hiện tại bạn được báo cáo là đã mất tích!', 'You are not permitted to approve documents': 'Bạn không được phép phê duyệt tài liệu', 'You are not permitted to upload files': 'Bạn không được phép đăng tải tệp tin', 'You are viewing': 'Bạn đang xem', 'You can click on the map below to select the Lat/Lon fields': 'Bạn có thể nhấn vào bản đồ phía dưới để chọn các trường Vĩ độ/Kinh độ', 'You can only make %d kit(s) with the available stock': 'Bạn chỉ có thể điền %d bộ(s) với các số lượng hàng có sẵn', 'You can select the Draw tool': 'Bạn có thể lựa chọn công cụ Vẽ', 'You can set the modem settings for SMS here.': 'Bạn có thể cài đặt modem cho tin nhắn ở đây', 'You can use the Conversion Tool to convert from either GPS coordinates or Degrees/Minutes/Seconds.': 'Bạn có thể sử dụng Công cụ Đổi để chuyển đổi từ tọa độ GPS (Hệ thống định vị toàn cầu) hoặc Độ/ Phút/ Giây.', 'You do not have permission for any facility to add an order.': 'Bạn không có quyền đối với bất kỳ tính năng nào để thêm đơn đặt hàng.', 'You do not have permission for any facility to make a commitment.': 'Bạn không có quyền đối với bất kỳ tính năng nào để đưa ra cam kết.', 'You do not have permission for any facility to make a request.': 'Bạn không có quyền đối với bất kỳ tính năng nào để đưa ra yêu cầu.', 'You do not have permission for any facility to perform this action.': 'Bạn không có quyền đối với bất kỳ tính năng nào để thực hiện hành động này.', 'You do not have permission for any facility to receive a shipment.': 'Bạn không có quyền đối với bất kỳ tính năng nào để nhận chuyến hàng.', 'You do not have permission for any facility to send a shipment.': 'Bạn không có quyền đối với bất kỳ tính năng nào để gửi chuyến hàng.', 'You do not have permission for any organization to perform this action.': 'Bạn không có quyền truy cập bất cứ tổ chức nào để thực hiện hành động này', 'You do not have permission for any site to add an inventory item.': 'Bạn không được phép thêm mặt hàng lưu kho tại bất kỳ địa điểm nào.', 'You do not have permission to adjust the stock level in this warehouse.': 'Bạn không được phép điều chỉnh cấp độ lưu kho trong nhà kho này.', 'You do not have permission to cancel this received shipment.': 'Bạn không được phép hủy lô hàng đã nhận này.', 'You do not have permission to cancel this sent shipment.': 'Bạn không được phép hủy lô hàng đã gửi này.', 'You do not have permission to make this commitment.': 'Bạn không được phép thực hiện cam kết này.', 'You do not have permission to receive this shipment.': 'Bạn không được phép nhận lô hàng này.', 'You do not have permission to return this sent shipment.': 'Bạn không được phép trả lại lô hàng đã gửi này.', 'You do not have permission to send messages': 'Bạn không được phép gửi tin nhắn', 'You do not have permission to send this shipment.': 'Bạn không được phép gửi lô hàng này.', 'You have unsaved changes. You need to press the Save button to save them': 'Bạn chưa lưu lại những thay đổi. Bạn cần nhấn nút Lưu để lưu lại những thay đổi này', 'You must enter a minimum of %d characters': 'Bạn phải điền ít nhất %d ký tự', 'You must provide a series id to proceed.': 'Bạn phải nhập số id của serie để thao tác tiếp', 'You need to check all item quantities and allocate to bins before you can receive the shipment': 'Bạn cần kiểm tra số lượng của tất cả các mặt hàng và chia thành các thùng trước khi nhận lô hàng', 'You need to check all item quantities before you can complete the return process': 'Bạn cần kiểm tra số lượng của tất cả các mặt hàng trước khi hoàn tất quá trình trả lại hàng', 'You need to create a template before you can create a series': 'Bạn cần tạo ra một biểu mẫu trước khi tạo ra một loạt các biểu mẫu', 'You need to use the spreadsheet which you can download from this page': 'Bạn cần sử dụng bảng tính tải từ trang này', 'You should edit Twitter settings in models/000_config.py': 'Bạn nên chỉnh sửa cài đặt Twitter trong các kiểu models/000-config.py', 'Your name for this search. Notifications will use this name.': 'Tên của bạn cho tìm kiếm này. Các thông báo sẽ sử dụng tên này.', 'Your post was added successfully.': 'Bạn đã gửi thông tin thành công', 'Youth Development': 'Phát triển thanh thiếu niên', 'Youth and Volunteer Development': 'Phát triển TNV và Thanh thiếu niên', 'Zone Types': 'Các loại vùng châu lục', 'Zones': 'Vùng châu lục', 'Zoom In: click in the map or use the left mouse button and drag to create a rectangle': 'Phóng to: nhấn vào bản đồ hoặc sử dụng nút chuột trái và kéo để tạo ra một hình chữ nhật', 'Zoom Levels': 'Các cấp độ phóng', 'Zoom Out: click in the map or use the left mouse button and drag to create a rectangle': 'Thu nhỏ: nhấn vào bản đồ hoặc sử dụng nút chuột trái và kéo để tạo ra một hình chữ nhật', 'Zoom in closer to Edit OpenStreetMap layer': 'Phóng gần hơn tới lớp Sửa Bản đồ Đường đi Chưa xác định', 'Zoom to Current Location': 'Phóng đến Địa điểm Hiện tại', 'Zoom to maximum map extent': 'Phóng to để mở rộng tối đa bản đồ', 'Zoom': 'Phóng', 'access granted': 'truy cập được chấp thuận', 'activate to sort column ascending': 'Sắp xếp theo thứ tự tăng dần', 'activate to sort column descending': 'Sắp xếp theo thứ tự giảm dần', 'active': 'đang hoạt động', 'adaptation to climate change, sustainable development': 'thích ứng với biến đổi khí hậu, phát triển bền vững', 'always update': 'luôn luôn cập nhật', 'an individual/team to do in 1-2 days': 'một cá nhân/nhóm thực hiện trong 1-2 ngày', 'and': 'và', 'anonymous user': 'Người dùng nặc danh', 'assigned': 'đã phân công', 'at-risk populations, including: children, orphans, disabled, elderly, homeless, hospitalized people, illegal immigrants, illiterate, medically or chemically dependent, impoverished p': 'đối tượng chịu rủi ro gồm có: trẻ em, trẻ mồ côi, người khuyết tật, người già, người vô gia cư, người bệnh, dân di cư bất hợp pháp, người không biết chữ, người phải điều trị hóa chất hoặc điều trị y tế, người nghèo ', 'average': 'Trung bình', 'black': 'đen', 'blond': 'Tóc vàng', 'blue': 'Xanh da trời', 'brown': 'Nâu', 'bubonic plague, cholera, dengue, non-pandemic diseases, typhoid': 'bệnh dịch hạch, dịch tả, bệnh đănggơ, bệnh không phát dịch, bệnh thương hàn', 'building back better, long-term recovery and reconstruction, rehabilitation, shelter': 'hồi phục tốt hơn, tái xây dựng và phục hồi lâu dài, nhà tạm', 'building codes, building standards, building materials, construction, retrofitting': 'luật xây dựng, tiêu chuẩn xây dựng, vật liệu xây dựng, trang bị thêm ', 'by %(person)s': 'bởi %(person)s', 'by': 'bởi', 'can be used to extract data from spreadsheets and put them into database tables.': 'có thể dùng để trích xuất dữ liệu từ bẳng tính đưa vào cơ sở dữ liệu', 'cannot be deleted.': 'không thể xóa', 'capacity of health practitioners, mental health': 'năng lực của cán bộ CSSK, sức khỏe tâm thần', 'check all': 'kiểm tra tất cả', 'civic action, collective community action, community-based organization (CBO) action, grassroots action, integrative DRR, non-governmental organization (NGO) action': 'hành động của công dân, của cộng đồng, của các tổ chức dựa vào cộng đồng, GNRRTH mang tính tích hợp, các hành động của các tổ chức phi chính phủ.', 'civil protection, contingency and emergency planning, early recovery, preparedness': 'bảo vệ nhân dân, lập kế hoạch dự phòng và ứng phó với tình huống khẩn cấp, phục hồi nhanh, phòng ngừa', 'clear': 'xóa', 'click here': 'Ấn vào đây', 'coastal flood, wave surge, wind setup': 'lũ ven biển, sóng dâng cao, tạo gió', 'consider': 'cân nhắc', 'contains': 'Gồm có', 'coping capacity, loss absorption, loss acceptance, psychosocial support, social vulnerability, trauma prevention': 'khả năng ứng phó, khả năng chịu tổn thất, hỗ trợ tâm lý, tổn thương xã hội, ngăn ngừa các chấn thương tâm lý', 'corporate social responsibility, private sector engagement in DRR': 'trách nhiệm với xã hội của các công ty, tập đoàn, sự tham gia của khu vực tư nhân vào công tác GNRRTH', 'cost benefit analysis, disaster risk financing, financial effects of disasters, poverty and disaster risk, risk sharing, socio-economic impacts of disasters': 'phân tích lợi ích kinh tế, hỗ trợ tài chính cho hoạt động ứng phó với rủi ro thảm họa, ảnh hưởng tài chính của thảm họa, nghèo đói và rủi ro thảm họa, sự tác động đến kinh tế xã hội của thảm họa', 'crater, lava, magma, molten materials, pyroclastic flows, volcanic rock, volcanic ash': 'dung nham, vật liệu nóng chảy, nham tầng phun trào, nham thạch, bụi núi lửa', 'created': 'Đã tạo', 'curly': 'Xoắn', 'current': 'Đang hoạt động', 'daily': 'hàng ngày', 'dark': 'tối', 'database %s select': '%s cơ sở dự liệu lựa chọn', 'database': 'Cơ sở Dữ liệu', 'days': 'các ngày', 'debris flow, mud flow, mud slide, rock fall, slide, lahar, rock slide and topple': 'sạt lở đất, đá, sạt bùn', 'deceased': 'Đã chết', 'deficiency of precipitation, desertification, pronounced absence of rainfall': 'thiếu nước, sa mạc hóa, không có mưa kéo dài', 'delete all checked': 'Xóa tất cả các chọn', 'deleted': 'đã xóa', 'disaster databases, disaster information, disaster risk information portals, ICT': 'cơ sở dữ liệu về thảm họa, thông tin thảm họa, cổng thông tin về rủi ro thảm họa, ICT', 'disaster insurance, contingency funding, micro-insurance, post-disaster loans, risk financing, risk insurance, risk sharing, pooling': 'bảo hiểm thảm họa, quỹ dự phòng, bảo hiểm vi mô, khoản vay sau thảm họa, hỗ trợ tài chính nhằm ứng phó với rủi ro, chia sẻ, hợp nhất nhằm ứng phó với rủi ro', 'disaster reporting, disaster information dissemination': 'báo cáo thảm họa, tuyên truyền thông tin về thảm họa', 'disaster risk reduction policy and legislation, National Platform for disaster risk reduction, Regional Platforms for disaster risk reduction': 'việc banh hành và hoạch định chính sách về GNRRTH, Diễn đàn quốc gia về GNRRTH, Diễn đàn khu vực về GNRRTH', 'diseased': 'Bị dịch bệnh', 'displaced': 'Sơ tán', 'divorced': 'ly hôn', 'does not contain': 'không chứa', 'drinking water, freshwater, irrigation, potable water, water and sanitation, water resource management': 'nước uống, nước ngọt, hệ thống tưới tiêu, nước sạch và vệ sinh, quản lý nguồn nước', 'e.g. Census 2010': 'ví dụ Điều tra 2010', 'editor': 'người biên tập', 'expired': 'đã hết hạn', 'export as csv file': 'Xuất dưới dạng file csv', 'extreme weather, extreme temperature, cold temperatures': 'thời tiết cực đoan, nhiệt độ khắc nghiệt, nhiệt độ lạnh', 'extreme weather, extreme temperature, high temperatures': 'thời tiết cực đoan, nhiệt độ khắc nghiệt, nhiệt độ cao', 'fair': 'công bằng', 'fat': 'béo', 'feedback': 'phản hồi', 'female': 'nữ', 'fill in order: day(2) month(2) year(4)': 'điền theo thứ tự: ngày(2) tháng(2) năm(4)', 'fill in order: hour(2) min(2) day(2) month(2) year(4)': 'điền theo thứ tự: giờ(2) phút(2) ngày(2) tháng(2) năm(4)', 'forehead': 'Phía trước', 'form data': 'Tạo dữ liệu', 'found': 'Tìm thấy', 'full': 'đầy đủ', 'gendered vulnerability, gender-sensitive disaster risk management': 'tình trạng dễ bị tổn thương có yếu tố về giới, quản lý rủi ro thảm họa có tính nhạy cảm về giới', 'geographic information systems, hazard exposure mapping, vulnerability mapping, risk mapping': 'hệ thống thông tin địa lý, bản đồ hiểm họa, bản đồ tình trạng dễ bị tổn thương, bản đồ rủi ro', 'getting': 'đang nhận được', 'green': 'xanh lá cây', 'grey': 'xám', 'here': 'ở đây', 'hourly': 'hàng giờ', 'hours': 'thời gian hoạt động', 'hurricane, tropical storm, tropical depression, typhoon': 'bão, bão nhiệt đới, áp thấp nhiệt đới', 'ignore': 'bỏ qua', 'in GPS format': 'Ở định dạng GPS', 'in Stock': 'Tồn kho', 'in this': 'trong đó', 'in': 'trong', 'injured': 'Bị thương', 'input': 'nhập liệu', 'insert new %s': 'Thêm mới %s', 'insert new': 'Thêm mới', 'insufficient number of pages provided': 'không đủ số lượng trang được cung cấp', 'inundation; includes: flash floods': 'ngập úng, lũ quét', 'invalid request': 'Yêu cầu không hợp lệ', 'is a central online repository where information on all the disaster victims and families, especially identified casualties, evacuees and displaced people can be stored. Information like name, age, contact number, identity card number, displaced location, and other details are captured. Picture and finger print details of the people can be uploaded to the system. People can also be captured by group for efficiency and convenience.': 'là trung tâm thông tin trực tuyến, nơi lưu trữ thông tin về các nạn nhân và gia đình chịu ảnh hưởng của thiên tai, đặc biệt là xác định con số thương vong và lượng người sơ tán.Thông tin như tên, tuổi, số điện thoại, số CMND, nơi sơ tán và các thông tin khác cũng được lưu lại.Ảnh và dấu vân tay cũng có thể tải lên hệ thống.Để hiệu quả và tiện lợi hơn có thể quản lý theo nhóm', 'items selected': 'mặt hàng được lựa chọn', 'key': 'phím', 'label': 'Nhãn', 'latrines': 'nhà vệ sinh', 'learning, safe schools': 'trường học an toàn, giáo dục', 'light': 'Ánh sáng', 'local knowledge, local risk mapping': 'hiểu biết của địa phương, lập bản đồ rủi ro của địa phương', 'locust, plague, African bees': 'châu chấu, ong Châu Phi', 'long': 'dài', 'long>12cm': 'dài>12cm', 'male': 'Nam', 'mandatory fields': 'Trường bắt buộc', 'married': 'đã kết hôn', 'max': 'tới', 'maxExtent': 'Mở rộng tối đa', 'maxResolution': 'Độ phân giải tối đa', 'medium': 'trung bình', 'medium<12cm': 'trung bình <12cm', 'min': 'từ', 'minutes': 'biên bản', 'missing': 'mất tích', 'moderate': 'trung bình', 'module allows the site administrator to configure various options.': 'mô đun cho phép người quản trị trang thông tin cài đặt cấu hình các tùy chọn khác nhau', 'module helps monitoring the status of hospitals.': 'module giúp theo dõi tình trạng bệnh viện', 'multiple hazard crisis, humanitarian crisis, conflict': 'đa hiểm họa, xung đột, khủng hoảng nhân đạo', 'multiplier[0]': 'số nhân[0]', 'natural hazard': 'thảm họa thiên nhiên', 'negroid': 'người da đen', 'never update': 'không bao giờ cập nhật', 'never': 'không bao giờ', 'new ACL': 'ACL mới', 'new': 'thêm mới', 'next 50 rows': '50 dòng tiếp theo', 'no options available': 'không có lựa chọn sẵn có', 'no': 'không', 'none': 'không có', 'normal': 'bình thường', 'not specified': 'không xác định', 'obsolete': 'Đã thôi hoạt động', 'of total data reported': 'của dữ liệu tổng được báo cáo', 'of': 'của', 'offices by organisation': 'văn phòng theo tổ chức', 'on %(date)s': 'vào %(date)s', 'or import from csv file': 'hoặc nhập dữ liệu từ tệp tin csv', 'or': 'hoặc', 'other': 'khác', 'out of': 'ngoài ra', 'over one hour': 'hơn một tiếng', 'overdue': 'quá hạn', 'paid': 'đã nộp', 'per month': 'theo tháng', 'piece': 'chiếc', 'poor': 'nghèo', 'popup_label': 'nhãn_cửa sổ tự động hiển thị', 'previous 50 rows': '50 dòng trước', 'problem connecting to twitter.com - please refresh': 'lỗi kết nối với twitter.com - vui lòng tải lại', 'provides a catalogue of digital media.': 'cung cấp danh mục các phương tiện truyền thông kỹ thuật số', 'pull and push': 'kéo và đẩy', 'pull': 'kéo', 'push': 'đẩy', 'record does not exist': 'Thư mục ghi không tồn tại', 'record id': 'lưu tên truy nhập', 'records deleted': 'hồ sơ đã được xóa', 'red': 'đỏ', 'replace': 'thay thế', 'reports successfully imported.': 'báo cáo đã được nhập khẩu thành công', 'representation of the Polygon/Line.': 'đại diện của Polygon/Line.', 'retry': 'Thử lại', 'risk assessment, loss data, disaster risk management': 'đánh giá rủi ro, dữ liệu thiệt hại, quản lý rủi ro thảm họa', 'risk knowledge, monitoring and warning service, risk communication, response capability, disaster preparedness, risk modelling': 'tăng cường hiểu biết về rủi ro, hoạt động cảnh báo và giám sát, truyền thông về rủi ro, khả năng ứng phó, phòng ngừa thảm họa, lập mô hình ứng phó với rủi ro', 'river': 'sông', 'row.name': 'dòng.tên', 'search': 'tìm kiếm', 'seconds': 'giây', 'see comment': 'xem ghi chú', 'seismic, tectonic': 'địa chấn', 'selected': 'được lựa chọn', 'separated from family': 'Chia tách khỏi gia đình', 'separated': 'ly thân', 'shaved': 'bị cạo sạch', 'short': 'Ngắn', 'short<6cm': 'Ngắn hơn <6cm', 'sides': 'các mặt', 'sign-up now': 'Đăng ký bây giờ', 'simple': 'đơn giản', 'single': 'độc thân', 'slim': 'mỏng', 'straight': 'thẳng hướng', 'strong': 'Mạnh', 'sublayer.name': 'tên.lớp dưới', 'submitted by': 'được gửi bởi', 'suffered financial losses': 'Các mất mát tài chính đã phải chịu', 'sustainable development, environmental degradation, ecosystems and environmental management': 'phát triển bền vững, thoái hóa môi trường, quản lý môi trường và hệ sinh thái', 'table': 'bảng', 'tall': 'cao', 'text': 'từ khóa', 'times (0 = unlimited)': 'thời gian (0 = vô hạn)', 'times and it is still not working. We give in. Sorry.': 'Nhiều lần mà vẫn không có kết quả, thất bại, xin lỗi', 'times': 'thời gian', 'to access the system': 'truy cập vào hệ thống', 'to download a OCR Form.': 'Để tải xuống một mẫu OCR', 'tonsure': 'lễ cạo đầu', 'total': 'tổng', 'training and development, institutional strengthening, institutional learning': 'tập huấn và phát triển, tăng cường thể chế, tăng cường hiểu biết của tổ chức', 'tweepy module not available within the running Python - this needs installing for non-Tropo Twitter support!': 'mô đun tweepy không có trong quá trình chạy Python - cần cài đặt để hỗ trợ Twitter không có Tropo!', 'unapproved': 'chưa được chấp thuận', 'uncheck all': 'bỏ chọn toàn bộ', 'unknown': 'không biết', 'unlimited': 'vô hạn', 'up to 3 locations': 'lên tới 3 địa điểm', 'update if master': 'cập nhật nếu là bản gốc', 'update if newer': 'cập nhật nếu mới hơn', 'update': 'cập nhật', 'updated': 'đã cập nhật', 'urban fire, bush fire, forest fire, uncontrolled fire, wildland fire': 'cháy trong đô thị, cháy rừng, cháy không kiểm soát, cháy vùng đất hoang dã', 'urban planning, urban management': 'quy hoạch đô thị, quản lý đô thị', 'using default': 'sử dụng mặc định', 'waterspout, twister, vortex': 'vòi rồng, gió xoáy, giông lốc', 'wavy': 'dạng sóng', 'weekly': 'hàng tuần', 'weeks': 'tuần', 'white': 'trắng', 'wider area, longer term, usually contain multiple Activities': 'khu vực rộng lớn hơn, dài hạn hơn, thường chứa nhiều Hoạt động', 'widowed': 'góa', 'within human habitat': 'trong khu dân cư', 'yes': 'có', }
sahana/Turkey
languages/vi.py
Python
mit
374,100
[ "VisIt" ]
f9e3cbbbffadd3b37069f9c85d62fd53f1144ca6eb160110462707853edde946
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RAlsace(RPackage): """Alternating Least Squares (or Multivariate Curve Resolution) for analytical chemical data, in particular hyphenated data where the first direction is a retention time axis, and the second a spectral axis. Package builds on the basic als function from the ALS package and adds functionality for high-throughput analysis, including definition of time windows, clustering of profiles, retention time correction, etcetera.""" homepage = "https://www.bioconductor.org/packages/alsace/" url = "https://git.bioconductor.org/packages/alsace" version('1.12.0', git='https://git.bioconductor.org/packages/alsace', commit='1364c65bbff05786d05c02799fd44fd57748fae3') depends_on('r-als', type=('build', 'run')) depends_on('r-ptw', type=('build', 'run'))
lgarren/spack
var/spack/repos/builtin/packages/r-alsace/package.py
Python
lgpl-2.1
2,081
[ "Bioconductor" ]
447dff53da8ba037fbaed5b8c7bc34d904ec281a598456e1f34115b0f4ad44c4
### ############################################################################################################ ### # ### # Project: # teh_tools - by The Highway 2013. ### # Author: # The Highway ### # Version: # (ever changing) ### # Description: # My collection of common tools. ### # ### ############################################################################################################ ### ############################################################################################################ from config import * __plugin__ = ps('__plugin__') __authors__ = ps('__authors__') plugin_id = ps('_addon_id') ### ############################################################################################################ ### ############################################################################################################ import xbmc,xbmcplugin,xbmcgui,xbmcaddon,xbmcvfs try: import requests ### <import addon="script.module.requests" version="1.1.0"/> ### except: t='' ### See https://github.com/kennethreitz/requests ### import urllib,urllib2,re,os,sys,htmllib,string,StringIO,logging,random,array,time,datetime try: import urlresolver except: t='' import copy try: import json except ImportError: import simplejson as json try: import StorageServer except: import storageserverdummy as StorageServer cache = StorageServer.StorageServer(plugin_id) #import SimpleDownloader as downloader from t0mm0.common.net import Net from t0mm0.common.net import Net as net from t0mm0.common.addon import Addon #try: from t0mm0.common.addon import Addon #except: from t0mm0_common_addon import Addon #try: from t0mm0.common.net import Net #except: from t0mm0_common_net import Net #try: from t0mm0.common.net import Net as net #except: from t0mm0_common_net import Net as net net2=Net(); #from config import * ### ############################################################################################################ ### ############################################################################################################ ### ### Common Imports ### ### ###################### ### import shutil, md5, base64, unicodedata, threading, string ### import resources.lib.common as common ### import xbmc, xbmcplugin, xbmcgui, xbmcaddon, xbmcvfs, common ### import os.path, sys, urllib, urllib2, cookielib, string, httplib, socket, random ### import os, re, math, binascii, datetime, HTMLParser ### from BeautifulSoup import BeautifulStoneSoup ### from BeautifulSoup import BeautifulSoup , Tag, NavigableString ### try: from xml.etree import ElementTree ### except: from elementtree import ElementTree ### from xbmcgui import Dialog ### import copy ### requests, httplib, urlparse ### from operator import itemgetter ### from metahandler import metahandlers ### from metahandler import metacontainers ### ### ### ### ### ### ### ### ### ### ############################################################################################################ ### ############################################################################################################ def get_params(): param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2] cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param ### ############################################################################################################ ### ############################################################################################################ cache = StorageServer.StorageServer(plugin_id) addon = Addon(plugin_id, sys.argv) local = xbmcaddon.Addon(id=plugin_id) __settings__ = xbmcaddon.Addon(id=plugin_id) __home__ = __settings__.getAddonInfo('path') addonPath = __settings__.getAddonInfo('path') artPath = addonPath+'/art/' #special://home/addons/plugin.video.theanimehighway/art if __settings__.getSetting("debug-enable") == "true":debugging=True #if (debugging==True): else: debugging=False if __settings__.getSetting("debug-show") == "true": shoDebugging=True #if (showDebugging==True): else: shoDebugging=False _debugging=debugging; _shoDebugging=shoDebugging params=get_params() ICON = os.path.join(__home__, 'icon.png') fanart = os.path.join(__home__, 'fanart.jpg') _addon=Addon(ps('_addon_id'), sys.argv); def addst(r,s=''): return _addon.get_setting(r) ## Get Settings def addpr(r,s=''): return _addon.queries.get(r,s) ## Get Params def cFL(t,c=ps('default_cFL_color')): ### For Coloring Text ### return '[COLOR '+c+']'+t+'[/COLOR]' def cFL_(t,c=ps('default_cFL_color')): ### For Coloring Text ### return '[COLOR '+c+']'+t[0:1]+'[/COLOR]'+t[1:] ### ############################################################################################################ ### ############################################################################################################ url=None; urlbac=None; name=None; name2=None; type2=None; favcmd=None; mode=None; scr=None; imgfan=None; show=None; category=None try: category=urllib.unquote_plus(params["cat"]) except: pass if category==None: category='Base' try: url=urllib.unquote_plus(params["url"]) urlbac=url except: pass try: scr=urllib.unquote_plus(params["scr"]) except: pass try: imgfan=urllib.unquote_plus(params["fan"]) except: pass try: favcmd=urllib.unquote_plus(params["fav"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: name2=urllib.unquote_plus(params["nm"]) except: pass try: show=urllib.unquote_plus(params["show"]) except: pass try: type2=int(params["tp"]) except: pass try: mode=int(params["mode"]) except: pass ### ############################################################################################################ ### ############################################################################################################ ICON8 = os.path.join(artPath, 'icon_watchdub.png');ICON7 = os.path.join(artPath, 'icon_dubhappy.png');ICON6 = os.path.join(artPath, 'iconDAOn2.png');ICON5 = os.path.join(artPath, 'iconA44couk.png');ICON4 = os.path.join(artPath, 'icongd.png');ICON3 = os.path.join(artPath, 'iconAPlus.png');ICON2 = os.path.join(artPath, 'iconA44.png');ICON1 = os.path.join(artPath, 'iconAG.png');ICON0 = os.path.join(__home__, 'icon.png') fanart8 = os.path.join(artPath, 'fanart_watchdub.jpg');fanart7 = os.path.join(artPath, 'fanart_dubhappy.jpg');fanart6 = os.path.join(artPath, 'fanartDAOn2.jpg');fanart5 = os.path.join(artPath, 'fanartA44couk.jpg');fanart4 = os.path.join(artPath, 'fanartgd.jpg');fanart3 = os.path.join(artPath, 'fanartAPlus.jpg');fanart2 = os.path.join(artPath, 'fanartA44.jpg');fanart1 = os.path.join(artPath, 'fanartAG.jpg');fanart0 = os.path.join(__home__, 'fanart.jpg') if type2==8: #site 8 fanart = os.path.join(artPath, 'fanart_watchdub.jpg');ICON = os.path.join(artPath, 'icon_watchdub.png');mainSite='http://www.watchdub.com/' elif type2==7: #site 7 fanart = os.path.join(artPath, 'fanart_dubhappy.jpg');ICON = os.path.join(artPath, 'icon_dubhappy.png');mainSite='http://www.dubhappy.eu/' elif type2==6: #site 6 fanart = os.path.join(artPath, 'fanartDAOn2.jpg');ICON = os.path.join(artPath, 'iconDAOn2.png');mainSite='http://dubbedanimeon.com/' elif type2==5: #site 5 fanart = os.path.join(artPath, 'fanartA44couk.jpg');ICON = os.path.join(artPath, 'iconA44couk.png');mainSite='http://www.anime44.co.uk/' if ('-anime' in url) and ('http://' not in url): url = mainSite + 'subanime/' + url if ('-anime' in url) and ('http://' not in scr) and (artPath not in scr): scr = mainSite + 'subanime/' + scr if ('-anime' in url) and ('http://' not in imgfan) and (artPath not in imgfan): imgfan = mainSite + 'subanime/' + imgfan #if ('-anime' not in url) and ('http://' not in url): url = mainSite + 'english-dubbed/' + url #if ('-anime' not in url) and ('http://' not in scr) and (artPath not in scr): scr = mainSite + 'english-dubbed/' + scr #if ('-anime' not in url) and ('http://' not in imgfan) and (artPath not in imgfan): imgfan = mainSite + 'english-dubbed/' + imgfan #if ('alpha-anime' in url): url.replace('alpha-anime','subanime') #if ('alpha-movies' in url): url.replace('alpha-movies','subanime') #if ('alpha-anime' in show): show.replace('alpha-anime','subanime') #if ('alpha-movies' in show): show.replace('alpha-movies','subanime') elif type2==4: #site 4 fanart = os.path.join(artPath, 'fanartgd.jpg');ICON = os.path.join(artPath, 'icongd.png');mainSite='http://www.gooddrama.net/' elif type2==3: #site 3 fanart = os.path.join(artPath, 'fanartplus.jpg');ICON = os.path.join(artPath, 'iconplus.png');mainSite='http://www.animeplus.tv/' elif type2==2: #site 2 fanart = os.path.join(artPath, 'fanartA44.jpg');ICON = os.path.join(artPath, 'iconA44.png');mainSite='http://www.anime44.com/' else: #site 1 fanart = os.path.join(artPath, 'fanartAG.jpg');ICON = os.path.join(artPath, 'iconAG.png');mainSite='http://www.animeget.com/' ### ############################################################################################################ ### ############################################################################################################ SiteBits=['nosite','animeget.com','anime44.com','animeplus.tv','gooddrama.net','anime44.co.uk','dubbedanimeon.com','dubhappy.eu','watchdub.com'] SiteNames=['nosite','[COLOR blue][COLOR white]Anime[/COLOR]Get[/COLOR]','[COLOR red][COLOR white]Anime[/COLOR]44[/COLOR]','[COLOR darkblue][COLOR white]Anime[/COLOR]Plus[/COLOR]','[COLOR grey]Good[COLOR white]Drama[/COLOR][/COLOR]','[COLOR maroon][COLOR white]Anime[/COLOR]Zone[/COLOR]','[COLOR teal]Dubbed[COLOR white]Anime[/COLOR]On [/COLOR]','[COLOR cornflowerblue][COLOR white]dub[/COLOR]happy[/COLOR]','[COLOR cornflowerblue]Watch[/COLOR][COLOR white]Dub[/COLOR]','',''] SitePrefixes=['nosite','','','','','subanime/','','','','','','','','','','','',''] SiteSufixes= ['nosite','','','','','.html','','','','','','','','','','','','',''] SiteSearchUrls= ['nosite','http://www.animeget.com/search','http://www.anime44.com/anime/search?search_submit=Go&key=','http://www.animeplus.tv/anime/search?search_submit=Go&key=','http://www.gooddrama.net/drama/search?stype=drama&search_submit=Go&key=','No Search Engine for VideoZone','http://dubbedanimeon.com/?s=','','','','','','',''] SiteSearchMethod= ['nosite','post','get','get','get','VideoZone','get','','','','','','',''] Sites=['animeget.com','anime44.com','animeplus.tv','gooddrama.net','anime44.co.uk','dubbedanimeon.com','dubhappy.eu','watchdub.com'] MyAlphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] MyColors=['red','blue','darkblue','grey','maroon','teal','cornflowerblue','cornflowerblue','','','',''] MyBrowser=['User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'] ### ############################################################################################################ MyVideoLinkSrcMatches=['src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"' ,'src="(.+?)"' ,'src="(.+?)"', 'src="(.+?)"'] MyVideoLinkSrcMatchesB=['src="(.+?)"', '<embed.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"' ,'src="(.+?)"' ,'src="(.+?)"', 'src="(.+?)"'] MyVideoLinkBrackets=['<iframe.+?src="(.+?)"', '<embed.+?src="(.+?)"', '<object.+?data="(.+?)"'] MyAlphabet= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] MyBrowser= ['User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'] MySourcesV= ['videoweed.es', 'video44.net', 'novamov.com', 'dailymotion.com', 'videofun.me', 'yourupload.com', 'video.google.com', 'vidzur.com', 'upload2.com','putlocker.com','videoslasher.com','vidbull.com', 'uploadc.com', 'veevr.com', 'rutube.ru'] #MySourcesV= ['videoweed.es', 'video44.net', 'novamov.com', 'dailymotion.com', 'videofun.me', 'yourupload.com', 'video.google.com', 'vidzur.com', 'upload2.com','putlocker.com','videoslasher.com','vidbull.com', 'UploadC', 'veevr.com', 'rutube.ru', 'MP4UPLOAD' ,'AUENGINE'] MyIconsV= [artPath + 'videoweed.jpg', artPath + 'video44a.png', artPath + 'novamov.jpg', artPath + 'dailymotion.jpg', artPath + 'videofun.png', artPath + 'yourupload.jpg', artPath + 'googlevideo.gif', artPath + 'vidzur.png', artPath + 'upload2.png', artPath + 'putlocker.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png']#BLANK.png MyNamesV= ['VideoWeed', 'Video44', 'NovaMov', 'DailyMotion', 'VideoFun', 'YourUpload', 'Google Video', 'VidZur', 'Upload2', 'PutLocker', 'VideoSlasher', 'VidBull', 'UploadC', 'Veevr', 'RuTube', 'MP4Upload' ,'AUEngine'] MyColorsV= ['lime', 'red', 'silver', 'green', 'cyan', 'grey', 'blue', 'orange', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white'] ### ############################################################################################################ ### ############################################################################################################ def getURLr(url,dReferer): try: req = urllib2.Request(url,dReferer) req.add_header(MyBrowser[0], MyBrowser[1]) req.add_header('Referer', dReferer) response = urllib2.urlopen(req) link=response.read() response.close() return(link) except: return('none') def getURL(url): try: req = urllib2.Request(url) req.add_header(MyBrowser[0], MyBrowser[1]) response = urllib2.urlopen(req) link=response.read() response.close() return(link) except: return('none') def postURL(url,postStr): postData=urllib.urlencode(postStr) req = urllib2.Request(url,postData) req.add_header(MyBrowser[0], MyBrowser[1]) response = urllib2.urlopen(req) link=response.read() response.close() return(link) def notification(header="", message="", sleep=5000 ): xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i)" % ( header, message, sleep ) ) #notify(msg=message, title=header, delay=sleep, image=ICON) #notify(msg=message, title='[COLOR green][B]'+header+'[/B][/COLOR]', delay=sleep, image=ICON0) ### ############################################################################################################ ##Example##VaddDir('[COLOR blue]' + text[0] + '[/COLOR]', '', 0, '', False) def addFolder(name,name2,url,type2,mode,iconimage,categoryA='Blank'): ###addDir(name,name2,url,type2,mode,iconimage,fanimage) if ('http://' in iconimage) or (artPath in iconimage): t='' else: iconimage = artPath + iconimage mainSite='http://'+SiteBits[type2]+'/' addDir(name,name2,mainSite + url,type2,mode,iconimage,fanart,categoryA) #addDirD(name,name2,mainSite + url,type2,mode,artPath + iconimage,fanart,'wow') ### from videolinks.py ### #def addFolder(name,name2,url,type2,mode,iconimage): # ##addDir(name,name2,url,type2,mode,iconimage,fanimage) # addDir(name,name2,mainSite + url,type2,mode,artPath + iconimage,fanart) def addDirF(name,name2,url,favcmd,type2=0,mode=0,iconimage=ICON0,fanimage=fanart0,categoryA='Blank'): if (debugging==True): print 'Category: ',category,categoryA categoryA=category+' ::: '+categoryA u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&scr="+urllib.quote_plus(iconimage)+"&fan="+urllib.quote_plus(fanimage)+"&show="+urllib.quote_plus(name2)+"&cat="+categoryA+'&fav='+favcmd ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty( "Fanart_Image", fanimage ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def addDir(name,name2,url,type2,mode,iconimage,fanimage,categoryA='Blank'): if (debugging==True): print 'Category: ',category,categoryA categoryA=category+' ::: '+categoryA u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&scr="+urllib.quote_plus(iconimage)+"&fan="+urllib.quote_plus(fanimage)+"&show="+urllib.quote_plus(name2)+"&cat="+categoryA ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty( "Fanart_Image", fanimage ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def addDirD(name,name2,url,type2,mode,iconimage,fanimage,doSorting=False,categoryA='Blank',Labels='none'):#,plot='Blank',genres='none listed',status='none',released='unknown',rating='none',others='none'): if Labels=='none': Labels={ "Title" : name } if categoryA=='Blank': categoryA=name #if (debugging==True): print 'Category: ',category,categoryA categoryA=category+' ::: '+categoryA u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&scr="+urllib.quote_plus(iconimage)+"&fan="+urllib.quote_plus(fanimage)+"&show="+urllib.quote_plus(name2)+"&cat="+urllib.quote_plus(categoryA) # if (debugging==True): print u vc_tag=visited_DoCheck(u) #if (name=='Maburaho'): visited_add(u) if (debugging==True): print vc_tag # ok=True liz=xbmcgui.ListItem(vc_tag+name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels= Labels ) #"Title": "'" + name + "'", "Plot" : plot, "Genres" : genres } ) liz.setProperty( "Fanart_Image", fanimage ) sysname = urllib.quote_plus(name) sysurl = urllib.quote_plus(url) sysscr = urllib.quote_plus(iconimage) sysfan = urllib.quote_plus(fanimage) #handle adding context menus contextMenuItems = [] if (debugging==True): print getsetbool('enable-showurl') if __settings__.getSetting("enable-showurl") == "true":#doesn't work for some odd reason >> #if getsetbool('enable-showurl') == 'true':# contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'showurl', sysurl, sysscr, sysfan))) contextMenuItems.append(('[B][COLOR green]ADD[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'add', sysurl, sysscr, sysfan,urllib.quote_plus(name2)))) contextMenuItems.append(('[B][COLOR red]REMOVE[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'rem', sysurl, sysscr, sysfan,urllib.quote_plus(name2)))) contextMenuItems.append(('Show Information', 'XBMC.Action(Info)')) # #contextMenuItems.append(('[B][COLOR orange]Test[/COLOR][/B] ~ [B]Test[/B]',"notification(%s,%s)" % (sysname,sysurl))) if (debugging==True): print getset('enable-clearfavorites') if __settings__.getSetting("enable-clearfavorites") == "true":#if getset('enable-clearfavorites')==True: contextMenuItems.append(('[B][COLOR yellow]Clear[/COLOR][/B] ~ [B][COLOR tan]Favorites[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'clr', sysurl, sysscr, sysfan))) liz.addContextMenuItems(contextMenuItems, replaceItems=False)#True#liz.addContextMenuItems(contextMenuItems) if doSorting==True: xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def addDirV(name,name2,url,type2,mode,iconimage,fanimage,categoryA=''): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&cat="+categoryA ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty( "Fanart_Image", fanimage ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok #def VaddDir(name, url, mode, iconimage, fanimage, is_folder=False,categoryA=''):#VANILLA ADDDIR (kept for reference) # u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&cat="+categoryA # ok=True # liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) # liz.setInfo( type="Video", infoLabels={ "Title": name } ) # liz.setProperty( "Fanart_Image", fanimage ) # ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=is_folder) # return ok def VaddDir(name, url, mode, iconimage, fanimage, is_folder=False,categoryA=''):#VANILLA ADDDIR (kept for reference) u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&cat="+categoryA #if (debugging==True): print u ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty( "Fanart_Image", fanimage ) contextMenuItems = [] if __settings__.getSetting("enable-showurl") == "true": contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , urllib.quote_plus(name), urllib.quote_plus(name), 877, 'showurl', urllib.quote_plus(url), urllib.quote_plus(iconimage), urllib.quote_plus(fanimage)))) liz.addContextMenuItems(contextMenuItems, replaceItems=True)#True#liz.addContextMenuItems(contextMenuItems) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=is_folder) return ok ### from theanimehighway.py ### #def addLink(name,url,iconimage): # ok=True # liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage) # liz.setInfo( type="Video", infoLabels={ "Title": name } ) # ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) # return ok def addLink(name,url,iconimage=ICON,fanimage=fanart,shoname='none',downloadable=True): ok=True if shoname=='none': try: shoname=show except: shoname=name if fanimage==fanart: try: fanimage=imgfan except: pass if iconimage in MyIconsV: try: iconimage=scr except: pass # #liz=xbmcgui.ListItem(name, iconImage=artPath+"blank.gif", thumbnailImage=iconimage) liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage) ##if (debugging==True): print 'sitename name: '+SiteNames[type2] + name ##liz.setInfo( type="Video", infoLabels={ "Title": name } ) Studio=name if (' - [COLOR grey]' in Studio): Studio = Studio.split(' - [COLOR grey]')[0] if (' [COLOR grey]- ' in Studio): Studio = Studio.split(' [COLOR grey]- ')[0] if ('[COLOR grey] - ' in Studio): Studio = Studio.split('[COLOR grey] - ')[0] if (' - [COLOR' in Studio): Studio = Studio.split(' - [COLOR')[0] showtitle=shoname if (' [COLOR lime](English Dubbed)[/COLOR]' in showtitle): Studio += ' [COLOR lime](English Dubbed)[/COLOR]' showtitle = showtitle.replace(' [COLOR lime](English Dubbed)[/COLOR]','') elif ('English Dubbed' in showtitle): Studio += ' [COLOR lime](English Dubbed)[/COLOR]' elif ('Eng Dubbed' in showtitle): Studio += ' [COLOR lime](English Dubbed)[/COLOR]' elif ('Dubbed' in showtitle): Studio += ' [COLOR lime](Dubbed)[/COLOR]' elif ('English Subbed' in showtitle): Studio += ' [COLOR lime](English Subbed)[/COLOR]' elif ('Eng Subbed' in showtitle): Studio += ' [COLOR lime](English Subbed)[/COLOR]' elif ('Subbed' in showtitle): Studio += ' [COLOR lime](Subbed)[/COLOR]' liz.setInfo( type="Video", infoLabels={ "Title": showtitle, "Studio": Studio } ) #liz.setProperty( "Fanart_Image", fanimage ) contextMenuItems = [] if (debugging==True): print getset('enable-showurl') if __settings__.getSetting("enable-showurl") == "true":#if getset('enable-showurl')=='true': contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(shoname), urllib.quote_plus(shoname), 0, 'showurl', urllib.quote_plus(url), iconimage, fanimage))) if (__settings__.getSetting("enable-downloading") == "true") and (downloadable == True):#if getset('enable-downloading',True)=='True': #if ('videofun.me' not in url) and ('videoweed.es' not in url) and ('dailymotion.com' not in url): if ('novamov.com' not in url) and ('videoweed.es' not in url) and ('dailymotion.com' not in url): contextMenuItems.append(('[B][COLOR purple]Download[/COLOR][/B] ~ [B]File[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(shoname), urllib.quote_plus(shoname), 0, 'download', urllib.quote_plus(url), iconimage, fanimage))) liz.addContextMenuItems(contextMenuItems, replaceItems=True)#True#liz.addContextMenuItems(contextMenuItems) ##liz.addContextMenuItems([('[B][COLOR green]D[/COLOR][/B][B]ownload[/B]',"downloadfile(url,name)")]) #liz.addContextMenuItems([('[B][COLOR green]D[/COLOR][/B][B]ownload[/B]',"XBMC.RunPlugin(%s?mode=%s&name=%s&url=%s)"%(sys.argv[0],999,name,url))]) ##xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) return ok ### ############################################################################################################ def getset(idSetting):#,defaultValue=''):#Addon.getSetting('idNameOfSetting') return __settings__.getSetting(idSetting)#==defaultValue def getsetbool(idSetting):#Addon.getSetting('idNameOfSetting') #Method seems to be an utter failure for BOOL(true/false)'s #if (debugging==True): print __settings__.getSetting(idSetting) == 'true' return __settings__.getSetting(idSetting) == 'true' def getsetbool_(idSetting):#Addon.getSetting('idNameOfSetting') #Method seems to be an utter failure for BOOL(true/false)'s #if (debugging==True): print __settings__.getSetting(idSetting) == 'true' #try: tst=__settings__.getSetting(idSetting) == 'true' try: tst=__settings__.getSetting(idSetting) except: tst='False' if (tst=='true') or (tst=='True') or (tst=='TRUE'): return True else: return False #return __settings__.getSetting(idSetting) == 'true' ### ############################################################################################################ def download_it_now(url,name):## mode=1901 ## name=name.strip() if ('[/COLOR]' in name): name=name.replace('[/COLOR]','') if ('[COLOR lime]' in name): name=name.replace('[COLOR lime]','') if ('[/color]' in name): name=name.replace('[/color]','') if ('[color lime]' in name): name=name.replace('[color lime]','') #if ('' in name): name=name.replace('','') #if ('' in name): name=name.replace('','') #if ('' in name): name=name.replace('','') notification(name,'Attempting Download...') download_file_prep(url,name,name,name) ## Example of how to connect to this addon's download feature from another plugin: ## #### xbmc.executebuiltin('XBMC.RunPlugin(%s?mode=1901&url=%s&name=%s)' % ('plugin://plugin.video.theanimehighway/', urllib.quote_plus(stream_url), urllib.quote_plus(title))) #### Simply make sure to include the quoted name and url for this function to work. #### File must be for a downloadable file or video stream, not for a page with a video on it. def download_metapack(url, dest, displayname=False): print 'Downloading Metapack' print 'URL: %s' % url print 'Destination: %s' % dest if not displayname: displayname = url dlg = xbmcgui.DialogProgress() dlg.create('Downloading', '', displayname) start_time = time.time() if os.path.isfile(dest): print 'File to be downloaded already esists' return True try: urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dlg, start_time)) except: #only handle StopDownloading (from cancel), #ContentTooShort (from urlretrieve), and OS (from the race condition); #let other exceptions bubble if sys.exc_info()[0] in (urllib.ContentTooShortError, StopDownloading, OSError): return False else: raise return True ### ### Dialog DialogBusy DialogButton Menu DialogContentSettings DialogContentMenu DialogExtendedProgressBar ### DialogFavourites DialogKaiToast DialogKeyboard DialogOK DialogProgress DialogVolumeBar DialogVideoScan ### DialogVideoInfo DialogTextViewer DialogSlider DialogSelect DialogSeekBar DialogYesNo ### def download_file(url='',name='temp',localfilename='temp',localpath=artPath,filext='.flv'): t='' ###url='https://github.com/HIGHWAY99/plugin.video.theanimehighway/archive/master.zip' ###localfilename='plugin.video.theanimehighway.zip' ###localpath=__home__ #localfilewithpath=os.path.join(localpath,localfilename) #if (debugging==True): print 'Attempting to download "' + localfilename + '" to "' + localfilewithpath + '" from: ' + url ###dialogbox('To: ' + localfilewithpath,'Download File: ' + localfilename,'From: ' + url,'[COLOR red]This is still being tested.[/COLOR]') #if os.path.isfile(localfilewithpath): # if (debugging==True): print 'File to be downloaded already esists.' # notification('Download: '+localfilename,'File already exists.')#This function may never happen. # return #dialog = xbmcgui.Dialog() #if dialog.yesno('Download File', 'Do you wish to download this file?','File: ' + localfilename,'To: ' + localpath): # notification('Attempting to Download File',localfilename + '[CR] This function is still being tested.')#This function may never happen. # try: dp = xbmcgui.DialogProgressBG() ## Only works on daily build of XBMC. # except: dp = xbmcgui.DialogProgress() # dp.create('Downloading', '', localfilename) # #### # ####urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhookb(nb, bs, fs, dlg, start_time)) # #### # urllib.urlretrieve(url, localfilewithpath, lambda nb, bs, fs: _pbhookb(nb, bs, fs, dlg, start_time)) # #urllib.urlretrieve(url, localfilewithpath) # notification('Download File','Download Complete.[CR] ' + localfilename,15000) # dialogbox_ok('File Size: ' + str(os.path.getsize(localfilewithpath)) + ' (bytes)','Download Complete','Note:','Make sure the size seems right.') # ###total_size += os.path.getsize(fp) ### ### ###notification('Download File','Sorry this feature is not yet implimented.')#This function may never happen. def _pbhookb(numblocks, blocksize, filesize, dlg, start_time): try: percent = min(numblocks * blocksize * 100 / filesize, 100) currently_downloaded = float(numblocks) * blocksize / (1024 * 1024) kbps_speed = numblocks * blocksize / (time.time() - start_time) if kbps_speed > 0: eta = (filesize - numblocks * blocksize) / kbps_speed else: eta = 0 kbps_speed /= 1024 total = float(filesize) / (1024 * 1024) mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total) est = 'Speed: %.02f Kb/s ' % kbps_speed est += 'ETA: %02d:%02d' % divmod(eta, 60) dlg.update(percent, mbs, est) except: percent = 100 dlg.update(percent) #if dlg.iscanceled(): ## used for xbmcgui.DialogProgress() but causes an error with xbmcgui.DialogProgressBG() # dlg.close() # raise StopDownloading('Stopped Downloading') def download_file_frodo(url='',name='temp',localfilename='temp',localpath=artPath,filext='.flv'): localfilewithpath=os.path.join(localpath,localfilename) if (debugging==True): print 'Attempting to download "' + localfilename + '" to "' + localfilewithpath + '" from: ' + url #dialogbox('To: ' + localfilewithpath,'Download File: ' + localfilename,'From: ' + url,'[COLOR red]This is still being tested.[/COLOR]') if os.path.isfile(localfilewithpath): if (debugging==True): print 'File to be downloaded already esists.' notification('Download: '+localfilename,'File already exists.')#This function may never happen. return dialog = xbmcgui.Dialog() if dialog.yesno('Download File', 'Do you wish to download this file?','File: ' + localfilename,'To: ' + localpath): notification('Attempting to Download File',localfilename + '[CR] This function is still being tested.')#This function may never happen. dp = xbmcgui.DialogProgress() dp.create('Downloading', '', localfilename) start_time = time.time() urllib.urlretrieve(url, localfilewithpath, lambda nb, bs, fs: _pbhookb_frodo(nb, bs, fs, dp, start_time)) #urllib.urlretrieve(url, localfilewithpath) ##urllib.urlretrieve(url, localfilewithpath, lambda nb, bs, fs: _pbhookb_frodo(nb, bs, fs, dlg, start_time)) #urllib.urlretrieve(url, localfilewithpath) notification('Download File','Download Complete.[CR] ' + localfilename,15000) dialogbox_ok('File Size: ' + str(os.path.getsize(localfilewithpath)) + ' (bytes)','Download Complete','Note:','Make sure the size seems right.') #total_size += os.path.getsize(fp) #notification('Download File','Sorry this feature is not yet implimented.')#This function may never happen. def _pbhookb_frodo(numblocks, blocksize, filesize, dlg, start_time): try: percent = min(numblocks * blocksize * 100 / filesize, 100) currently_downloaded = float(numblocks) * blocksize / (1024 * 1024) kbps_speed = numblocks * blocksize / (time.time() - start_time) if kbps_speed > 0: eta = (filesize - numblocks * blocksize) / kbps_speed else: eta = 0 kbps_speed /= 1024 total = float(filesize) / (1024 * 1024) mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total) est = 'Speed: %.02f Kb/s ' % kbps_speed est += 'ETA: %02d:%02d' % divmod(eta, 60) dlg.update(percent, mbs, est) except: percent = 100 dlg.update(percent) if dlg.iscanceled(): ## used for xbmcgui.DialogProgress() but causes an error with xbmcgui.DialogProgressBG() dlg.close() raise StopDownloading('Stopped Downloading') def filename_filter_out_year(name=''): years=re.compile(' \((\d+)\)').findall('__'+name+'__') for year in years: name=name.replace(' ('+year+')','') name=name.strip() return name def filename_filter_colorcodes(name=''): if ('[/color]' in name): name=name.replace('[/color]','') if ('[/COLOR]' in name): name=name.replace('[/COLOR]','') if ('[color lime]' in name): name=name.replace('[color lime]','') if ('[COLOR lime]' in name): name=name.replace('[COLOR lime]','') if ('[COLOR green]' in name): name=name.replace('[COLOR green]','') if ('[COLOR yellow]' in name): name=name.replace('[COLOR yellow]','') if ('[COLOR red]' in name): name=name.replace('[COLOR red]','') if ('[b]' in name): name=name.replace('[b]','') if ('[B]' in name): name=name.replace('[B]','') if ('[/b]' in name): name=name.replace('[/b]','') if ('[/B]' in name): name=name.replace('[/B]','') if ('[cr]' in name): name=name.replace('[cr]','') if ('[CR]' in name): name=name.replace('[CR]','') if ('[i]' in name): name=name.replace('[i]','') if ('[I]' in name): name=name.replace('[I]','') if ('[/i]' in name): name=name.replace('[/i]','') if ('[/I]' in name): name=name.replace('[/I]','') if ('[uppercase]' in name): name=name.replace('[uppercase]','') if ('[UPPERCASE]' in name): name=name.replace('[UPPERCASE]','') if ('[lowercase]' in name): name=name.replace('[lowercase]','') if ('[LOWERCASE]' in name): name=name.replace('[LOWERCASE]','') name=name.strip() #if ('' in name): name=name.replace('','') #if ('' in name): name=name.replace('','') #if ('' in name): name=name.replace('','') return name def Download_PrepExt(url,ext='.flv'): if '.zip' in url: ext='.zip' #Compressed Files elif '.rar' in url: ext='.rar' elif '.z7' in url: ext='.z7' elif '.png' in url: ext='.png' #images elif '.jpg' in url: ext='.jpg' elif '.gif' in url: ext='.gif' elif '.bmp' in url: ext='.bmp' elif '.jpeg' in url: ext='.jpeg' elif '.mp4' in url: ext='.mp4' #Videos elif '.mpeg' in url: ext='.mpeg' elif '.avi' in url: ext='.avi' elif '.flv' in url: ext='.flv' elif '.wmv' in url: ext='.wmv' elif '.mp3' in url: ext='.mp3' #others elif '.txt' in url: ext='.txt' #else: ext='.flv' #Default File Extention ('.flv') return ext def download_file_prep(url,name='none',name2='none',show='none',filext='none'): # if filext=='none': if '.zip' in url: filext='.zip' #Compressed Files elif '.rar' in url: filext='.rar' elif '.z7' in url: filext='.z7' elif '.png' in url: filext='.png' #images elif '.jpg' in url: filext='.jpg' elif '.gif' in url: filext='.gif' elif '.mp4' in url: filext='.mp4' #Videos elif '.mpeg' in url: filext='.mpeg' elif '.avi' in url: filext='.avi' elif '.flv' in url: filext='.flv' elif '.wmv' in url: filext='.wmv' elif '.mp3' in url: filext='.mp3' #others elif '.txt' in url: filext='.txt' else: filext='.flv' #Default File Extention ('.flv') try: name=filename_filter_colorcodes(name) except: name='' try: name2=filename_filter_colorcodes(name2) except: name2=name try: show=filename_filter_colorcodes(show) except: show=name filname = name + filext dialog = xbmcgui.Dialog() if dialog.yesno('Local Path', 'Where would you like to download to?', '', filname, 'Shows', 'Movies'): localpath = getset('folder-movie')#__settings__.getSetting('folder-movie') else: localpath = getset('folder-show')#__settings__.getSetting('folder-show') if (debugging==True): print localpath #download_file(url,name,filname,localpath) ## For nightly builds 13.x+ download_file_frodo(url,name,filname,localpath) ## For Frodo builds 12.x # #def downloadfile(url,name): # import SimpleDownloader as downloader # downloader = downloader.SimpleDownloader() # url='http://www.xbmcswift.com/en/develop/api.html' # dlfold='/tmp' # #dlfold='F:\\xbmc\\theanimehighway\\' # params = { "url": url, "download_path": dlfold, "Title": name } # #params = { "url": url, "download_path": "F:\\xbmc\\theanimehighway\\", "Title": name, "live": "true", "duration": "20" } # filenm = name + ".txt" # #filenm = name + ".mp4" # notification('file download: ' + name, 'Downloading "' + url + '" to "' + filenm + '"') # downloader.download(filenm, params) ### ############################################################################################################ #def dialogboxyesno(txtMessage="",txtHeader="",txt3="",txt4=""): # dialog = xbmcgui.Dialog() # if dialog.yesno(txtHeader, txtMessage, txt3, txt4): def dialogbox_ok(txtMessage="",txtHeader="",txt3="",txt4=""): dialog = xbmcgui.Dialog() ok = dialog.ok(txtHeader, txtMessage, txt3, txt4) #keyboard = xbmc.Keyboard(txtMessage, txtHeader, passwordField)#("text to show","header text", True="password field"/False="show text") #import win64clipboard as wc def copy_to_clipboard(msg): notification('Copy-to-Clipboard','Sorry this feature is not yet implimented.') # # #if sys.platform == 'win32': # wc.OpenClipboard() # wc.EmptyClipboard() # wc.SetClipboardData(win32con.CF_TEXT, msg) # wc.CloseClipboard() # # def showkeyboard(txtMessage="",txtHeader="",passwordField=False): if txtMessage=='None': txtMessage='' keyboard = xbmc.Keyboard(txtMessage, txtHeader, passwordField)#("text to show","header text", True="password field"/False="show text") keyboard.doModal() if keyboard.isConfirmed(): return keyboard.getText() else: return False # return '' def dialogbox_number(Header="",n='',type=0): #Types: #0 : ShowAndGetNumber #1 : ShowAndGetDate #2 : ShowAndGetTime #3 : ShowAndGetIPAddress dialog = xbmcgui.Dialog() dlg=xbmcgui.Dialog() if (n==''): r=dlg.numeric(1,Header) else: r=dlg.numeric(1,Header,n) return r ### ############################################################################################################ def checkForPartNo(url,partInfo=''): url=urllib.unquote_plus(url) if '_part_' in urllib.unquote_plus(url): try: matchaptn=re.compile('_part_(.+?).').findall(url) partInfo=' - Part # ' + matchaptn[0] except: partInfo=' - Part # ' + 'Unknown' elif '-part-' in urllib.unquote_plus(url): try: matchaptn=re.compile('-part-(.+?).').findall(url) partInfo=' - Part # ' + matchaptn[0] except: partInfo=' - Part # ' + 'Unknown' elif 'part' in urllib.unquote_plus(url): try: matchaptn=re.compile('part(.+?).').findall(url) partInfo=' - Part # ' + matchaptn[0] except: temp='' return partInfo ### ############################################################################################################ def aSortMeth(sM,h=int(sys.argv[1])): xbmcplugin.addSortMethod(handle=h, sortMethod=sM) def set_view(content='none',view_mode=50,do_sort=False): if (debugging==True): print 'content type: ',content if (debugging==True): print 'view mode: ',view_mode h=int(sys.argv[1]) #try: h=int(sys.argv[1]) #except: h=_addon.handle if (content is not 'none'): xbmcplugin.setContent(h, content) #types: # set_view() # 50 CommonRootView # 51 FullWidthList # 500 ThumbnailView # 501 PosterWrapView # 508 PosterWrapView2_Fanart # 505 WideIconView # # # set content type so library shows more views and info if (tfalse(addst("auto-view"))==True): xbmc.executebuiltin("Container.SetViewMode(%s)" % view_mode) # set sort methods - probably we don't need all of them #aSortMeth(xbmcplugin.SORT_METHOD_NONE) aSortMeth(xbmcplugin.SORT_METHOD_UNSORTED) aSortMeth(xbmcplugin.SORT_METHOD_TITLE) aSortMeth(xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE) aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_TITLE) aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE) aSortMeth(xbmcplugin.SORT_METHOD_LABEL) aSortMeth(xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE) aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RATING) aSortMeth(xbmcplugin.SORT_METHOD_DATE) aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_YEAR) #aSortMeth(xbmcplugin.SORT_METHOD_PROGRAM_COUNT) aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RUNTIME) aSortMeth(xbmcplugin.SORT_METHOD_GENRE) # aSortMeth(xbmcplugin.SORT_METHOD_FILE) #aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RUNTIME) #aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RATING) #aSortMeth(xbmcplugin.SORT_METHOD_STUDIO) #aSortMeth(xbmcplugin.SORT_METHOD_STUDIO_IGNORE_THE) #aSortMeth(xbmcplugin.SORT_METHOD_PLAYLIST_ORDER) aSortMeth(xbmcplugin.SORT_METHOD_EPISODE) aSortMeth(xbmcplugin.SORT_METHOD_DURATION) #aSortMeth(xbmcplugin.SORT_METHOD_BITRATE) # if (do_sort == True): #aSortMeth(h, xbmcplugin.SORT_METHOD_TITLE)#xbmcplugin.SORT_METHOD_LABEL xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_TITLE)#xbmcplugin.SORT_METHOD_LABEL # ####xbmcplugin.addSortMethod(handle=h, sortMethod=xbmcplugin.SORT_METHOD_TRACKNUM) # #SORT_METHOD_NONE, SORT_METHOD_UNSORTED, SORT_METHOD_VIDEO_TITLE, # # SORT_METHOD_TRACKNUM, SORT_METHOD_FILE, SORT_METHOD_TITLE # # SORT_METHOD_TITLE_IGNORE_THE, SORT_METHOD_LABEL # # SORT_METHOD_LABEL_IGNORE_THE, SORT_METHOD_VIDEO_SORT_TITLE, # # SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE ### ############################################################################################################ ### from theanimehighway.py ### #def showurl(name,url,scr=ICON0,imgfan=fanart0,type2=0,mode=0): # copy_to_clipboard(url) # if (debugging==True): print url, name, scr, imgfan # kmsg=showkeyboard(url, name) def showurl(name,url,scr=ICON,imgfan=fanart,type2=0,mode=0): copy_to_clipboard(url) if (debugging==True): print url, name, scr, imgfan kmsg=showkeyboard(url, name) ### ############################################################################################################ def metaArt_empty(): saved_fans = cache.get('MetaArt_') fans = [] cache.set('MetaArt_', str(fans)) notification('[B][COLOR orange]Fanart[/COLOR][/B]','[B] Your Cached Fanart(s) Have Been Wiped Clean. Bye Bye.[/B]') def emptyFavorites(): saved_favs = cache.get('favourites_') favs = [] cache.set('favourites_', str(favs)) notification('[B][COLOR orange]Favorites[/COLOR][/B]','[B] Your Favorites Have Been Wiped Clean. Bye Bye.[/B]') def addfavorite(name,url,scr=ICON0,imgfan=fanart0,tp2=0,mode=0): if (debugging==True): print name,url,scr,imgfan,tp2,mode saved_favs = cache.get('favourites_') favs = [] if saved_favs: favs = eval(saved_favs) if favs: if (name,url,scr,imgfan,tp2,mode) in favs: notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Already in your Favorites[/B]') #xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Already in your Favourites[/B],5000,"")") return favs.append((name,url,scr,imgfan,tp2,mode)) cache.set('favourites_', str(favs)) notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Added to Favorites[/B]') #xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Added to Favourites[/B],5000,"")") def removefavorite(name,url,scr=ICON0,imgfan=fanart0,tp2=0,mode=0):#,scr,imgfan if (debugging==True): print name,url,scr,imgfan,tp2,mode saved_favs = cache.get('favourites_') if saved_favs: favs = eval(saved_favs) if (name,url,scr,imgfan,tp2,mode) in favs: favs.remove((name,url,scr,imgfan,tp2,mode)) cache.set('favourites_', str(favs)) notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Removed from Favorites[/B]') if (debugging==True): print name+' Removed from Favorites.' #set_view('tvshows',int(getset('viewmode-favs')),True) #VaddDir('[COLOR maroon] Visit with [COLOR tan]Highway[/COLOR] and others @ [COLOR white]#XBMCHUB[/COLOR] on [COLOR white]irc.freenode.net[/COLOR]:6667 [/COLOR]', '', 0, ICON, fanart, False) #LastPage=page_last_update() #xbmc.executebuiltin("XBMC.Container.Update(%s)" % (LastPage)) xbmc.executebuiltin("XBMC.Container.Refresh") #VaddDir('[COLOR maroon] Visit with [COLOR tan]Highway[/COLOR] and others @ [COLOR white]#XBMCHUB[/COLOR] on [COLOR white]irc.freenode.net[/COLOR]:6667 [/COLOR]', '', 0, ICON, fanart, False) ##xbmc.Container.Refresh #xbmc.sleep(4000) elif ((name) in favs): favs.remove((name)) cache.set('favourites_', str(favs)) notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Removed from Favorites[/B]') if (debugging==True): print name+' Removed from Favorites. (Hopefully)' xbmc.executebuiltin("XBMC.Container.Refresh") elif favs: tf=False for (_name,_url,_scr,_imgfan,_tp2,_mode) in favs: if (name==_name): favs.remove((name,_url,_scr,_imgfan,_tp2,_mode)) cache.set('favourites_', str(favs)) notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Removed from Favorites[/B]') if (debugging==True): print name+' Removed from Favorites. (Hopefully)' tf=True xbmc.executebuiltin("XBMC.Container.Refresh") return if (tf==False): notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] not found in your Favorites[/B]') else: notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] not found in your Favorites[/B]') #xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Removed from Favourites[/B],5000,"")") def metaArt_add(show_name,show_title_thetvdb,show_id,url_thetvdb,show_fanart,show_poster,show_bannner,show_desc,show_genres,show_status,show_language,show_network,show_rating):#metaArt_add(match_showname,match_showid,match_thetvdb_url,match_fanart,match_poster,match_banner) ##if (debugging==True): print name,url,scr,imgfan,tp2,mode saved_fans = cache.get('MetaArt_') fans = [] if saved_fans: fans = eval(saved_fans) if fans: if (show_name,show_id,url_thetvdb,show_fanart,show_poster,show_bannner,show_desc) in fans: #notification('[B][COLOR orange]'+show_name.upper()+'[/COLOR][/B]','[B] Already in your Cached Fanart(s).[/B]') return fans.append((show_name,show_title_thetvdb,show_id,url_thetvdb,show_fanart,show_poster,show_bannner,show_desc,show_genres,show_status,show_language,show_network,show_rating)) cache.set('MetaArt_', str(fans)) #notification('[B][COLOR orange]'+show_name.upper()+'[/COLOR][/B]','[B] Added to MetaArt[/B]') ##xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Added to Favourites[/B],5000,"")") ### ############################################################################################################ def getAlphaFolder(alphaTxt='',typeTxt='',slashTxt=''): if type2==5: return 'subanime/' #elif mode==211: return 'alpha-anime/' #elif mode==311: return 'alpha-movies/' else: return alphaTxt+typeTxt+slashTxt def getAlphaEnd(typeTxt='',alphaTxt=''): if (type2==5) and (typeTxt=='anime'): return '-2' elif (type2==5) and (typeTxt=='movies'): return '-3' else: return alphaTxt def showlistdir(vLetterA,vLetterB,vImageC):#SitePrefixes#SiteSufixes addFolder('[COLOR ' + MyColors[1] + ']' + vLetterB + '[/COLOR]','shows',getAlphaFolder('alpha-','anime','/') + vLetterA + getAlphaEnd('anime') + SiteSufixes[type2],type2,6,'Glossy_Black\\' + vImageC + '.png') def movielistdir(vLetterA,vLetterB,vImageC): addFolder('[COLOR ' + MyColors[1] + ']' + vLetterB + '[/COLOR]','movies',getAlphaFolder('alpha-','movies','/') + vLetterA + getAlphaEnd('movies') + SiteSufixes[type2],type2,6,'Glossy_Black\\' + vImageC + '.png') ### ############################################################################################################ def clean_filename(filename): # filename = _1CH.unescape(filename) return re.sub('[/:"*?<>|]+', ' ', filename) def ParseDescription(plot): ## Cleans up the dumb number stuff thats ugly. if ("&amp;" in plot): plot=plot.replace('&amp;' ,'&')#&amp;#x27; if ("&nbsp;" in plot): plot=plot.replace('&nbsp;' ," ") #if (chr(226) in plot): plot=plot.replace(chr(226),"'") if ('&#' in plot) and (';' in plot): if ("&#8211;" in plot): plot=plot.replace("&#8211;",";") #unknown if ("&#8216;" in plot): plot=plot.replace("&#8216;","'") if ("&#8217;" in plot): plot=plot.replace("&#8217;","'") if ("&#8220;" in plot): plot=plot.replace('&#8220;','"') if ("&#8221;" in plot): plot=plot.replace('&#8221;','"') if ("&#215;" in plot): plot=plot.replace('&#215;' ,'x') if ("&#x27;" in plot): plot=plot.replace('&#x27;' ,"'") if ("&#xF4;" in plot): plot=plot.replace('&#xF4;' ,"o") if ("&#xb7;" in plot): plot=plot.replace('&#xb7;' ,"-") if ("&#xFB;" in plot): plot=plot.replace('&#xFB;' ,"u") if ("&#xE0;" in plot): plot=plot.replace('&#xE0;' ,"a") if ("&#0421;" in plot): plot=plot.replace('&#0421;',"") if ("&#xE9;" in plot): plot=plot.replace('&#xE9;' ,"e") if ("&#xE2;" in plot): plot=plot.replace('&#xE2;' ,"a") #if ("&#2019;" in plot): plot=plot.replace('&#2019;',"") if ('&#' in plot) and (';' in plot): try: matches=re.compile('&#(.+?);').findall(plot) except: matches='' if (matches is not ''): for match in matches: if (match is not '') and (match is not ' ') and ("&#"+match+";" in plot): plot=plot.replace("&#"+match+";" ,"") #if ("\xb7" in plot): plot=plot.replace('\xb7' ,"-") #if ('&#' in plot) and (';' in plot): plot=unescape_(plot) for i in xrange(127,256): try: plot=plot.replace(chr(i),"") except: plot=plot return plot def unescape_(s): p = htmllib.HTMLParser(None) p.save_bgn() p.feed(s) return p.save_end() def check_ifUrl_isHTML(pathUrl): ## Doesn't work yet. Needs Fixed. ######## 'http://s12.trollvid.net/videos/'+testString+'/'+vid_id1+'.mp4' ##timeout=10 ##socket.setdefaulttimeout(timeout) # timeout in seconds if (debugging==True): print 'TestingUrl: '+pathUrl try: req=urllib2.Request(pathUrl)#,timeout=6) tUrl=urllib2.urlopen(req) return True except: return False ### ############################################################################################################ def visited_DoCheck(urlToCheck,s='[B][COLOR yellowgreen]@[/COLOR][/B] ',e='[COLOR black]@[/COLOR] '): #visited_empty() #return '' vc=visited_check(urlToCheck) if (vc==True): return s else: ##visited_add(urlToCheck) return e def visited_check(urlToCheck): try: saved_visits = cache.get('visited_') except: return False erNoFavs='XBMC.Notification([B][COLOR orange]Favorites[/COLOR][/B],[B]You have no favorites saved.[/B],5000,"")' if not saved_visits: return False #xbmc.executebuiltin(erNoFavs) if saved_visits == '[]': return False #xbmc.executebuiltin(erNoFavs) if saved_visits: visits = eval(saved_visits) if (urlToCheck in visits): return True return False def visited_empty(): saved_favs = cache.get('visited_') favs = [] cache.set('visited_', str(favs)) notification('[B][COLOR orange]Visited[/COLOR][/B]','[B] Your Visited Data has been wiped clean. Bye Bye.[/B]') def visited_add(urlToAdd): if (urlToAdd==''): return '' elif (urlToAdd==None): return '' if (debugging==True): print 'checking rather url has been visited: ' + urlToAdd saved_visits = cache.get('visited_') visits = [] if saved_visits: #if (debugging==True): print 'saved visits: ',saved_visits visits = eval(saved_visits) if visits: if (urlToAdd) in visits: return visits.append((urlToAdd)) cache.set('visited_', str(visits)) def qp_get(n): ## Deals with errors in using None type within a urllib.quote_plus(). #print n if (n==''): return '' elif (n==None): return '' else: return urllib.quote_plus(n) def st_get(n): ## Deals with errors in using None type within a str(). #print n if (n==None): return '' else: return str(n) def page_last_get(defaultLastPage=sys.argv[0]+'?mode=0'): try: last_visited = cache.get('lastpage') except: return defaultLastPage erNoFavs='XBMC.Notification([B][COLOR orange]Favorites[/COLOR][/B],[B]You have no favorites saved.[/B],5000,"")' if not last_visited: return defaultLastPage if last_visited == '[]': return defaultLastPage if last_visited == '': return defaultLastPage if last_visited: return eval(last_visited) return defaultLastPage def page_last_update(defaultLastPage=sys.argv[0]+sys.argv[2]): cache.set('lastpage', defaultLastPage) def format_eta(seconds): minutes, seconds = divmod(seconds, 60) if minutes > 60: hours, minutes = divmod(minutes, 60) return "ETA: %02d:%02d:%02d " % (hours, minutes, seconds) else: return "ETA: %02d:%02d " % (minutes, seconds) def format_time(seconds): minutes, seconds = divmod(seconds, 60) if minutes > 60: hours, minutes = divmod(minutes, 60) return "%02d:%02d:%02d" % (hours, minutes, seconds) else: return "%02d:%02d" % (minutes, seconds) ### ############################################################################################################ ### ############################################################################################################ class TextBox_FromFile: # constants WINDOW = 10147 CONTROL_LABEL = 1 CONTROL_TEXTBOX = 5 def __init__(self, *args, **kwargs): xbmc.executebuiltin("ActivateWindow(%d)" % ( self.WINDOW, )) # activate the text viewer window self.win = xbmcgui.Window(self.WINDOW) # get window xbmc.sleep(1000) # give window time to initialize self.setControls() def setControls(self,txtFilepath=__home__,txtFilename='changelog.txt'): HeaderMsg = "%s - ( v%s )" % (__plugin__,addon.get_version()) # set heading self.win.getControl(self.CONTROL_LABEL).setLabel(HeaderMsg) #root = addon.get_path() # set text txt_path = os.path.join(txtFilepath,txtFilename) #txt_path = os.path.join(__home__, 'news.txt') f = open(txt_path) text = f.read() self.win.getControl(self.CONTROL_TEXTBOX).setText(text) ### ############################################################################################################ class TextBox_FromUrl: ## Usage Example: TextBox_FromUrl().load('https://raw.github.com/HIGHWAY99/plugin.video.theanimehighway/master/README.md') WINDOW = 10147 CONTROL_LABEL = 1 CONTROL_TEXTBOX = 5 HEADER_MESSAGE = "%s - ( v%s )" % (__plugin__,addon.get_version()) # set heading def load(self, URL_PATH, HEADER_MESSAGE2=''): if (HEADER_MESSAGE2==''): HEADER_MESSAGE2=self.HEADER_MESSAGE print 'text window from url: ',URL_PATH #self.URL_PATH try: text=getURL(URL_PATH)#(self.URL_PATH) except: text='' xbmc.executebuiltin("ActivateWindow(%d)" % ( self.WINDOW, )) # activate the text viewer window self.win = xbmcgui.Window(self.WINDOW) # get window xbmc.sleep(500) # give window time to initialize self.win.getControl(self.CONTROL_LABEL).setLabel(HEADER_MESSAGE2) self.win.getControl(self.CONTROL_TEXTBOX).setText(text) ### ############################################################################################################ class TextBox2: ## Usage Example: TextBox_FromUrl().load('https://raw.github.com/HIGHWAY99/plugin.video.theanimehighway/master/README.md') WINDOW = 10147 CONTROL_LABEL = 1 CONTROL_TEXTBOX = 5 HEADER_MESSAGE = "%s - ( v%s )" % (__plugin__,addon.get_version()) # set heading def load_url(self, URL_PATH, HEADER_MESSAGE2=''): if (debugging==True): print 'text window from url: ',URL_PATH #self.URL_PATH try: text=getURL(URL_PATH)#(self.URL_PATH) except: text='' self.load_window() self.set_header(HEADER_MESSAGE2) self.set_text(text) def load_file(self, FILE_NAME='changelog.txt', HEADER_MESSAGE2='', FILE_PATH=__home__): txt_path = os.path.join(FILE_PATH,FILE_NAME) if (debugging==True): print 'text window from file: ',txt_path f = open(txt_path) text = f.read() self.load_window() self.set_header(HEADER_MESSAGE2) self.set_text(text) def load_string(self, text_string='', HEADER_MESSAGE2=''): self.load_window() self.set_header(HEADER_MESSAGE2) self.set_text(text_string) def load_window(self, sleeptime=500): xbmc.executebuiltin("ActivateWindow(%d)" % ( self.WINDOW, )) # activate the text viewer window self.win = xbmcgui.Window(self.WINDOW) # get window xbmc.sleep(sleeptime) # give window time to initialize def set_header(self, HEADER_MESSAGE2=''): if (HEADER_MESSAGE2==''): HEADER_MESSAGE2=self.HEADER_MESSAGE self.win.getControl(self.CONTROL_LABEL).setLabel(HEADER_MESSAGE2) def set_text(self, text=''): self.win.getControl(self.CONTROL_TEXTBOX).setText(text) ### ############################################################################################################ ### ############################################################################################################ class class_itmOBJ(object): ## Thx to those of plugin.video.SportsDevil. def __init__(self): self.infos_names = [] self.infos_values = [] def __getitem__(self, key, type1=1): #return self.getInfo_str(key) if (type1==1): return self.getInfo_str(key) if (type1==2): return self.getInfo_int(key) if (type1==3): return self.getInfo_b(key) else: return self.getInfo(key) def __setitem__(self, key, value): self.setInfo(key, value) def reset(self): self.infos_names = [] self.infos_values = [] def setInfo(self, key, value): if key in self.infos_names: self.infos_values[self.infos_names.index(key)] = value else: self.infos_names.append(key) self.infos_values.append(value) #if (debugging==True): print 'value: ',value #if (debugging==True): print 'key: '+key #if (debugging==True): print 'value set: ',self.infos_values[self.infos_names.index(key)] ##if (debugging==True): notification('value',value) def getInfo(self, key): if (debugging==True): print self.infos_names if (debugging==True): print self.infos_values if self.infos_names.__contains__(key): return self.infos_values[self.infos_names.index(key)] return None def getInfo_str(self, key): if self.infos_names.__contains__(key): return self.infos_values[self.infos_names.index(key)] return '' def getInfo_int(self, key): if self.infos_names.__contains__(key): return self.infos_values[self.infos_names.index(key)] return 0 def getInfo_b(self, key): if self.infos_names.__contains__(key): return self.infos_values[self.infos_names.index(key)] return False def merge(self, item): for info_name in item.infos_names: if not self[info_name]: self[info_name] = item[info_name] def __str__(self): txt = '' for info_name in self.infos_names: txt += string.ljust(info_name,15) +':\t' + self[info_name] + '\n' return txt ### ############################################################################################################ class class_MyMenu(object): def eod(self): ## xbmcplugin.endOfDirectory(int(sys.argv[1])) def refresh(self): ## To Refresh the Menu. xbmc.executebuiltin("XBMC.Container.Refresh") def get_u(self,iOBJ): ## To make the plugin URL. u=sys.argv[0] u+="?url="+urllib.quote_plus(iOBJ['url']) u+="&mode="+str(iOBJ['mode']) u+="&name="+urllib.quote_plus(iOBJ['name']) u+="&nm="+urllib.quote_plus(iOBJ['name2']) u+="&tp="+str(iOBJ['type2']) u+="&scr="+urllib.quote_plus(iOBJ['image_thumbnail']) u+="&fan="+urllib.quote_plus(iOBJ['image_fanart']) u+="&show="+urllib.quote_plus(iOBJ['show']) u+="&cat="+urllib.quote_plus(iOBJ['category']) return u def addDir_MI(self,iOBJ): ## For Folders - Menu Items #if (debugging==True): print iOBJ if (debugging==True): print 'addDir_MI -- label_title: '+iOBJ['label_title'] ok=True; u=self.get_u(iOBJ) if (debugging==True): print 'addDir_MI -- u: '+u liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail']) liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } ) liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) return ok def addDir_FC(self,iOBJ): ## For Folders - Menu Items with %Fav= for special over-ride commands. ok=True; u=self.get_u(iOBJ) u+='&fav='+iOBJ['favcmd'] if (debugging==True): print 'addDir_FC -- u: '+u liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail']) liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } ) liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) return ok def addDir_LA(self,iOBJ): ## Label Text ok=True; u=self.get_u(iOBJ) if (debugging==True): print 'addDir_LA -- u: '+u liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail']) liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } ) liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) return ok def addDir_CM1(self,iOBJ): ## For ?? ok=True; u=self.get_u(iOBJ) if (debugging==True): print 'addDir_CM1 -- u: '+u liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail']) liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } ) liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] ) contextMenuItems = [] if __settings__.getSetting("enable-showurl") == "true": contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],iOBJ['mode'] , urllib.quote_plus(iOBJ['name']), urllib.quote_plus(iOBJ['name']), 877, 'showurl', urllib.quote_plus(iOBJ['url']), urllib.quote_plus(iOBJ['image_thumbnail']), urllib.quote_plus(iOBJ['image_fanart'])))) liz.addContextMenuItems(contextMenuItems, replaceItems=True) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) ## is_folder=False return ok def addDir_CM2(self,iOBJ,Labels='none'): ## For Folder - Used for show listings. if Labels=='none': Labels={ "Title" : iOBJ['label_title'] } #Labels=self.get_L(iOBJ,Labels) ok=True; u=self.get_u(iOBJ) if (debugging==True): print 'addDir_CM2 -- u: '+u vc_tag=visited_DoCheck(u) if (debugging==True): print vc_tag liz=xbmcgui.ListItem(vc_tag+iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail']) liz.setInfo( type="Video", infoLabels=Labels ) liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] ) contextMenuItems = [] sysname = urllib.quote_plus(iOBJ['name']) sysurl = urllib.quote_plus(iOBJ['url']) sysscr = urllib.quote_plus(iOBJ['image_thumbnail']) sysfan = urllib.quote_plus(iOBJ['image_fanart']) if (debugging==True): print getsetbool('enable-showurl') if __settings__.getSetting("enable-showurl") == "true":#doesn't work for some odd reason >> #if getsetbool('enable-showurl') == 'true':# contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'showurl', sysurl, sysscr, sysfan))) contextMenuItems.append(('[B][COLOR green]ADD[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'add', sysurl, sysscr, sysfan,urllib.quote_plus(iOBJ['name2'])))) contextMenuItems.append(('[B][COLOR red]REMOVE[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'rem', sysurl, sysscr, sysfan,urllib.quote_plus(iOBJ['name2'])))) contextMenuItems.append(('Show Information', 'XBMC.Action(Info)')) contextMenuItems.append(('[B][COLOR orange]Metadata[/COLOR][/B] ~ Show Name', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'metachangeshowname', sysurl, sysscr, sysfan))) #contextMenuItems.append(('[B][COLOR orange]Test[/COLOR][/B] ~ [B]Test[/B]',"notification(%s,%s)" % (sysname,sysurl))) if (debugging==True): print getset('enable-clearfavorites') if __settings__.getSetting("enable-clearfavorites") == "true":#if getset('enable-clearfavorites')==True: contextMenuItems.append(('[B][COLOR yellow]Clear[/COLOR][/B] ~ [B][COLOR tan]Favorites[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'clr', sysurl, sysscr, sysfan))) liz.addContextMenuItems(contextMenuItems, replaceItems=True) if iOBJ['doSorting']==True: ## doSorting=False by default xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) ## is_folder=True return ok def addLink_(self, iOBJ, downloadable=True): ## For Video Links. ok=True; u=self.get_u(iOBJ) if (debugging==True): print u liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail']) if (' - [COLOR grey]' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split(' - [COLOR grey]')[0] if (' [COLOR grey]- ' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split(' [COLOR grey]- ')[0] if ('[COLOR grey] - ' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split('[COLOR grey] - ')[0] if (' - [COLOR' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split(' - [COLOR')[0] if (' [COLOR lime](English Dubbed)[/COLOR]' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Dubbed)[/COLOR]' iOBJ['label_title'] =iOBJ['label_title'].replace(' [COLOR lime](English Dubbed)[/COLOR]','') elif ('English Dubbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Dubbed)[/COLOR]' elif ('Eng Dubbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Dubbed)[/COLOR]' elif ('Dubbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](Dubbed)[/COLOR]' elif ('English Subbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Subbed)[/COLOR]' elif ('Eng Subbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Subbed)[/COLOR]' elif ('Subbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](Subbed)[/COLOR]' liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'], "Studio": iOBJ['label_studio'] } ) liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] ) if (debugging==True): print getset('enable-showurl') if (getsetbool_('enable-showurl')==True): contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(iOBJ['show']), urllib.quote_plus(iOBJ['show']), 0, 'showurl', urllib.quote_plus(iOBJ['url']), iOBJ['image_thumbnail'], iOBJ['image_fanart']))) if (getsetbool_('enable-downloading') == True) and (downloadable==True): if ('novamov.com' not in iOBJ['url']) and ('videoweed.es' not in iOBJ['url']) and ('dailymotion.com' not in iOBJ['url']): contextMenuItems.append(('[B][COLOR purple]Download[/COLOR][/B] ~ [B]File[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(iOBJ['show']), urllib.quote_plus(iOBJ['show']), 0, 'download', urllib.quote_plus(iOBJ['url']), iOBJ['image_thumbnail'], iOBJ['image_fanart']))) liz.addContextMenuItems(contextMenuItems, replaceItems=True) if iOBJ['doSorting']==True: xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz) ## is_folder=True return ok ### ############################################################################################################ ### ############################################################################################################ def getparambool_(idSetting): try: o=params[idSetting] except: o=None if (o==True) or (o=='True') or (o=='true') or (o=='TRUE'): return True else: return False def getparamstr_(idSetting): try: o=params[idSetting] except: o=None if (o==None): return '' else: return o def getparamint_(idSetting): try: o=params[idSetting] except: o=None if (o==None): return 0 else: return o ### ############################################################################################################ def make_item_fill_it( _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ): if (_name2==''): _name2=_name if (_label_title==''): _label_title=_name cio=class_itmOBJ() if (_name==''): return cio cio['url']=_url cio['category']=getparamstr_('cat')+' ::: '+_category cio['type2']=_type2 cio['mode']=_mode cio['name']=_name cio['name2']=_name2 cio['label_title']=_label_title cio['image_thumbnail']=_image_thumbnail cio['image_fanart']=_image_fanart cio['isFolder']=_isFolder return cio def make_item( _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ): cio=make_item_fill_it( _name, _isFolder, _mode, _type2, _category, _image_thumbnail, _image_fanart, _url, _name2, _label_title ) MyMenu.addDir_MI(cio) return cio def make_item_cmd( _favcmd='', _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ): cio=make_item_fill_it( _name, _isFolder, _mode, _type2, _category, _image_thumbnail, _image_fanart, _url, _name2, _label_title ) cio['favcmd']=_favcmd MyMenu.addDir_FC(cio) return cio def make_item_show( cio ): # _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ): #cio=make_item_fill_it( _name, _isFolder, _mode, _type2, _category, _image_thumbnail, _image_fanart, _url, _name2, _label_title ) #cio['Plot']=_ #cio['Rating']=_ #cio['Date_Added']=_ #cio['Date_Released']=_ #cio['Genres']=_ #cio['Themes']=_ #cio['_image_banner']=_ #cio['Date_Aired']=_ #cio['']=_ #cio['']=_ #cio['']=_ #cio['']=_ #cio['']=_ cio['isFolder']=True Labels={ 'Title':cio['label_title'],'Plot':cio['Plot'],'Year':cio['Year'],'Status':cio['Status'],'Rating':cio['Rating'], 'ShowID':cio['id_show'],'Votes':cio['Votes'],'Type':cio['Type'], 'Fanart':cio['image_fanart'], 'Poster':cio['image_thumbnail'], 'Banner':cio['image_banner'], 'Language':cio['Language'], 'Network':cio['Network'], 'Genre':cio['Genres'] } # # # MyMenu.addDir_CM2(cio,Labels) return cio ### ############################################################################################################ ### ############################################################################################################ def get_xbmc_os(): try: xbmc_os = os.environ.get('OS') except: xbmc_os = "unknown" return xbmc_os def get_xbmc_version(): rev_re = re.compile('r(\d+)') try: xbmc_version = xbmc.getInfoLabel('System.BuildVersion') except: xbmc_version = 'Unknown' return xbmc_version def get_xbmc_revision(): rev_re = re.compile('r(\d+)') try: xbmc_version = xbmc.getInfoLabel('System.BuildVersion') except: xbmc_version = 'Unknown' try: xbmc_rev = int(rev_re.search(xbmc_version).group(1)) print "addoncompat.py: XBMC Revision: %s" % xbmc_rev except: print "addoncompat.py: XBMC Revision not available - Version String: %s" % xbmc_version xbmc_rev = 0 return xbmc_rev def _SaveFile(path, data): file = open(path,'w') file.write(data) file.close() def _OpenFile(path): if os.path.isfile(path): ## File found. file = open(path, 'r') contents=file.read() file.close() return contents else: return '' ## File not found. def _CreateDirectory(dir_path): dir_path = dir_path.strip() if not os.path.exists(dir_path): os.makedirs(dir_path) def _get_dir(mypath, dirname): #...creates sub-directories if they are not found. subpath = os.path.join(mypath, dirname) if not os.path.exists(subpath): os.makedirs(subpath) return subpath #def _cleanfilename(name): # valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) # return ''.join(c for c in name if c in valid_chars) #def _cleanFilename(name): # valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) # return ''.join(c for c in name if c in valid_chars) def _time2ms(time): hour,minute,seconds = time.split(';')[0].split(':') frame = int((float(time.split(';')[1])/24)*1000) milliseconds = (((int(hour)*60*60)+(int(minute)*60)+int(seconds))*1000)+frame return milliseconds def _convert_time(milliseconds): seconds = int(float(milliseconds)/1000) milliseconds -= (seconds*1000) hours = seconds / 3600 seconds -= 3600*hours minutes = seconds / 60 seconds -= 60*minutes return "%02d:%02d:%02d,%3d" % (hours, minutes, seconds, milliseconds) def check_url_v(_url): rs=0 try: r = requests.head(_url) #if (debugging==True): print str(r.status_code) rs=r.status_code except: t='' if (rs==404) or (rs=='') or (rs==None): return False elif (rs==200) or (rs==302): return True else: return False ### >>> url = 'http://hup.hu' ### >>> r = requests.head(url) ### >>> r.status_code ### 200 # requests.codes.OK ### >>> url = 'http://www.google.com' ### >>> r = requests.head(url) ### >>> r.status_code ### 302 # requests.codes.FOUND ### >>> url = 'http://simile.mit.edu/crowbar/nothing_here.html' ### >>> r = requests.head(url) ### >>> r.status_code ### 404 # requests.codes.NOT_FOUND def thetvdb_com_episodes3(show_id,season): if (debugging==True): print 'thetvdb.com show ID: '+show_id link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id) print 'thetvdb_com_episodes: '+'http://www.thetvdb.com/?tab=seasonall&id='+show_id itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0] if (season=='') or (season.lower()=='all'): iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td>(.+?)</tr>').findall(itable) else: iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(['+season+'][\s][x][\s]\d+)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td>(.+?)</tr>').findall(itable) ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr> #return iresults return sorted(iresults, key=lambda item: item[1], reverse=True) def thetvdb_com_episodes2(show_id): if (debugging==True): print 'thetvdb.com show ID: '+show_id link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id) print 'thetvdb_com_episodes: '+'http://www.thetvdb.com/?tab=seasonall&id='+show_id itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0] iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td>(.+?)</tr>').findall(itable) ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr> return iresults def thetvdb_com_episodes(show_id): if (debugging==True): print 'thetvdb.com show ID: '+show_id link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id) itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0] iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td><td class=".+?">(<img src=".+?" width=10 height=10>)* &nbsp;</td></tr>', re.IGNORECASE | re.DOTALL).findall(itable) #iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td><td class=".+?"><img src="(.+?)" width=.+? height=.+?>.+?</td></tr>', re.IGNORECASE | re.DOTALL).findall(itable) ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr> #print iresults return iresults # # # def thetvdb_com_episodes1(show_id): if (debugging==True): print 'thetvdb.com show ID: '+show_id link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id) print 'thetvdb_com_episodes: '+'http://www.thetvdb.com/?tab=seasonall&id='+show_id itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0] iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td><td class=".+?"><img src="(.+?)" width=.+? height=.+?>.+?</td></tr>').findall(itable) ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr> return iresults # # # def Episode__get_S_Ep_No(episode_title): season_number=''; episode_number='' if (' Season ' in episode_title): season_number=(re.compile(' Season (\d+) ').findall(episode_title+' ')[0]).strip() elif (' season ' in episode_title): season_number=(re.compile(' season (\d+) ').findall(episode_title+' ')[0]).strip() elif (' s ' in episode_title): season_number=(re.compile(' s (\d+) ').findall(episode_title+' ')[0]).strip() elif (' S ' in episode_title): season_number=(re.compile(' S (\d+) ').findall(episode_title+' ')[0]).strip() else: season_number='1' if (' Episode ' in episode_title): episode_number=(re.compile(' Episode (\d+) ').findall(episode_title+' ')[0]).strip() elif (' episode ' in episode_title): episode_number=(re.compile(' episode (\d+) ').findall(episode_title+' ')[0]).strip() elif (' ep ' in episode_title): episode_number=(re.compile(' ep (\d+) ').findall(episode_title+' ')[0]).strip() elif (' Ep ' in episode_title): episode_number=(re.compile(' Ep (\d+) ').findall(episode_title+' ')[0]).strip() elif (' EP ' in episode_title): episode_number=(re.compile(' EP (\d+) ').findall(episode_title+' ')[0]).strip() elif (' e ' in episode_title): episode_number=(re.compile(' e (\d+) ').findall(episode_title+' ')[0]).strip() elif (' E ' in episode_title): episode_number=(re.compile(' E (\d+) ').findall(episode_title+' ')[0]).strip() else: episode_number='' return (season_number,episode_number) def Episode__get_thumb(the_url,show_img): deb('the_url',the_url) if ('/?tab=episode&' in the_url) and ('&seriesid=' in the_url) and ('&id=' in the_url): id_series=(re.compile('&seriesid=(\d+)&').findall(the_url+'&')[0]).strip() id_episode=(re.compile('&id=(\d+)&').findall(the_url+'&')[0]).strip() episode_thumbnail='http://www.thetvdb.com/banners/episodes/'+id_series+'/'+id_episode+'.jpg' deb('Episode__get_thumb','| '+id_series+' | '+id_episode+' | '+episode_thumbnail+' |') else: episode_thumbnail=show_img; id_series=''; id_episode='' return (episode_thumbnail,id_series,id_episode) def Episode__get_date(thetvdb_episode): return (thetvdb_episode[4].strip()+'-'+thetvdb_episode[5].strip()+'-'+thetvdb_episode[6].strip(),thetvdb_episode[4].strip(),thetvdb_episode[5].strip(),thetvdb_episode[6].strip()) def thetvdb_com__show_search(show_name,show_id='none'): default_return= None #if (show_id=='none'): if (debugging==True): print 'thetvdb.com show name: '+show_name url_search='http://thetvdb.com/index.php?fieldlocation=2&language=7&genre=&year=&network=&zap2it_id=&tvcom_id=&imdb_id=&order=translation&addedBy=&searching=Search&tab=advancedsearch&seriesname='+urllib.quote_plus(show_name) #else: # if (debugging==True): print 'thetvdb.com show id: '+show_id # url_search='http://thetvdb.com/index.php?fieldlocation=2&language=7&genre=&year=&network=&zap2it_id=&tvcom_id=&imdb_id=&order=translation&addedBy=&searching=Search&tab=advancedsearch&seriesname='+urllib.quote_plus(show_name) if (debugging==True): print 'thetvdb.com search: '+url_search link=getURL(url_search) if (link=='none') or (link==''): return default_return elif 'No Series found.' in link: return default_return else: try: match=re.compile('<tr><td class=".+?">.+?</td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)</a></td><td class=".+?">(.+?)</td><td class=".+?">(.+?)</td><td class=".+?">.+?</td><td class=".+?">(.+?)</td><td class=".+?">.+?</td></tr>').findall(link) return match except: try: match=re.compile('<tr><td class=".+?">.+?</td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)</a></td><td class=".+?">(.+?)</td><td class=".+?">(.+?)</td><td class=".+?"></td><td class=".+?">(.+?)</td><td class=".+?">.+?</td></tr>').findall(link) return match except: return default_return def thetvdb_com__show_select(show_name,show_id='none',getFirst=False): default_return= None rMatches=thetvdb_com__show_search(show_name) ### match_showurl,match_name,match_genres,match_status,match_language,match_network,match_rating if (rMatches==None): if (debugging==True): print 'thetvdb_com__show_select() >> thetvdb_com__show_search() >> [no resullts found.]' if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Shows were found.') return default_return if (getFirst==True): if (option_list==[]): if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Results were found.') return default_return else: return rMatches[0] else: dialogSelect = xbmcgui.Dialog() option_list = [] for rMatch in rMatches: option_list.append(rMatch[1]) if (option_list==[]): if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Results were found.') return default_return index=dialogSelect.select('Choose', option_list) if (debugging==True): print 'choice selected: '+str(index)+'.) '+option_list[index] if (shoDebugging==True): notification('choice selected: ',str(index)+'.) '+option_list[index]) return rMatches[index] def metachange__Show_Name(show_name,show_id='none',getFirst=False): rSelected=thetvdb_com__show_select(show_name,show_id,getFirst) if (rSelected==None): return def episode__AirDates(show_name,show_id='none',getFirst=False): if (show_id=='none'): rSelected=thetvdb_com__show_select(show_name,show_id,getFirst) if (rSelected==None): if (debugging==True): print 'AirDates >> rSelect==None' return if ('&id=' in rSelected[0]): show_id=(re.compile('&id=(\d+)&').findall(rSelected[0]+'&')[0]).strip() show_name=(rSelected[1]).strip() elif (';id=' in rSelected[0]): show_id=(re.compile(';id=(\d+)&').findall(rSelected[0]+'&')[0]).strip() show_name=(rSelected[1]).strip() else: if (debugging==True): print 'AirDates >> no "&id=" found' if (debugging==True): print rSelected[0] return rEpisodes=thetvdb_com_episodes(show_id) ## 'http://www.thetvdb.com/?tab=seasonall&id='+show_id ## if (rEpisodes==[]): if (debugging==True): print 'AirDates >> rEpisodes is empty' return rEpisodes=sorted(rEpisodes, key=lambda item: item[4]+item[5]+item[6], reverse=True) dialogSelect = xbmcgui.Dialog(); option_list = [] for rMatch in rEpisodes: dateColor='tan' if (int(rMatch[4].strip()) > int(datetime.date.today().strftime("%Y"))) or (int(rMatch[4].strip())==int(datetime.date.today().strftime("%Y"))): if (int(rMatch[5].strip()) > int(datetime.date.today().strftime("%m"))): dateColor='cornflowerblue' elif (int(rMatch[5].strip()) > int(datetime.date.today().strftime("%m"))) or (int(rMatch[5].strip())==int(datetime.date.today().strftime("%m"))): if (int(rMatch[6].strip())==int(datetime.date.today().strftime("%d"))) and (int(rMatch[5].strip())==int(datetime.date.today().strftime("%m"))) and (int(rMatch[4].strip())==int(datetime.date.today().strftime("%Y"))): dateColor='orange' elif (int(rMatch[6].strip())==int(datetime.date.today().strftime("%d"))) or (int(rMatch[6].strip()) > int(datetime.date.today().strftime("%d"))): dateColor='cornflowerblue' #datetime.date.today().strftime("%B %d, %Y") option_list.append('[COLOR red][B]'+rMatch[1]+'[/B][/COLOR] [COLOR purple]([COLOR '+dateColor+']'+rMatch[4]+'[/COLOR]-[COLOR '+dateColor+']'+rMatch[5]+'[/COLOR]-[COLOR '+dateColor+']'+rMatch[6]+'[/COLOR])[/COLOR] [COLOR green][I]'+rMatch[3]+'[/I][/COLOR]') if (option_list==[]): if (debugging==True): print 'AirDates >> option_list is empty' return ##if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Results were found.') index=dialogSelect.select('Episodes: '+show_name, option_list) # # def search_for_airdates(r=''): if (r==None) or (r=='') or (r=='none') or (r==False): r=showkeyboard('','Search for Show:') else: r=filename_filter_out_year(filename_filter_colorcodes(r)) if (r==False) or (r==None) or (r==''): return rr=episode__AirDates(r) def askSelection(option_list=[],txtHeader=''): if (option_list==[]): if (debugging==True): print 'askSelection() >> option_list is empty' return None dialogSelect = xbmcgui.Dialog(); index=dialogSelect.select(txtHeader, option_list) #if (index== -1): # return None #if (index==False) or (index==None) or (index=='') or (index== -1): # if (debugging==True): print 'askSelection() >> problem retreiving selected item' # if (debugging==True): print index # if (debugging==True): print str(index) # return None #else: return index return index def tfalse(r,d=False): ## Get True / False if (r.lower()=='true' ): return True elif (r.lower()=='false'): return False else: return d ## ### This is already in default.py for the plugin.video.solarmovie.so addon / plugin. ##def cFL(t,c='white'): ### For Coloring Text ### ## return '[COLOR '+c+']'+t+'[/COLOR]' def iFL(t): ### For Italic Text ### return '[I]'+t+'[/I]' def bFL(t): ### For Bold Text ### return '[B]'+t+'[/B]' def _FL(t,c,e=''): ### For Custom Text Tags ### if (e==''): d='' else: d=' '+e return '['+c.upper()+d+']'+t+'[/'+c.upper()+']' def WhereAmI(t): ### for Writing Location Data to log file ### if (_debugging==True): print 'Where am I: '+t def deb(s,t): ### for Writing Debug Data to log file ### if (_debugging==True): print s+': '+t def debob(t): ### for Writing Debug Object to log file ### if (_debugging==True): print t def nolines(t): it=t.splitlines() t='' for L in it: t=t+L t=((t.replace("\r","")).replace("\n","")) return t def checkImgUrl(img): img=xbmc.translatePath(img)#; deb('Local Image',img) if (check_ifUrl_isHTML(img)==True): return img else: return '' def checkImgLocal(img): img=xbmc.translatePath(img)#; deb('Local Image',img) if (os.path.isfile(img)): return img else: return '' ### ############################################################################################################ ### ############################################################################################################ def Library_SaveTo_Movies(url,iconimage,name,year): library=xbmc.translatePath(_addon.get_profile()) foldername=xbmc.translatePath(os.path.join(library, 'Movies')) if os.path.exists(foldername)==False: os.mkdir(os.path.join(library, 'Movies')) strm='%s?mode=%s&section=%s&url=%s&iconimage=%s&title=%s&showtitle=%s&year=%s&showyear=%s'% (sys.argv[0],'PlayLibrary',ps('section.movie'),urllib.quote_plus(url),urllib.quote_plus(iconimage),urllib.quote_plus(name),urllib.quote_plus(name),year,year) filename=name+' ('+year+')' filename=clean_filename(filename+'.strm') file =xbmc.translatePath(os.path.join(foldername,filename)) ##print file a=open(file, "w"); a.write(strm); a.close() myNote('Library Movie:',filename) def Library_SaveTo_Episode(url,iconimage,name,year,country,season_number,episode_number,episode_title): library=xbmc.translatePath(_addon.get_profile()) foldermain=xbmc.translatePath(os.path.join(library, 'TV')) if os.path.exists(foldermain)==False: os.mkdir(foldermain) foldername=xbmc.translatePath(os.path.join(foldermain,name+' ('+year+')')) if os.path.exists(foldername)==False: os.mkdir(foldername) folderseason=xbmc.translatePath(os.path.join(foldername, 'Season '+season_number)) if os.path.exists(folderseason)==False: os.mkdir(folderseason) strm='%s?mode=%s&section=%s&url=%s&iconimage=%s&title=%s&showtitle=%s&year=%s&showyear=%s&country=%s&season=%s&episode=%s&episodetitle=%s'% (sys.argv[0],'PlayLibrary',ps('section.tv'),urllib.quote_plus(url),urllib.quote_plus(iconimage),urllib.quote_plus(name),urllib.quote_plus(name),year,year,country,season_number,episode_number,episode_title) # # filename=name+' ('+year+') S'+season_number+'E'+episode_number filename=clean_filename(filename+'.strm') file =xbmc.translatePath(os.path.join(folderseason,filename)) ##print file a=open(file, "w"); a.write(strm); a.close() myNote('Library TV:',filename) def myNote( header='',msg='',delay=5000,image='http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/US_99_%281961%29.svg/40px-US_99_%281961%29.svg.png'): header=cFL(header,ps('cFL_color')); msg=cFL(msg,ps('cFL_color2')) _addon.show_small_popup(title=header,msg=msg,delay=delay,image=image) ### ############################################################################################################ ### ############################################################################################################ def twitter_timeline(person): HTML=getURL('http://mobile.twitter.com/'+person) ### HTML=getURL('http://twitter.com/'+person) # # ### ############################################################################################################ ### ############################################################################################################ def nURL2(url,method='get',form_data={},headers={},html='',proxy='',User_Agent='',cookie_file='',load_cookie=False,save_cookie=False): if url=='': return '' AntiTag='<iframe style="display:none;visibility:hidden;" src="http://my.incapsula.com/public/ga/jsTest.html" id="gaIframe"></iframe>' dhtml=''+html html=' '+AntiTag+' ' if len(User_Agent) > 0: net.set_user_agent(User_Agent) else: net2.set_user_agent(ps('User-Agent')) if len(proxy) > 9: net2.set_proxy(proxy) if (len(cookie_file) > 0) and (load_cookie==True): net2.set_cookies(cookie_file) xTimes=0 while (AntiTag in html): xTimes=xTimes+1 if method.lower()=='get': try: html=net2.http_GET(url,headers=headers).content except: html=dhtml elif method.lower()=='post': try: html=net2.http_POST(url,form_data=form_data,headers=headers).content #,compression=False except: html=dhtml elif method.lower()=='head': try: html=net2.http_HEAD(url,headers=headers).content except: html=dhtml if xTimes > 5: html=html.replace(AntiTag,'') elif AntiTag in html: xbmc.sleep(4000) if (len(html) > 0) and (len(cookie_file) > 0) and (save_cookie==True): net2.save_cookies(cookie_file) return html def nURL(url,method='get',form_data={},headers={},html='',proxy='',User_Agent='',cookie_file='',load_cookie=False,save_cookie=False): if url=='': return '' dhtml=''+html if len(User_Agent) > 0: net2.set_user_agent(User_Agent) else: net2.set_user_agent(ps('User-Agent')) if (tfalse(addst('customproxy','false'))==True) and (len(addst('proxy','')) > 9): proxy=addst('proxy','') #else: proxy=ps('proxy') if len(proxy) > 9: net2.set_proxy(proxy) if (len(cookie_file) > 0) and (load_cookie==True): net2.set_cookies(cookie_file) if method.lower()=='get': try: html=net2.http_GET(url,headers=headers).content except: html=dhtml elif method.lower()=='post': try: html=net2.http_POST(url,form_data=form_data,headers=headers).content #,compression=False except: html=dhtml elif method.lower()=='head': try: html=net2.http_HEAD(url,headers=headers).content except: html=dhtml if (len(html) > 0) and (len(cookie_file) > 0) and (save_cookie==True): net2.save_cookies(cookie_file) return html ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################ MyMenu=class_MyMenu() #notification('Current Site',mainSite) ### ############################################################################################################ ### ############################################################################################################ ### ############################################################################################################
HIGHWAY99/plugin.audio.ukradio
teh_tools.py
Python
gpl-3.0
100,415
[ "VisIt" ]
00a667ae2fa3c9c6ba5c607e13fc737fd0fb3dbdfefdedac0c777d2a6e92335e
from __future__ import print_function import sys import os import numpy as np from collections import OrderedDict from astrometry.util.fits import fits_table from astrometry.util.file import trymakedirs from common import Decals, DecamImage from astrometry.libkd.spherematch import match_radec ''' This script is used to produce lists of CCDs or bricks, for production purposes (building qdo queue, eg). python legacypipe/queue-calibs.py | qdo load cal - dr1(d): qdo launch bricks 16 --mpack 6 --batchopts "-A desi" --walltime=24:00:00 --script projects/desi/pipebrick.sh --batchqueue regular --verbose qdo launch cal 1 --batchopts "-A cosmo -t 1-50" --walltime=24:00:00 --batchqueue serial --script projects/desi/run-calib.py #qdo launch cal 1 --batchopts "-A cosmo -t 1-10" --walltime=24:00:00 --batchqueue serial Or qdo launch cal 8 --batchopts "-A cosmo -t 1-6" --pack --walltime=30:00 --batchqueue debug --script projects/desi/run-calib.py Or lists of bricks to run in production: python projects/desi/queue-calibs.py | qdo load bricks - qdo launch bricks 1 --batchopts "-A cosmo -t 1-10 -l walltime=24:00:00 -q serial -o pipebrick-logs -j oe -l pvmem=6GB" \ --script projects/desi/pipebrick.sh ''' import matplotlib matplotlib.use('Agg') import pylab as plt from glob import glob def log(*s): print >>sys.stderr, ' '.join([str(ss) for ss in s]) if __name__ == '__main__': import optparse parser = optparse.OptionParser() parser.add_option('--calibs', action='store_true', default=False, help='Output CCDs that need to be calibrated.') parser.add_option('--forced', action='store_true', default=False, help='Output forced-photometry commands') parser.add_option('--lsb', action='store_true', default=False, help='Output Low-Surface-Brightness commands') parser.add_option('--touching', action='store_true', default=False, help='Cut to only CCDs touching selected bricks') parser.add_option('--check', action='store_true', default=False, help='Check which calibrations actually need to run.') parser.add_option('--check-coadd', action='store_true', default=False, help='Check which caoadds actually need to run.') parser.add_option('--out', help='Output filename for calibs, default %default', default='jobs') parser.add_option('--command', action='store_true', default=False, help='Write out full command-line to run calib') parser.add_option('--maxdec', type=float, help='Maximum Dec to run') parser.add_option('--mindec', type=float, help='Minimum Dec to run') parser.add_option('--region', help='Region to select') parser.add_option('--bricks', help='Set bricks.fits file to load') parser.add_option('--ccds', help='Set ccds.fits file to load') parser.add_option('--delete-sky', default=False, action='store_true', help='Delete any existing sky calibration files') parser.add_option('--delete-pvastrom', default=False, action='store_true', help='Delete any existing PV WCS calibration files') parser.add_option('--write-ccds', help='Write CCDs list as FITS table?') opt,args = parser.parse_args() decals = Decals() if opt.bricks is not None: B = fits_table(opt.bricks) log('Read', len(B), 'from', opt.bricks) else: B = decals.get_bricks() if opt.ccds is not None: T = fits_table(opt.ccds) log('Read', len(T), 'from', opt.ccds) else: T = decals.get_ccds() log(len(T), 'CCDs') T.index = np.arange(len(T)) # I,J,d,counts = match_radec(B.ra, B.dec, T.ra, T.dec, 0.2, nearest=True, count=True) # plt.clf() # plt.hist(counts, counts.max()+1) # plt.savefig('bricks.png') # B.cut(I[counts >= 9]) # plt.clf() # plt.plot(B.ra, B.dec, 'b.') # #plt.scatter(B.ra[I], B.dec[I], c=counts) # plt.savefig('bricks2.png') # DES Stripe82 #rlo,rhi = 350.,360. # rlo,rhi = 300., 10. # dlo,dhi = -6., 4. # TINY bit #rlo,rhi = 350.,351.1 #dlo,dhi = 0., 1.1 # EDR+ # 860 bricks # ~10,000 CCDs #rlo,rhi = 239,246 #dlo,dhi = 5, 13 # DR1 #rlo,rhi = 0, 360 # part 1 #dlo,dhi = 25, 40 # part 2 #dlo,dhi = 20,25 # part 3 #dlo,dhi = 15,20 # part 4 #dlo,dhi = 10,15 # part 5 #dlo,dhi = 5,10 # the rest #dlo,dhi = -11, 5 #dlo,dhi = 15,25.5 dlo,dhi = -15, 40 rlo,rhi = 0, 360 # Arjun says 3x3 coverage area is roughly # RA=240-252 DEC=6-12 (but not completely rectangular) # COSMOS #rlo,rhi = 148.9, 151.2 #dlo,dhi = 0.9, 3.5 # A nice well-behaved region (EDR2/3) # rlo,rhi = 243.6, 244.6 # dlo,dhi = 8.1, 8.6 # 56 bricks, ~725 CCDs #B.cut((B.ra > 240) * (B.ra < 242) * (B.dec > 5) * (B.dec < 7)) # 240 bricks, ~3000 CCDs #B.cut((B.ra > 240) * (B.ra < 244) * (B.dec > 5) * (B.dec < 9)) # 535 bricks, ~7000 CCDs #B.cut((B.ra > 240) * (B.ra < 245) * (B.dec > 5) * (B.dec < 12)) if opt.region in ['test1', 'test2', 'test3', 'test4']: nm = dict(test1='2446p115', # weird stuff around bright star test2='1183p292', # faint sources around bright galaxy test3='3503p005', # DES test4='1163p277', # Pollux )[opt.region] B.cut(np.flatnonzero(np.array([s == nm for s in B.brickname]))) log('Cut to', len(B), 'bricks') log(B.ra, B.dec) dlo,dhi = -90,90 rlo,rhi = 0, 360 elif opt.region == 'edr': # EDR: # 535 bricks, ~7000 CCDs rlo,rhi = 240,245 dlo,dhi = 5, 12 elif opt.region == 'des': dlo, dhi = -6., 4. rlo, rhi = 317., 7. T.cut(np.flatnonzero(np.array(['CPDES82' in fn for fn in T.cpimage]))) log('Cut to', len(T), 'CCDs with "CPDES82" in filename') elif opt.region == 'subdes': rlo,rhi = 320., 360. dlo,dhi = -1.25, 1.25 elif opt.region == 'grz': # Bricks with grz coverage. # Be sure to use --bricks decals-bricks-in-dr1.fits # which has_[grz] columns. B.cut((B.has_g == 1) * (B.has_r == 1) * (B.has_z == 1)) log('Cut to', len(B), 'bricks with grz coverage') elif opt.region == 'nogrz': # Bricks without grz coverage. # Be sure to use --bricks decals-bricks-in-dr1.fits # which has_[grz] columns. B.cut(np.logical_not((B.has_g == 1) * (B.has_r == 1) * (B.has_z == 1))) log('Cut to', len(B), 'bricks withOUT grz coverage') elif opt.region == 'deep2': rlo,rhi = 250,260 dlo,dhi = 30,35 elif opt.region == 'virgo': rlo,rhi = 185,190 dlo,dhi = 10, 15 elif opt.region == 'virgo2': rlo,rhi = 182,192 dlo,dhi = 8, 18 elif opt.region == 'lsb': rlo,rhi = 147.2, 147.8 dlo,dhi = -0.4, 0.4 if opt.mindec is not None: dlo = opt.mindec if opt.maxdec is not None: dhi = opt.maxdec if rlo < rhi: B.cut((B.ra >= rlo) * (B.ra <= rhi) * (B.dec >= dlo) * (B.dec <= dhi)) else: # RA wrap B.cut(np.logical_or(B.ra >= rlo, B.ra <= rhi) * (B.dec >= dlo) * (B.dec <= dhi)) log(len(B), 'bricks in range') I,J,d = match_radec(B.ra, B.dec, T.ra, T.dec, 0.25) keep = np.zeros(len(B), bool) for i in I: keep[i] = True B.cut(keep) log('Cut to', len(B), 'bricks near CCDs') if opt.touching: keep = np.zeros(len(T), bool) for j in J: keep[j] = True T.cut(keep) log('Cut to', len(T), 'CCDs near bricks') # Aside -- how many near DR1=1 CCDs? if False: T2 = D.get_ccds() log(len(T2), 'CCDs') T2.cut(T2.dr1 == 1) log(len(T2), 'CCDs marked DR1=1') log(len(B), 'bricks in range') I,J,d = match_radec(B.ra, B.dec, T2.ra, T2.dec, 0.25) keep = np.zeros(len(B), bool) for i in I: keep[i] = True B2 = B[keep] log('Total of', len(B2), 'bricks near CCDs with DR1=1') for band in 'grz': Tb = T2[T2.filter == band] log(len(Tb), 'in filter', band) I,J,d = match_radec(B2.ra, B2.dec, Tb.ra, Tb.dec, 0.25) good = np.zeros(len(B2), np.uint8) for i in I: good[i] = 1 B2.set('has_' + band, good) B2.writeto('decals-bricks-in-dr1.fits') sys.exit(0) # sort by dec decreasing B.cut(np.argsort(-B.dec)) for b in B: if opt.check: fn = 'dr1n/tractor/%s/tractor-%s.fits' % (b.brickname[:3], b.brickname) if os.path.exists(fn): print('Exists:', fn, file=sys.stderr) continue if opt.check_coadd: fn = 'dr1b/coadd/%s/%s/decals-%s-image.jpg' % (b.brickname[:3], b.brickname, b.brickname) if os.path.exists(fn): print('Exists:', fn, file=sys.stderr) continue print(b.brickname) if not (opt.calibs or opt.forced or opt.lsb): sys.exit(0) if 'dr1' in T.columns(): T.cut(T.dr1 == 1) log(len(T), 'photometric for DR1') bands = 'grz' log('Filters:', np.unique(T.filter)) T.cut(np.flatnonzero(np.array([f in bands for f in T.filter]))) log('Cut to', len(T), 'CCDs in filters', bands) if opt.touching: allI = set() for b in B: wcs = wcs_for_brick(b) I = ccds_touching_wcs(wcs, T) log(len(I), 'CCDs for brick', b.brickid, 'RA,Dec (%.2f, %.2f)' % (b.ra, b.dec)) if len(I) == 0: continue allI.update(I) allI = list(allI) allI.sort() else: allI = np.arange(len(T)) if opt.write_ccds: T[allI].writeto(opt.write_ccds) log('Wrote', opt.write_ccds) ## Be careful here -- T has been cut; we want to write out T.index. ## 'allI' contains indices into T. if opt.forced: log('Writing forced-photometry commands to', opt.out) f = open(opt.out,'w') log('Total of', len(allI), 'CCDs') for j,i in enumerate(allI): expstr = '%08i' % T.expnum[i] #outdir = os.path.join('forced', expstr[:5], expstr) #trymakedirs(outdir) outfn = os.path.join('forced', expstr[:5], expstr, 'decam-%s-%s-forced.fits' % (expstr, T.ccdname[i])) imgfn = os.path.join(decals.decals_dir, 'images', T.image_filename[i].strip()) if (not os.path.exists(imgfn) and imgfn.endswith('.fz') and os.path.exists(imgfn[:-3])): imgfn = imgfn[:-3] f.write('python legacypipe/forced-photom-decam.py %s %i DR1 %s\n' % (imgfn, T.cpimage_hdu[i], outfn)) f.close() log('Wrote', opt.out) sys.exit(0) if opt.lsb: log('Writing LSB commands to', opt.out) f = open(opt.out,'w') log('Total of', len(allI), 'CCDs') for j,i in enumerate(allI): exp = T.expnum[i] ext = T.ccdname[i].strip() outfn = 'lsb/lsb-%s-%s.fits' % (exp, ext) f.write('python projects/desi/lsb.py --expnum %i --extname %s --out %s -F -n > lsb/lsb-%s-%s.log 2>&1\n' % (exp, ext, outfn, exp, ext)) f.close() log('Wrote', opt.out) sys.exit(0) log('Writing calibs to', opt.out) f = open(opt.out,'w') log('Total of', len(allI), 'CCDs') for j,i in enumerate(allI): if opt.delete_sky or opt.delete_pvastrom: log(j+1, 'of', len(allI)) im = DecamImage(decals, T[i]) if opt.delete_sky and os.path.exists(im.skyfn): log(' deleting:', im.skyfn) os.unlink(im.skyfn) if opt.delete_pvastrom and os.path.exists(im.pvwcsfn): log(' deleting:', im.pvwcsfn) os.unlink(im.pvwcsfn) if opt.check: log(j+1, 'of', len(allI)) im = DecamImage(decals, T[i]) if not im.run_calibs(im, just_check=True): log('Calibs for', im.expnum, im.ccdname, im.calname, 'already done') continue if opt.command: f.write('python legacypipe/run-calib.py --expnum %i --ccdname %s\n' % (T.expnum[i], T.ccdname[i])) else: f.write('%i\n' % T.index[i]) if opt.check: f.flush() f.close() log('Wrote', opt.out)
gregreen/legacypipe
py/legacypipe/queue-calibs.py
Python
gpl-2.0
12,890
[ "Galaxy" ]
0f0781fd9a977502e0bfa4a71b174e62337aeb7eabb537ab278e394d5ad00551
import sys import ast import constants as c import datetime import inspect from matplotlib.dates import date2num import meteorologicalfunctions as mf import numpy import os import qcck import qcfunc import qcio import qcutils from scipy import interpolate, signal import time import xlrd from matplotlib.mlab import griddata import xlwt import logging import pysolar log = logging.getLogger('qc.ts') def albedo(cf,ds): """ Filter albedo measurements to: high solar angle specified by periods between 10.00 and 14.00, inclusive and full sunlight in which Fsd > 290 W/m2 Usage qcts.albedo(ds) ds: data structure """ log.info(' Applying albedo constraints') if 'albedo' not in ds.series.keys(): if 'Fsd' in ds.series.keys() and 'Fsu' in ds.series.keys(): Fsd,f,a = qcutils.GetSeriesasMA(ds,'Fsd') Fsu,f,a = qcutils.GetSeriesasMA(ds,'Fsu') albedo = Fsu / Fsd attr = qcutils.MakeAttributeDictionary(long_name='solar albedo',units='none',standard_name='solar_albedo') qcutils.CreateSeries(ds,'albedo',albedo,FList=['Fsd','Fsu'],Attr=attr) else: log.warning(' Fsd or Fsu not in ds, albedo not calculated') return else: albedo,f,a = qcutils.GetSeriesasMA(ds,'albedo') if 'Fsd' in ds.series.keys(): Fsd,f,a = qcutils.GetSeriesasMA(ds,'Fsd') else: Fsd,f,a = qcutils.GetSeriesasMA(ds,'Fn') if qcutils.cfkeycheck(cf,ThisOne='albedo',key='Threshold'): Fsdbase = float(cf['Variables']['albedo']['Threshold']['Fsd']) ds.series['albedo']['Attr']['FsdCutoff'] = Fsdbase else: Fsdbase = 290. index = numpy.ma.where((Fsd < Fsdbase) | (ds.series['Hdh']['Data'] < 10) | (ds.series['Hdh']['Data'] > 14))[0] index1 = numpy.ma.where(Fsd < Fsdbase)[0] index2 = numpy.ma.where((ds.series['Hdh']['Data'] < 10) | (ds.series['Hdh']['Data'] > 14))[0] albedo[index] = numpy.float64(c.missing_value) ds.series['albedo']['Flag'][index1] = numpy.int32(51) # bad Fsd flag only if bad time flag not set ds.series['albedo']['Flag'][index2] = numpy.int32(52) # bad time flag ds.series['albedo']['Data']=numpy.ma.filled(albedo,float(c.missing_value)) def ApplyLinear(cf,ds,ThisOne): """ Applies a linear correction to variable passed from qcls. Time period to apply the correction, slope and offset are specified in the control file. Usage qcts.ApplyLinear(cf,ds,x) cf: control file ds: data structure x: input/output variable in ds. Example: 'Cc_7500_Av' """ if ThisOne not in ds.series.keys(): return if qcutils.incf(cf,ThisOne) and qcutils.haskey(cf,ThisOne,'Linear'): log.info(' Applying linear correction to '+ThisOne) data = numpy.ma.masked_where(ds.series[ThisOne]['Data']==float(c.missing_value),ds.series[ThisOne]['Data']) flag = ds.series[ThisOne]['Flag'].copy() ldt = ds.series['DateTime']['Data'] LinearList = cf['Variables'][ThisOne]['Linear'].keys() for i in range(len(LinearList)): LinearItemList = ast.literal_eval(cf['Variables'][ThisOne]['Linear'][str(i)]) try: si = ldt.index(datetime.datetime.strptime(LinearItemList[0],'%Y-%m-%d %H:%M')) except ValueError: si = 0 try: ei = ldt.index(datetime.datetime.strptime(LinearItemList[1],'%Y-%m-%d %H:%M')) + 1 except ValueError: ei = -1 Slope = float(LinearItemList[2]) Offset = float(LinearItemList[3]) data[si:ei] = Slope * data[si:ei] + Offset index = numpy.where(flag[si:ei]==0)[0] flag[si:ei][index] = numpy.int32(10) ds.series[ThisOne]['Data'] = numpy.ma.filled(data,float(c.missing_value)).astype(numpy.float64) ds.series[ThisOne]['Flag'] = flag def ApplyLinearDrift(cf,ds,ThisOne): """ Applies a linear correction to variable passed from qcls. The slope is interpolated for each 30-min period between the starting value at time 0 and the ending value at time 1. Slope0, Slope1 and Offset are defined in the control file. This function applies to a dataset in which the start and end times in the control file are matched by the time period in the dataset. Usage qcts.ApplyLinearDrift(cf,ds,x) cf: control file ds: data structure x: input/output variable in ds. Example: 'Cc_7500_Av' """ if ThisOne not in ds.series.keys(): return if qcutils.incf(cf,ThisOne) and qcutils.haskey(cf,ThisOne,'Drift'): log.info(' Applying linear drift correction to '+ThisOne) data = numpy.ma.masked_where(ds.series[ThisOne]['Data']==float(c.missing_value),ds.series[ThisOne]['Data']) flag = ds.series[ThisOne]['Flag'] ldt = ds.series['DateTime']['Data'] DriftList = cf['Variables'][ThisOne]['Drift'].keys() for i in range(len(DriftList)): DriftItemList = ast.literal_eval(cf['Variables'][ThisOne]['Drift'][str(i)]) try: si = ldt.index(datetime.datetime.strptime(DriftItemList[0],'%Y-%m-%d %H:%M')) except ValueError: si = 0 try: ei = ldt.index(datetime.datetime.strptime(DriftItemList[1],'%Y-%m-%d %H:%M')) + 1 except ValueError: ei = -1 Slope = numpy.zeros(len(data)) Slope0 = float(DriftItemList[2]) Slope1 = float(DriftItemList[3]) Offset = float(DriftItemList[4]) nRecs = len(Slope[si:ei]) for i in range(nRecs): ssi = si + i Slope[ssi] = ((((Slope1 - Slope0) / nRecs) * i) + Slope0) data[si:ei] = Slope[si:ei] * data[si:ei] + Offset flag[si:ei] = 10 ds.series[ThisOne]['Data'] = numpy.ma.filled(data,float(c.missing_value)) ds.series[ThisOne]['Flag'] = flag def ApplyLinearDriftLocal(cf,ds,ThisOne): """ Applies a linear correction to variable passed from qcls. The slope is interpolated since the starting value at time 0 using a known 30-min increment. Slope0, SlopeIncrement and Offset are defined in the control file. This function applies to a dataset in which the start time in the control file is matched by dataset start time, but in which the end time in the control file extends beyond the dataset end. Usage qcts.ApplyLinearDriftLocal(cf,ds,x) cf: control file ds: data structure x: input/output variable in ds. Example: 'Cc_7500_Av' """ if ThisOne not in ds.series.keys(): return if qcutils.incf(cf,ThisOne) and qcutils.haskey(cf,ThisOne,'LocalDrift'): log.info(' Applying linear drift correction to '+ThisOne) data = numpy.ma.masked_where(ds.series[ThisOne]['Data']==float(c.missing_value),ds.series[ThisOne]['Data']) flag = ds.series[ThisOne]['Flag'] ldt = ds.series['DateTime']['Data'] DriftList = cf['Variables'][ThisOne]['LocalDrift'].keys() for i in range(len(DriftList)): DriftItemList = ast.literal_eval(cf['Variables'][ThisOne]['LocalDrift'][str(i)]) try: si = ldt.index(datetime.datetime.strptime(DriftItemList[0],'%Y-%m-%d %H:%M')) except ValueError: si = 0 try: ei = ldt.index(datetime.datetime.strptime(DriftItemList[1],'%Y-%m-%d %H:%M')) + 1 except ValueError: ei = -1 Slope = numpy.zeros(len(data)) Slope0 = float(DriftItemList[2]) SlopeIncrement = float(DriftItemList[3]) Offset = float(DriftItemList[4]) nRecs = len(Slope[si:ei]) for i in range(nRecs): ssi = si + i Slope[ssi] = (SlopeIncrement * i) + Slope0 data[si:ei] = Slope[si:ei] * data[si:ei] + Offset flag[si:ei] = numpy.int32(10) ds.series[ThisOne]['Data'] = numpy.ma.filled(data,float(c.missing_value)) ds.series[ThisOne]['Flag'] = flag def AverageSeriesByElements(cf,ds,Av_out): """ Calculates the average of multiple time series. Multiple time series are entered and a single time series representing the average at each observational period is returned. Usage qcts.AverageSeriesByElements(cf,ds,Av_out) cf: control file object (must contain an entry for Av_out) ds: data structure Av_out: output variable to ds. Example: 'Fg' Series_in: input variable series in ds. Example: ['Fg_8cma','Fg_8cmb'] """ if Av_out not in cf['Variables'].keys(): return if Av_out in ds.averageserieslist: return srclist, standardname = qcutils.GetAverageSeriesKeys(cf,Av_out) # log.info(' Averaging series in '+str(srclist)+' into '+Av_out) log.info(' Averaging '+str(srclist)+'==>'+Av_out) nSeries = len(srclist) if nSeries==0: log.error(' AverageSeriesByElements: no input series specified for'+str(Av_out)) return if nSeries==1: tmp_data = ds.series[srclist[0]]['Data'].copy() tmp_flag = ds.series[srclist[0]]['Flag'].copy() tmp_attr = ds.series[srclist[0]]['Attr'].copy() Av_data = numpy.ma.masked_where(tmp_data==float(c.missing_value),tmp_data) Mn_flag = tmp_flag SeriesNameString = srclist[0] else: tmp_data = ds.series[srclist[0]]['Data'].copy() tmp_flag = ds.series[srclist[0]]['Flag'].copy() index = numpy.where(numpy.mod(tmp_flag,10)==0) # find the elements with flag = 0, 10, 20 etc tmp_flag[index] = 0 # set them all to 0 tmp_attr = ds.series[srclist[0]]['Attr'].copy() SeriesNameString = srclist[0] srclist.remove(srclist[0]) for ThisOne in srclist: SeriesNameString = SeriesNameString+', '+ThisOne tmp_data = numpy.vstack((tmp_data,ds.series[ThisOne]['Data'].copy())) tmp_flag = numpy.vstack((tmp_flag,ds.series[ThisOne]['Flag'].copy())) tmp_data = numpy.ma.masked_where(tmp_data==float(c.missing_value),tmp_data) Av_data = numpy.ma.average(tmp_data,axis=0) Mn_flag = numpy.min(tmp_flag,axis=0) ds.averageserieslist.append(Av_out) #attr = qcutils.MakeAttributeDictionary(long_name='Element-wise average of series '+SeriesNameString, #standard_name=standardname,units=ds.series[srclist[0]]['Attr']['units']) # this is a temporary fix, better to have a routine update the attr dictionary tmp_attr["long_name"] = tmp_attr["long_name"]+", element-wise average of series " + SeriesNameString qcutils.CreateSeries(ds,Av_out,Av_data,Flag=Mn_flag,Attr=tmp_attr) def CalculateAvailableEnergy(ds,Fa_out='Fa',Fn_in='Fn',Fg_in='Fg'): """ Calculate the average energy as Fn - G. Usage qcts.CalculateAvailableEnergy(ds,Fa_out='Fa',Fn_in='Fn',Fg_in='Fg') ds: data structure Fa_out: output available energy variable to ds. Example: 'Fa' Fn_in: input net radiation in ds. Example: 'Fn' Fg_in: input ground heat flux in ds. Example: 'Fg' """ log.info(' Calculating available energy from Fn and Fg') if Fn_in not in ds.series.keys(): log.warning(" Series "+Fn_in+" not found in data file") return if Fg_in not in ds.series.keys(): log.warning(" Series "+Fg_in+" not found in data file") return Fn,f,a = qcutils.GetSeriesasMA(ds,Fn_in) Fg,f,a = qcutils.GetSeriesasMA(ds,Fg_in) Fa_calc = Fn - Fg if Fa_out not in ds.series.keys(): attr = qcutils.MakeAttributeDictionary(long_name='Available energy using '+Fn_in+','+Fg_in,units='W/m2') qcutils.CreateSeries(ds,Fa_out,Fa_calc,FList=[Fn_in,Fg_in],Attr=attr) else: Fa_exist,flag,attr = qcutils.GetSeriesasMA(ds,Fa_out) idx = numpy.where((numpy.ma.getmaskarray(Fa_exist)==True)&(numpy.ma.getmaskarray(Fa_calc)==False))[0] if len(idx)!=0: Fa_exist[idx] = Fa_calc[idx] flag[idx] = numpy.int32(20) qcutils.CreateSeries(ds,Fa_out,Fa_exist,Flag=flag,Attr=attr) def CalculateFluxes(cf,ds): """ Calculate the fluxes from the rotated covariances. Usage qcts.CalculateFluxes(ds) ds: data structure Pre-requisite: CoordRotation2D Accepts meteorological constants or variables """ Ta,f,a = qcutils.GetSeriesasMA(ds,"Ta") ps,f,a = qcutils.GetSeriesasMA(ds,"ps") Ah,f,a = qcutils.GetSeriesasMA(ds,"Ah") rhom,f,a = qcutils.GetSeriesasMA(ds,"rhom") RhoCp,f,a = qcutils.GetSeriesasMA(ds,"RhoCp") Lv,f,a = qcutils.GetSeriesasMA(ds,"Lv") long_name = '' if 'Massman' in ds.globalattributes['Functions']: long_name = ' and frequency response corrected' log.info(" Calculating fluxes from covariances") if "wT" in ds.series.keys(): ok_units = ["mC/s","Cm/s"] wT,flag,attr = qcutils.GetSeriesasMA(ds,"wT") if attr["units"] in ok_units: Fhv = RhoCp*wT attr["long_name"] = "Virtual heat flux, rotated to natural wind coordinates"+long_name attr["units"] = "W/m2" qcutils.CreateSeries(ds,"Fhv",Fhv,Flag=flag,Attr=attr) else: log.error(" CalculateFluxes: Incorrect units for wA, Fe not calculated") else: log.error(" CalculateFluxes: wT not found, Fh not calculated") if "wA" in ds.series.keys(): wA,flag,attr = qcutils.GetSeriesasMA(ds,"wA") if attr["units"]=="g/m2/s": Fe = Lv*wA/float(1000) attr["long_name"] = "Latent heat flux, rotated to natural wind coordinates"+long_name attr["standard_name"] = "surface_upward_latent_heat_flux" attr["units"] = "W/m2" qcutils.CreateSeries(ds,"Fe",Fe,Flag=flag,Attr=attr) else: log.error(" CalculateFluxes: Incorrect units for wA, Fe not calculated") else: log.error(" CalculateFluxes: wA not found, Fe not calculated") if "wC" in ds.series.keys(): wC,flag,attr = qcutils.GetSeriesasMA(ds,"wC") if attr["units"]=="mg/m2/s": Fc = wC attr["long_name"] = "CO2 flux, rotated to natural wind coordinates"+long_name attr["units"] = "mg/m2/s" qcutils.CreateSeries(ds,"Fc",Fc,Flag=flag,Attr=attr) else: log.error(" CalculateFluxes: Incorrect units for wC, Fc not calculated") else: log.error(" CalculateFluxes: wC not found, Fc not calculated") if "uw" in ds.series.keys(): if "vw" in ds.series.keys(): uw,f,a = qcutils.GetSeriesasMA(ds,"uw") vw,f,a = qcutils.GetSeriesasMA(ds,"vw") vs = uw*uw + vw*vw Fm = rhom*numpy.ma.sqrt(vs) us = numpy.ma.sqrt(numpy.ma.sqrt(vs)) attr["long_name"] = "Momentum flux, rotated to natural wind coordinates"+long_name attr["units"] = "kg/m/s2" qcutils.CreateSeries(ds,"Fm",Fm,FList=["uw","vw"],Attr=attr) attr["long_name"] = "Friction velocity, rotated to natural wind coordinates"+long_name attr["units"] = "m/s" qcutils.CreateSeries(ds,"ustar",us,FList=["uw","vw"],Attr=attr) else: log.error(" CalculateFluxes: vw not found, Fm and ustar not calculated") else: log.error(" CalculateFluxes: uw not found, Fm and ustar not calculated") if 'CalculateFluxes' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', CalculateFluxes' def CalculateLongwave(ds,Fl_out,Fl_in,Tbody_in): """ Calculate the longwave radiation given the raw thermopile output and the sensor body temperature. Usage qcts.CalculateLongwave(ds,Fl_out,Fl_in,Tbody_in) ds: data structure Fl_out: output longwave variable to ds. Example: 'Flu' Fl_in: input longwave in ds. Example: 'Flu_raw' Tbody_in: input sensor body temperature in ds. Example: 'Tbody' """ log.info(' Calculating longwave radiation') Fl_raw,f,a = qcutils.GetSeriesasMA(ds,Fl_in) Tbody,f,a = qcutils.GetSeriesasMA(ds,Tbody_in) Fl = Fl_raw + c.sb*(Tbody + 273.15)**4 attr = qcutils.MakeAttributeDictionary(long_name='Calculated longwave radiation using '+Fl_in+','+Tbody_in,units='W/m2') qcutils.CreateSeries(ds,Fl_out,Fl,FList=[Fl_in,Tbody_in],Attr=attr) def CalculateHumidities(ds): """ Purpose: Calculate any missing humidities from whatever is available. If absolute humidity (Ah) is available then; - calculate specific humidity (q) if it is not present - calculate relative humidity (RH) if it is not present If specific humidity (q) is available then; - calculate absolute humidity (Ah) if it is not present - calculate relative humidity (RH) if it is not present If reative humidity (RH) is available then; - calculate specific humidity (q) if it is not present - calculate relative humidity (RH) if it is not present Usage: qcts.CalculateHumidities(ds) Date: March 2015 Author: PRI """ if "Ah" not in ds.series.keys(): if "q" in ds.series.keys(): AbsoluteHumidityFromq(ds) # calculate Ah from q elif "RH" in ds.series.keys(): AbsoluteHumidityFromRH(ds) # calculate Ah from RH if "q" not in ds.series.keys(): if "Ah" in ds.series.keys(): SpecificHumidityFromAh(ds) elif "RH" in ds.series.keys(): SpecificHumidityFromRH(ds) if "RH" not in ds.series.keys(): if "Ah" in ds.series.keys(): RelativeHumidityFromAh(ds) elif "q" in ds.series.keys(): RelativeHumidityFromq(ds) def CalculateHumiditiesAfterGapFill(ds): """ Purpose: Check to see which humidity quantities (Ah, RH or q) have been gap filled and, if necessary, calculate the other humidity quantities from the gap filled one. Usage: qcts.CalculateHumiditiesAfterGapFill(ds) where ds is a data structure Author: PRI Date: April 2015 """ # create an empty list alt_list = [] # check to see if there was any gap filling using data from alternate sources if "alternate" in dir(ds): # if so, get a list of the quantities gap filled from alternate sources alt_list = list(set([ds.alternate[item]["label_tower"] for item in ds.alternate.keys()])) # create an empty list cli_list = [] # check to see if there was any gap filling from climatology if "climatology" in dir(ds): # if so, get a list of the quantities gap filled using climatology cli_list = list(set([ds.climatology[item]["label_tower"] for item in ds.climatology.keys()])) # one list to rule them, one list to bind them ... gf_list = list(set(alt_list+cli_list)) # clear out if there was no gap filling if len(gf_list)==0: return # check to see if absolute humidity (Ah) was gap filled ... if "Ah" in gf_list: if "q" not in gf_list: SpecificHumidityFromAh(ds) if "RH" not in gf_list: RelativeHumidityFromAh(ds) # ... or was relative humidity (RH) gap filled ... elif "RH" in gf_list: if "Ah" not in gf_list: AbsoluteHumidityFromRH(ds) if "q" not in gf_list: SpecificHumidityFromRH(ds) # ... or was specific humidity (q) gap filled ... elif "q" in gf_list: if "Ah" not in gf_list: AbsoluteHumidityFromq(ds) if "RH" not in gf_list: RelativeHumidityFromq(ds) else: msg = "No humidities were gap filled!" log.warning(msg) def AbsoluteHumidityFromRH(ds): """ Calculate absolute humidity from relative humidity. """ log.info(' Calculating absolute humidity from relative humidity') Ta,Ta_flag,a = qcutils.GetSeriesasMA(ds,"Ta") RH,RH_flag,a = qcutils.GetSeriesasMA(ds,"RH") Ah_new_flag = qcutils.MergeQCFlag([Ta_flag,RH_flag]) Ah_new = mf.absolutehumidityfromRH(Ta,RH) if "Ah" in ds.series.keys(): Ah,Ah_flag,Ah_attr = qcutils.GetSeriesasMA(ds,"Ah") index = numpy.where(numpy.ma.getmaskarray(Ah)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(Ah)==True)[0] Ah[index] = Ah_new[index] Ah_flag[index] = Ah_new_flag[index] Ah_attr["long_name"] = Ah_attr["long_name"]+", merged with Ah calculated from RH" qcutils.CreateSeries(ds,"Ah",Ah,Flag=Ah_flag,Attr=Ah_attr) else: attr = qcutils.MakeAttributeDictionary(long_name='Absolute humidity',units='g/m3',standard_name='mass_concentration_of_water_vapor_in_air') qcutils.CreateSeries(ds,'Ah',Ah_new,Flag=Ah_new_flag,Attr=attr) def AbsoluteHumidityFromq(ds): """ Calculate absolute humidity from specific humidity. """ log.info(' Calculating absolute humidity from specific humidity') Ta,Ta_flag,a = qcutils.GetSeriesasMA(ds,"Ta") ps,ps_flag,a = qcutils.GetSeriesasMA(ds,"ps") q,q_flag,a = qcutils.GetSeriesasMA(ds,"q") Ah_new_flag = qcutils.MergeQCFlag([Ta_flag,ps_flag,q_flag]) RH = mf.RHfromspecifichumidity(q,Ta,ps) Ah_new = mf.absolutehumidityfromRH(Ta,RH) if "Ah" in ds.series.keys(): Ah,Ah_flag,Ah_attr = qcutils.GetSeriesasMA(ds,"Ah") index = numpy.where(numpy.ma.getmaskarray(Ah)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(Ah)==True)[0] Ah[index] = Ah_new[index] Ah_flag[index] = Ah_new_flag[index] Ah_attr["long_name"] = Ah_attr["long_name"]+", merged with Ah calculated from q" qcutils.CreateSeries(ds,"Ah",Ah,Flag=Ah_flag,Attr=Ah_attr) else: attr = qcutils.MakeAttributeDictionary(long_name='Absolute humidity',units='g/m3',standard_name='mass_concentration_of_water_vapor_in_air') qcutils.CreateSeries(ds,"Ah",Ah_new,Flag=Ah_new_flag,Attr=attr) def RelativeHumidityFromq(ds): """ Calculate relative humidity from specific humidity. """ log.info(' Calculating relative humidity from specific humidity') Ta,Ta_flag,a = qcutils.GetSeriesasMA(ds,"Ta") ps,ps_flag,a = qcutils.GetSeriesasMA(ds,"ps") q,q_flag,a = qcutils.GetSeriesasMA(ds,"q") RH_new_flag = qcutils.MergeQCFlag([Ta_flag,ps_flag,q_flag]) RH_new = mf.RHfromspecifichumidity(q,Ta,ps) if "RH" in ds.series.keys(): RH,RH_flag,RH_attr = qcutils.GetSeriesasMA(ds,"RH") index = numpy.where(numpy.ma.getmaskarray(RH)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(RH)==True)[0] RH[index] = RH_new[index] RH_flag[index] = RH_new_flag[index] RH_attr["long_name"] = RH_attr["long_name"]+", merged with RH calculated from q" qcutils.CreateSeries(ds,"RH",RH,Flag=RH_flag,Attr=RH_attr) else: attr = qcutils.MakeAttributeDictionary(long_name='Relative humidity',units='%',standard_name='relative_humidity') qcutils.CreateSeries(ds,'RH',RH_new,Flag=RH_new_flag,Attr=attr) def RelativeHumidityFromAh(ds): """ Calculate relative humidity from absolute humidity. """ log.info(' Calculating relative humidity from absolute humidity') Ta,Ta_flag,a = qcutils.GetSeriesasMA(ds,"Ta") Ah,Ah_flag,a = qcutils.GetSeriesasMA(ds,"Ah") RH_new_flag = qcutils.MergeQCFlag([Ta_flag,Ah_flag]) RH_new = mf.RHfromabsolutehumidity(Ah,Ta) # relative humidity in units of percent if "RH" in ds.series.keys(): RH,RH_flag,RH_attr = qcutils.GetSeriesasMA(ds,"RH") index = numpy.where(numpy.ma.getmaskarray(RH)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(RH)==True)[0] RH[index] = RH_new[index] RH_flag[index] = RH_new_flag[index] RH_attr["long_name"] = RH_attr["long_name"]+", merged with RH calculated from Ah" qcutils.CreateSeries(ds,"RH",RH,Flag=RH_flag,Attr=RH_attr) else: attr = qcutils.MakeAttributeDictionary(long_name='Relative humidity',units='%',standard_name='relative_humidity') qcutils.CreateSeries(ds,"RH",RH_new,Flag=RH_new_flag,Attr=attr) def smooth(x,window_len=11,window='hanning'): """ Purpose: Smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. Input: x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. Output: the smoothed signal Example: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) See also: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string Note: 1) length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y. 2) odd values for window_len return output with different length from input Source: Lifted from scipy Cookbook (http://wiki.scipy.org/Cookbook/SignalSmooth) """ if x.ndim != 1: raise ValueError, "smooth only accepts 1 dimension arrays." if x.size < window_len: raise ValueError, "Input vector needs to be bigger than window size." if window_len<3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" s=numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]] if window == 'flat': #moving average w=numpy.ones(window_len,'d') else: w=eval('numpy.'+window+'(window_len)') y=numpy.convolve(w/w.sum(),s,mode='valid') # return y return y[(window_len/2-1):-(window_len/2)] def SpecificHumidityFromAh(ds): """ Calculate specific humidity from absolute humidity. """ log.info(' Calculating specific humidity from absolute humidity') Ta,Ta_flag,a = qcutils.GetSeriesasMA(ds,"Ta") ps,ps_flag,a = qcutils.GetSeriesasMA(ds,"ps") Ah,Ah_flag,a = qcutils.GetSeriesasMA(ds,"Ah") q_new_flag = qcutils.MergeQCFlag([Ta_flag,ps_flag,Ah_flag]) RH = mf.RHfromabsolutehumidity(Ah,Ta) q_new = mf.specifichumidityfromRH(RH, Ta, ps) if "q" in ds.series.keys(): q,q_flag,q_attr = qcutils.GetSeriesasMA(ds,"q") index = numpy.where(numpy.ma.getmaskarray(q)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(q)==True)[0] q[index] = q_new[index] q_flag[index] = q_new_flag[index] q_attr["long_name"] = q_attr["long_name"]+", merged with q calculated from Ah" qcutils.CreateSeries(ds,"q",q,Flag=q_flag,Attr=q_attr) else: attr = qcutils.MakeAttributeDictionary(long_name='Specific humidity',units='kg/kg',standard_name='specific_humidity') qcutils.CreateSeries(ds,'q',q_new,Flag=q_new_flag,Attr=attr) def SpecificHumidityFromRH(ds): """ Calculate specific humidity from relative humidity.""" log.info(' Calculating specific humidity from relative humidity') Ta,Ta_flag,a = qcutils.GetSeriesasMA(ds,"Ta") ps,ps_flag,a = qcutils.GetSeriesasMA(ds,"ps") RH,RH_flag,a = qcutils.GetSeriesasMA(ds,"RH") q_new_flag = qcutils.MergeQCFlag([Ta_flag,ps_flag,RH_flag]) q_new = mf.specifichumidityfromRH(RH,Ta,ps) # specific humidity in units of kg/kg if "q" in ds.series.keys(): q,q_flag,q_attr = qcutils.GetSeriesasMA(ds,"q") index = numpy.where(numpy.ma.getmaskarray(q)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(q)==True)[0] q[index] = q_new[index] q_flag[index] = q_new_flag[index] q_attr["long_name"] = q_attr["long_name"]+", merged with q calculated from RH" qcutils.CreateSeries(ds,"q",q,Flag=q_flag,Attr=q_attr) else: attr = qcutils.MakeAttributeDictionary(long_name='Specific humidity',units='kg/kg',standard_name='specific_humidity') qcutils.CreateSeries(ds,"q",q_new,Flag=q_new_flag,Attr=attr) def CalculateMeteorologicalVariables(ds,Ta_name='Ta',Tv_name='Tv_CSAT',ps_name='ps', q_name="q",Ah_name='Ah',RH_name='RH'): """ Add time series of meteorological variables based on fundamental relationships (Stull 1988) Usage qcts.CalculateMeteorologicalVariables(ds,Ta_name,ps_name,Ah_name) ds: data structure Ta_name: data series name for air temperature ps_name: data series name for pressure Ah_name: data series name for absolute humidity q_name : data series name for specific humidity RH_name: data series for relative humidity Variables added: rhom: density of moist air, mf.densitymoistair(Ta,ps,Ah) Lv: latent heat of vapourisation, mf.Lv(Ta) q: specific humidity, mf.specifichumidity(mr) where mr (mixing ratio) = mf.mixingratio(ps,vp) Cpm: specific heat of moist air, mf.specificheatmoistair(q) VPD: vapour pressure deficit, VPD = esat - e """ for item in [Ta_name,ps_name,Ah_name,q_name]: if item not in ds.series.keys(): msg = " CalculateMeteorologicalVariables: series " msg = msg + item + " not found, returning ..." log.warning(msg) return log.info(' Adding standard met variables to database') # get the required data series Ta,f,a = qcutils.GetSeriesasMA(ds,Ta_name) # use Tv_CSAT if it is in the data structure, otherwise use Ta if Tv_name not in ds.series.keys(): Tv_name = Ta_name Tv,f,a = qcutils.GetSeriesasMA(ds,Tv_name) ps,f,a = qcutils.GetSeriesasMA(ds,ps_name) Ah,f,a = qcutils.GetSeriesasMA(ds,Ah_name) q,f,a = qcutils.GetSeriesasMA(ds,q_name) # do the calculations e = mf.vapourpressure(Ah,Ta) # vapour pressure from absolute humidity and temperature esat = mf.es(Ta) # saturation vapour pressure rhod = mf.densitydryair(Ta,ps,e) # partial density of dry air rhom = mf.densitymoistair(Ta,ps,e) # density of moist air rhow = mf.densitywatervapour(Ta,e) # partial density of water vapour Lv = mf.Lv(Ta) # latent heat of vapourisation mr = mf.mixingratio(ps,e) # mixing ratio mrsat = mf.mixingratio(ps,esat) # saturation mixing ratio qsat = mf.specifichumidity(mrsat) # saturation specific humidity from saturation mixing ratio Cpd = mf.specificheatcapacitydryair(Tv) Cpw = mf.specificheatcapacitywatervapour(Ta,Ah) RhoCp = mf.densitytimesspecificheat(rhow,Cpw,rhod,Cpd) Cpm = mf.specificheatmoistair(q) # specific heat of moist air VPD = esat - e # vapour pressure deficit SHD = qsat - q # specific humidity deficit # write the meteorological series to the data structure attr = qcutils.MakeAttributeDictionary(long_name='Vapour pressure',units='kPa',standard_name='water_vapor_partial_pressure_in_air') qcutils.CreateSeries(ds,'e',e,FList=[Ta_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Saturation vapour pressure',units='kPa') qcutils.CreateSeries(ds,'esat',esat,FList=[Ta_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Density of dry air',units='kg/m3') qcutils.CreateSeries(ds,'rhod',rhod,FList=[Ta_name,ps_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Density of moist air',units='kg/m3',standard_name='air_density') qcutils.CreateSeries(ds,'rhom',rhom,FList=[Ta_name,ps_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Partial density of water vapour',units='kg/m3') qcutils.CreateSeries(ds,'rhow',rhow,FList=[Ta_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Latent heat of vapourisation',units='J/kg') qcutils.CreateSeries(ds,'Lv',Lv,FList=[Ta_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Specific heat capacity of dry air',units='J/kg-K') qcutils.CreateSeries(ds,'Cpd',Cpd,FList=[Tv_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Specific heat capacity of water vapour',units='J/kg-K') qcutils.CreateSeries(ds,'Cpw',Cpw,FList=[Ta_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Specific heat capacity of moist air',units='J/kg-K') qcutils.CreateSeries(ds,'Cpm',Cpm,FList=[Ta_name,ps_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Product of air density and specific heat capacity',units='J/m3-K') qcutils.CreateSeries(ds,'RhoCp',RhoCp,FList=[Ta_name,Tv_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Vapour pressure deficit',units='kPa',standard_name='water_vapor_saturation_deficit_in_air') qcutils.CreateSeries(ds,'VPD',VPD,FList=[Ta_name,Ah_name],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Specific humidity deficit',units='kg/kg') qcutils.CreateSeries(ds,'SHD',SHD,FList=[Ta_name,Ah_name],Attr=attr) if 'CalculateMetVars' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', CalculateMetVars' def CalculateNetRadiation(cf,ds,Fn_out='Fn',Fsd_in='Fsd',Fsu_in='Fsu',Fld_in='Fld',Flu_in='Flu'): """ Purpose: Calculate the net radiation from the 4 components of the surface radiation budget. Usage: qcts.CalculateNetRadiation(cf,ds,Fn_out,Fsd_in,Fsu_in,Fld_in,Flu_in) cf: control file ds: data structure Fn_out: output net radiation variable to ds. Example: 'Fn_KZ' Fsd_in: input downwelling solar radiation in ds. Example: 'Fsd' Fsu_in: input upwelling solar radiation in ds. Example: 'Fsu' Fld_in: input downwelling longwave radiation in ds. Example: 'Fld' Flu_in: input upwelling longwave radiation in ds. Example: 'Flu' Side effects: Creates a new series in the data structure containing the net radiation. Author: PRI Date: Sometime early on """ log.info(' Calculating net radiation from 4 components') if Fsd_in in ds.series.keys() and Fsu_in in ds.series.keys() and Fld_in in ds.series.keys() and Flu_in in ds.series.keys(): Fsd,f,a = qcutils.GetSeriesasMA(ds,Fsd_in) Fsu,f,a = qcutils.GetSeriesasMA(ds,Fsu_in) Fld,f,a = qcutils.GetSeriesasMA(ds,Fld_in) Flu,f,a = qcutils.GetSeriesasMA(ds,Flu_in) Fn_calc = (Fsd - Fsu) + (Fld - Flu) if Fn_out not in ds.series.keys(): attr = qcutils.MakeAttributeDictionary(long_name='Calculated net radiation using '+Fsd_in+','+Fsu_in+','+Fld_in+','+Flu_in, standard_name='surface_net_downwawrd_radiative_flux',units='W/m2') qcutils.CreateSeries(ds,Fn_out,Fn_calc,FList=[Fsd_in,Fsu_in,Fld_in,Flu_in],Attr=attr) else: Fn_exist,flag,attr = qcutils.GetSeriesasMA(ds,Fn_out) idx = numpy.where((numpy.ma.getmaskarray(Fn_exist)==True)&(numpy.ma.getmaskarray(Fn_calc)==False))[0] #idx = numpy.ma.where((numpy.ma.getmaskarray(Fn_exist)==True)&(numpy.ma.getmaskarray(Fn_calc)==False))[0] if len(idx)!=0: Fn_exist[idx] = Fn_calc[idx] flag[idx] = numpy.int32(20) qcutils.CreateSeries(ds,Fn_out,Fn_exist,Flag=flag,Attr=attr) else: nRecs = int(ds.globalattributes['nc_nrecs']) Fn = numpy.array([c.missing_value]*nRecs,dtype=numpy.float64) flag = numpy.ones(nRecs,dtype=numpy.int32) attr = qcutils.MakeAttributeDictionary(long_name='Calculated net radiation (one or more components missing)', standard_name='surface_net_downwawrd_radiative_flux',units='W/m2') qcutils.CreateSeries(ds,Fn_out,Fn,Flag=flag,Attr=attr) def CheckCovarianceUnits(ds): """ Purpose: Usage: Author: PRI Date: September 2015 """ log.info(' Checking covariance units') co2_list = ["UxC","UyC","UzC"] h2o_list = ["UxA","UyA","UzA","UxH","UyH","UzH"] for item in co2_list: if item not in ds.series.keys(): continue data,flag,attr = qcutils.GetSeriesasMA(ds,item) if "umol" in attr["units"]: Ta,f,a = qcutils.GetSeriesasMA(ds,"Ta") ps,f,a = qcutils.GetSeriesasMA(ds,"ps") data = mf.co2_mgpm3fromppm(data,Ta,ps) attr["units"] = "mg/m2/s" qcutils.CreateSeries(ds,item,data,Flag=flag,Attr=attr) for item in h2o_list: if item not in ds.series.keys(): continue data,flag,attr = qcutils.GetSeriesasMA(ds,item) if "mmol" in attr["units"]: Ta,f,a = qcutils.GetSeriesasMA(ds,"Ta") ps,f,a = qcutils.GetSeriesasMA(ds,"ps") data = mf.h2o_gpm3frommmolpmol(data,Ta,ps) attr["units"] = "g/m2/s" if "H" in item: item = item.replace("H","A") qcutils.CreateSeries(ds,item,data,Flag=flag,Attr=attr) def CoordRotation2D(cf,ds): """ 2D coordinate rotation to force v = w = 0. Based on Lee et al, Chapter 3 of Handbook of Micrometeorology. This routine does not do the third rotation to force v'w' = 0. Usage qcts.CoordRotation2D(ds) ds: data structure """ # get the raw wind velocity components Ux,f,a = qcutils.GetSeriesasMA(ds,'Ux') # longitudinal component in CSAT coordinate system Uy,f,a = qcutils.GetSeriesasMA(ds,'Uy') # lateral component in CSAT coordinate system Uz,f,a = qcutils.GetSeriesasMA(ds,'Uz') # vertical component in CSAT coordinate system # get the raw covariances UxUz,f,UxUz_a = qcutils.GetSeriesasMA(ds,'UxUz') # covariance(Ux,Uz) UyUz,f,UyUz_a = qcutils.GetSeriesasMA(ds,'UyUz') # covariance(Uy,Uz) UxUy,f,a = qcutils.GetSeriesasMA(ds,'UxUy') # covariance(Ux,Uy) UyUy,f,a = qcutils.GetSeriesasMA(ds,'UyUy') # variance(Uy) UxUx,f,a = qcutils.GetSeriesasMA(ds,'UxUx') # variance(Ux) UzUz,f,a = qcutils.GetSeriesasMA(ds,'UzUz') # variance(Ux) UzC,f,UzC_a = qcutils.GetSeriesasMA(ds,'UzC') # covariance(Uz,C) UzA,f,UzA_a = qcutils.GetSeriesasMA(ds,'UzA') # covariance(Uz,A) UzT,f,UzT_a = qcutils.GetSeriesasMA(ds,'UzT') # covariance(Uz,T) UxC,f,a = qcutils.GetSeriesasMA(ds,'UxC') # covariance(Ux,C) UyC,f,a = qcutils.GetSeriesasMA(ds,'UyC') # covariance(Uy,C) UxA,f,a = qcutils.GetSeriesasMA(ds,'UxA') # covariance(Ux,A) UyA,f,a = qcutils.GetSeriesasMA(ds,'UyA') # covariance(Ux,A) UxT,f,a = qcutils.GetSeriesasMA(ds,'UxT') # covariance(Ux,T) UyT,f,a = qcutils.GetSeriesasMA(ds,'UyT') # covariance(Uy,T) nRecs = int(ds.globalattributes['nc_nrecs']) # number of records # get the instrument heights fm_height = "not defined" if "height" in UxUz_a: fm_height = UxUz_a["height"] fc_height = "not defined" if "height" in UzC_a: fc_height = UzC_a["height"] fe_height = "not defined" if "height" in UzA_a: fe_height = UzA_a["height"] fh_height = "not defined" if "height" in UzT_a: fh_height = UzT_a["height"] # apply 2D coordinate rotation unless otherwise specified in control file rotate = True if ('Options' in cf) and ('2DCoordRotation' in cf['Options'].keys()): if not cf['Options'].as_bool('2DCoordRotation'): rotate = False if rotate: log.info(' Applying 2D coordinate rotation (components and covariances)') # get the 2D and 3D wind speeds ws2d = numpy.ma.sqrt(Ux**2 + Uy**2) ws3d = numpy.ma.sqrt(Ux**2 + Uy**2 + Uz**2) # get the sine and cosine of the angles through which to rotate # - first we rotate about the Uz axis by eta to get v = 0 # - then we rotate about the v axis by theta to get w = 0 ce = Ux/ws2d # cos(eta) se = Uy/ws2d # sin(eta) ct = ws2d/ws3d # cos(theta) st = Uz/ws3d # sin(theta) # get the rotation angles theta = numpy.rad2deg(numpy.arctan2(st,ct)) eta = numpy.rad2deg(numpy.arctan2(se,ce)) # do the wind velocity components first u = Ux*ct*ce + Uy*ct*se + Uz*st # longitudinal component in natural wind coordinates v = Uy*ce - Ux*se # lateral component in natural wind coordinates w = Uz*ct - Ux*st*ce - Uy*st*se # vertical component in natural wind coordinates # do the variances uu = UxUx*ct**2*ce**2 + UyUy*ct**2*se**2 + UzUz*st**2 + 2*UxUy*ct**2*ce*se + 2*UxUz*ct*st*ce + 2*UyUz*ct*st*se vv = UyUy*ce**2 + UxUx*se**2 - 2*UxUy*ce*se ww = UzUz*ct**2 + UxUx*st**2*ce**2 + UyUy*st**2*se**2 - 2*UxUz*ct*st*ce - 2*UyUz*ct*st*se + 2*UxUy*st**2*ce*se # now do the scalar covariances wT = UzT*ct - UxT*st*ce - UyT*st*se # covariance(w,T) in natural wind coordinate system wA = UzA*ct - UxA*st*ce - UyA*st*se # covariance(w,A) in natural wind coordinate system wC = UzC*ct - UxC*st*ce - UyC*st*se # covariance(w,C) in natural wind coordinate system # now do the momentum covariances # full equations, Wesely PhD thesis via James Cleverly and EddyPro uw = UxUz*ce*(ct*ct-st*st) - 2*UxUy*ct*st*ce*se + UyUz*se*(ct*ct-st*st) - \ UxUx*ct*st*ce*ce - UyUy*ct*st*se*se + UzUz*ct*st # covariance(w,x) in natural wind coordinate system uv = UxUy*ct*(ce*ce-se*se) + UyUz*st*ce - UxUz*st*se - \ UxUx*ct*ce*se + UyUy*ct*ce*se # covariance(x,y) in natural wind coordinate system vw = UyUz*ct*ce - UxUz*ct*se - UxUy*st*(ce*ce-se*se) + \ UxUx*st*ce*se - UyUy*st*ce*se # covariance(w,y) in natural wind coordinate system else: log.info(' 2D coordinate rotation disabled, using unrotated components and covariances') # dummy series for rotation angles theta = numpy.zeros(nRecs) eta = numpy.zeros(nRecs) # unrotated wind components u = Ux # unrotated x xomponent v = Uy # unrotated y xomponent w = Uz # unrotated z xomponent # unrotated covariances wT = UzT # unrotated wT covariance wA = UzA # unrotated wA covariance wC = UzC # unrotated wC covariance uw = UxUz # unrotated uw covariance vw = UyUz # unrotated vw covariance uv = UxUy # unrotated uv covariance # unrotated variances uu = UxUx # unrotated u variance vv = UyUy # unrotated v variance ww = UzUz # unrotated w variance # store the rotated quantities in the nc object # default behaviour of CreateSeries is to use the maximum value of the QC flag for any series specified in FList attr = qcutils.MakeAttributeDictionary(long_name='Horizontal rotation angle',units='deg',height=fm_height) qcutils.CreateSeries(ds,'eta',eta,FList=['Ux','Uy','Uz'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Vertical rotation angle',units='deg',height=fm_height) qcutils.CreateSeries(ds,'theta',theta,FList=['Ux','Uy','Uz'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Longitudinal component of wind-speed in natural wind coordinates', units='m/s',height=fm_height) qcutils.CreateSeries(ds,'u',u,FList=['Ux','Uy','Uz'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Lateral component of wind-speed in natural wind coordinates', units='m/s',height=fm_height) qcutils.CreateSeries(ds,'v',v,FList=['Ux','Uy','Uz'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Vertical component of wind-speed in natural wind coordinates', units='m/s',height=fm_height) qcutils.CreateSeries(ds,'w',w,FList=['Ux','Uy','Uz'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Kinematic heat flux, rotated to natural wind coordinates', units='mC/s',height=fh_height) qcutils.CreateSeries(ds,'wT',wT,FList=['Ux','Uy','Uz','UxT','UyT','UzT'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Kinematic vapour flux, rotated to natural wind coordinates', units='g/m2/s',height=fe_height) qcutils.CreateSeries(ds,'wA',wA,FList=['Ux','Uy','Uz','UxA','UyA','UzA'],Attr=attr) #ReplaceRotatedCovariance(cf,ds,'wA','UzA') attr = qcutils.MakeAttributeDictionary(long_name='Kinematic CO2 flux, rotated to natural wind coordinates', units='mg/m2/s',height=fc_height) qcutils.CreateSeries(ds,'wC',wC,FList=['Ux','Uy','Uz','UxC','UyC','UzC'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Momentum flux X component, corrected to natural wind coordinates', units='m2/s2',height=fm_height) qcutils.CreateSeries(ds,'uw',uw,FList=['Ux','Uy','Uz','UxUz','UxUx','UxUy'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Horizontal streamwise-crosswind covariance, rotated to natural wind coordinates', units='m2/s2',height=fm_height) qcutils.CreateSeries(ds,'uv',uv,FList=['Ux','Uy','Uz','UxUz','UxUx','UxUy'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Momentum flux Y component, corrected to natural wind coordinates', units='m2/s2',height=fm_height) qcutils.CreateSeries(ds,'vw',vw,FList=['Ux','Uy','Uz','UyUz','UxUy','UyUy'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Variance of streamwise windspeed, rotated to natural wind coordinates', units='m2/s2',height=fm_height) qcutils.CreateSeries(ds,'uu',uu,FList=['Ux','Uy','Uz','UxUx','UxUy','UxUz'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Variance of crossstream windspeed, rotated to natural wind coordinates', units='m2/s2',height=fm_height) qcutils.CreateSeries(ds,'vv',vv,FList=['Ux','Uy','Uz','UyUy','UxUy'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Variance of vertical windspeed, rotated to natural wind coordinates', units='m2/s2',height=fm_height) qcutils.CreateSeries(ds,'ww',ww,FList=['Ux','Uy','Uz','UzUz','UxUz','UyUz'],Attr=attr) # if RotateFlag is set, force the QC flag value from the maximum of the FList series to 11 #if qcutils.cfkeycheck(cf,Base='General',ThisOne='RotateFlag') and cf['General']['RotateFlag'] == 'True': #keys = ['eta','theta','u','v','w','wT','wA','wC','uw','vw'] #for ThisOne in keys: #testseries,f = qcutils.GetSeriesasMA(ds,ThisOne) #mask = numpy.ma.getmask(testseries) #index = numpy.where(mask.astype(int)==1) #ds.series[ThisOne]['Flag'][index] = numpy.int32(11) if 'CoordRotation2D' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', CoordRotation2D' if qcutils.cfoptionskeylogical(cf,Key='RelaxRotation'): RotatedSeriesList = ['wT','wA','wC','uw','vw'] NonRotatedSeriesList = ['UzT','UzA','UzC','UxUz','UyUz'] for ThisOne, ThatOne in zip(RotatedSeriesList,NonRotatedSeriesList): ReplaceWhereMissing(ds.series[ThisOne],ds.series[ThisOne],ds.series[ThatOne],FlagValue=21) if 'RelaxRotation' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', RelaxRotation' def CalculateComponentsFromWsWd(ds): """ Purpose: Calculate U (positive east) and V (positive north) from wind speed and direction and put the components into the data structure. Usage: qcts.CalculateComponentsFromWsWd(ds) Author: PRI/WW/MK/EvG Date: July 2016 """ Wd,Wd_flag,attr = qcutils.GetSeriesasMA(ds,"Wd") Ws,Ws_flag,attr = qcutils.GetSeriesasMA(ds,"Ws") u,v = qcutils.convert_WsWdtoUV(Ws,Wd) u_attr = qcutils.MakeAttributeDictionary(long_name="U component of wind in meteorological coordinates (positive east)") v_attr = qcutils.MakeAttributeDictionary(long_name="V component of wind in meteorological coordinates (positive north)") qcutils.CreateSeries(ds,"U",u,Flag=Wd_flag,Attr=u_attr) qcutils.CreateSeries(ds,"V",v,Flag=Wd_flag,Attr=v_attr) def CalculateFcStorage(cf,ds,Fc_out='Fc_storage',CO2_in='Cc'): """ Calculate CO2 flux storage term in the air column beneath the CO2 instrument. This routine assumes the air column between the sensor and the surface is well mixed. Usage qcts.CalculateFcStorage(cf,ds,Fc_out,CO2_in) cf: control file object ds: data structure Fc_out: series label of the CO2 flux storage term CO2_in: series label of the CO2 concentration Parameters loaded from control file: zms: measurement height from surface, m """ if 'Fc_storage' not in ds.series.keys(): if qcutils.cfkeycheck(cf,Base='General',ThisOne='zms'): log.info(' Calculating Fc storage (single height)') nRecs = int(ds.globalattributes['nc_nrecs']) ts = int(ds.globalattributes['time_step']) zms = float(cf['General']['zms']) # get the input data Cc,Cc_flag,Cc_attr = qcutils.GetSeriesasMA(ds,CO2_in,si=0,ei=-1) Ta,f,a = qcutils.GetSeriesasMA(ds,'Ta',si=0,ei=-1) ps,f,a = qcutils.GetSeriesasMA(ds,'ps',si=0,ei=-1) # check the CO2 concentration units # if the units are mg/m3, convert CO2 concentration to umol/mol before taking the difference if Cc_attr['units']=='mg/m3': Cc = mf.co2_ppmfrommgpm3(Cc,Ta,ps) # calculate the change in CO2 concentration between time steps, CO2 concentration in umol/mol. dc = numpy.ma.ediff1d(Cc,to_begin=0) # convert the CO2 concentration difference from umol/mol to mg/m3 dc = mf.co2_mgpm3fromppm(dc,Ta,ps) # calculate the time step in seconds dt=86400*numpy.ediff1d(ds.series['xlDateTime']['Data'],to_begin=float(ts)/1440) # time step in seconds from the Excel datetime values # calculate the CO2 flux based on storage below the measurement height Fc_storage = zms*dc/dt Fc_storage_units = 'mg/m2/s' descr = 'Fc infered from CO2 storage using single point CO2 measurement' # make the output series attribute dictionary attr_out = qcutils.MakeAttributeDictionary(long_name=descr,units=Fc_storage_units) # put the storage flux in the data structure qcutils.CreateSeries(ds,Fc_out,Fc_storage,FList=[CO2_in],Attr=attr_out) else: log.error('CalculateFcStorage: zms expected in General section of control file but not found') else: log.info('CalculateFcStorage: Fc_storage found in data structure, not calculated') def CorrectFcForStorage(cf,ds,Fc_out='Fc',Fc_in='Fc',Fc_storage_in='Fc_storage'): """ Correct CO2 flux for storage in the air column beneath the CO2 instrument. Usage qcts.CorrectFcForStorage(cf,ds,Fc_out,Fc_in,Fc_storage_in) cf: control file object ds: data structure Fc_out: series label of the corrected CO2 flux Fc_in: series label of the input CO2 flux Fc_storage: series label of the CO2 flux storage term """ if not qcutils.cfoptionskeylogical(cf,Key="ApplyFcStorage"): return if (Fc_in not in ds.series.keys()) or (Fc_storage_in not in ds.series.keys()): msg = "CorrectFcForStorage: Fc or Fc_storage not found, skipping ..." log.warning(msg) return log.info(" ***!!! Applying Fc storage term !!!***") Fc_raw,Fc_flag,Fc_attr = qcutils.GetSeriesasMA(ds,Fc_in) Fc_storage,Fc_storage_flag,Fc_storage_attr = qcutils.GetSeriesasMA(ds,Fc_storage_in) if Fc_attr["units"]!=Fc_storage_attr["units"]: log.error("CorrectFcForStorage: units of Fc do not match those of storage term, storage not applied") return log.info(" Applying storage correction to Fc") Fc = Fc_raw + Fc_storage if qcutils.cfoptionskeylogical(cf,Key="RelaxFcStorage"): idx=numpy.where(numpy.ma.getmaskarray(Fc)==True)[0] Fc[idx]=Fc_raw[idx] log.info(" Replaced corrected Fc with "+str(len(idx))+" raw values") Fc_attr["long_name"] = Fc_attr["long_name"] + ", uncorrected" qcutils.CreateSeries(ds,"Fc_raw",Fc_raw,Flag=Fc_flag,Attr=Fc_attr) Fc_attr["long_name"] = Fc_attr["long_name"].replace(", uncorrected",", corrected for storage using supplied storage term") qcutils.CreateSeries(ds,Fc_out,Fc,FList=[Fc_in,Fc_storage_in],Attr=Fc_attr) if "CorrectFcForStorage" not in ds.globalattributes["Functions"]: ds.globalattributes["Functions"] = ds.globalattributes["Functions"]+", CorrectFcForStorage" def CorrectIndividualFgForStorage(cf,ds): if qcutils.cfkeycheck(cf,Base='FunctionArgs',ThisOne='CFgArgs'): List = cf['FunctionArgs']['CFgArgs'].keys() for i in range(len(List)): CFgArgs = ast.literal_eval(cf['FunctionArgs']['CFgArgs'][str(i)]) CorrectFgForStorage(cf,ds,Fg_out=CFgArgs[0],Fg_in=CFgArgs[1],Ts_in=CFgArgs[2],Sws_in=CFgArgs[3]) return def CorrectFgForStorage(cf,ds,Fg_out='Fg',Fg_in='Fg',Ts_in='Ts',Sws_in='Sws'): """ Correct ground heat flux for storage in the layer above the heat flux plate Usage qcts.CorrectFgForStorage(cf,ds,Fg_out,Fg_in,Ts_in,Sws_in) ds: data structure Fg_out: output soil heat flux variable to ds. Example: 'Fg' Fg_in: input soil heat flux in ds. Example: 'Fg_Av' Ts_in: input soil temperature in ds. Example: 'Ts' Parameters loaded from control file: FgDepth: Depth of soil heat flux plates, m BulkDensity: soil bulk density, kg/m3 OrganicContent: soil organic content, fraction SwsDefault: default value of soil moisture content used when no sensors present """ # check to see if the user wants to skip the correction if not qcutils.cfoptionskeylogical(cf,Key="CorrectFgForStorage",default=True): log.info(' CorrectFgForStorage: storage correction disabled in control file') return # check to see if there is a [Soil] section in the control file if 'Soil' not in cf.keys(): # if there isn't, check to see if the soil information is in the netCDF global attributes if "FgDepth" in ds.globalattributes.keys(): # if it is, read it into the control file object so we can use it later cf["Soil"] = {} cf["Soil"]["FgDepth"] = ds.globalattributes["FgDepth"] cf["Soil"]["BulkDensity"] = ds.globalattributes["BulkDensity"] cf["Soil"]["OrganicContent"] = ds.globalattributes["OrganicContent"] cf["Soil"]["SwsDefault"] = ds.globalattributes["SwsDefault"] else: # tell the user if we can't find the information needed log.warning(' CorrectFgForStorage: [Soil] section not found in control file or global attributes, Fg not corrected') return if Fg_in not in ds.series.keys() or Ts_in not in ds.series.keys(): log.warning(' CorrectFgForStorage: '+Fg_in+' or '+Ts_in+' not found in data structure, Fg not corrected') return log.info(' Correcting soil heat flux for storage') # put the contents of the soil section into the global attributes for item in cf["Soil"].keys(): ds.globalattributes[item] = cf["Soil"][item] d = max(0.0,min(0.5,float(cf['Soil']['FgDepth']))) bd = max(1200.0,min(2500.0,float(cf['Soil']['BulkDensity']))) oc = max(0.0,min(1.0,float(cf['Soil']['OrganicContent']))) mc = 1.0 - oc Sws_default = min(1.0,max(0.0,float(cf['Soil']['SwsDefault']))) # get the data nRecs = int(ds.globalattributes["nc_nrecs"]) Fg,Fg_flag,Fg_attr = qcutils.GetSeriesasMA(ds,Fg_in) Ts,Ts_flag,Ts_attr = qcutils.GetSeriesasMA(ds,Ts_in) Sws,Sws_flag,Sws_attr = qcutils.GetSeriesasMA(ds,Sws_in) iom = numpy.where(numpy.mod(Sws_flag,10)!=0)[0] if len(iom)!=0: log.warning(' CorrectFgForStorage: Sws_default used for '+str(len(iom))+' values') Sws[iom] = Sws_default Sws_flag[iom] = numpy.int32(22) # get the soil temperature difference from time step to time step dTs = numpy.ma.zeros(nRecs) dTs[1:] = numpy.ma.diff(Ts) # write the temperature difference into the data structure so we can use its flag later dTs_flag = numpy.zeros(nRecs,dtype=numpy.int32) index = numpy.where(numpy.ma.getmaskarray(dTs)==True)[0] #index = numpy.ma.where(numpy.ma.getmaskarray(dTs)==True)[0] dTs_flag[index] = numpy.int32(1) attr = qcutils.MakeAttributeDictionary(long_name='Change in soil temperature',units='C') qcutils.CreateSeries(ds,"dTs",dTs,Flag=dTs_flag,Attr=attr) # get the time difference dt = numpy.ma.zeros(nRecs) dt[1:] = numpy.diff(date2num(ds.series['DateTime']['Data']))*float(86400) dt[0] = dt[1] # calculate the specific heat capacity of the soil Cs = mc*bd*c.Cd + oc*bd*c.Co + Sws*c.rho_water*c.Cw # calculate the soil heat storage S = Cs*(dTs/dt)*d # apply the storage term Fg_out_data = Fg + S # work out the QC flag Fg_out_flag = numpy.zeros(nRecs,dtype=numpy.int32) for item in [Fg_flag,Ts_flag,Sws_flag]: Fg_out_flag = numpy.maximum(Fg_out_flag,item) # trap and re-instate flag values of 1 (data missing at L1) for item in [Fg_flag,Ts_flag,Sws_flag]: index = numpy.where(item==numpy.int32(1))[0] Fg_out_flag[index] = numpy.int32(1) # put the corrected soil heat flux into the data structure attr= qcutils.MakeAttributeDictionary(long_name='Soil heat flux corrected for storage',units='W/m2',standard_name='downward_heat_flux_in_soil') qcutils.CreateSeries(ds,Fg_out,Fg_out_data,Flag=Fg_out_flag,Attr=attr) # save the input (uncorrected) soil heat flux series, this will be used if the correction is relaxed attr = qcutils.MakeAttributeDictionary(long_name='Soil heat flux uncorrected for storage',units='W/m2') qcutils.CreateSeries(ds,'Fg_Av',Fg,Flag=Fg_flag,Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Soil heat flux storage',units='W/m2') qcutils.CreateSeries(ds,'S',S,Flag=Fg_flag,Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Specific heat capacity',units='J/m3/K') qcutils.CreateSeries(ds,'Cs',Cs,Flag=Fg_flag,Attr=attr) if 'CorrectFgForStorage' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', CorrectFgForStorage' if qcutils.cfoptionskeylogical(cf,Key='RelaxFgStorage'): ReplaceWhereMissing(ds.series['Fg'],ds.series['Fg'],ds.series['Fg_Av'],FlagValue=20) if 'RelaxFgStorage' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', RelaxFgStorage' def CorrectSWC(cf,ds): """ Correct soil moisture data using calibration curve developed from collected soil samples. To avoid unrealistic or unphysical extreme values upon extrapolation, exponential and logarithmic using ln functions are applied to small and large values, respectively. Threshold values where one model replaces the other is determined where the functions cross. The logarithmic curve is constrained at with a point at which the soil measurement = field porosity and the sensor measurement is maximised under saturation at field capacity. Usage qcts.CorrectSWC(cf,ds) cf: control file ds: data structure Parameters loaded from control file: SWCempList: list of raw CS616 variables SWCoutList: list of corrected CS616 variables SWCattr: list of meta-data attributes for corrected CS616 variables SWC_a0: parameter in logarithmic model, actual = a1 * ln(sensor) + a0 SWC_a1: parameter in logarithmic model, actual = a1 * ln(sensor) + a0 SWC_b0: parameter in exponential model, actual = b0 * exp(b1 * sensor) SWC_b1: parameter in exponential model, actual = b0 * exp(b1 * sensor) SWC_t: threshold parameter for switching from exponential to logarithmic model TDRempList: list of raw CS610 variables TDRoutList: list of corrected CS610 variables TDRattr: list of meta-data attributes for corrected CS610 variables TDRlinList: list of deep TDR probes requiring post-hoc linear correction to match empirical samples TDR_a0: parameter in logarithmic model, actual = a1 * ln(sensor) + a0 TDR_a1: parameter in logarithmic model, actual = a1 * ln(sensor) + a0 TDR_b0: parameter in exponential model, actual = b0 * exp(b1 * sensor) TDR_b1: parameter in exponential model, actual = b0 * exp(b1 * sensor) TDR_t: threshold parameter for switching from exponential to logarithmic model """ if not qcutils.cfoptionskeylogical(cf,Key='CorrectSWC'): return log.info(' Correcting soil moisture data ...') SWCempList = ast.literal_eval(cf['Soil']['empSWCin']) SWCoutList = ast.literal_eval(cf['Soil']['empSWCout']) SWCattr = ast.literal_eval(cf['Soil']['SWCattr']) if cf['Soil']['TDR']=='Yes': TDRempList = ast.literal_eval(cf['Soil']['empTDRin']) TDRoutList = ast.literal_eval(cf['Soil']['empTDRout']) TDRlinList = ast.literal_eval(cf['Soil']['linTDRin']) TDRattr = ast.literal_eval(cf['Soil']['TDRattr']) TDR_a0 = float(cf['Soil']['TDR_a0']) TDR_a1 = float(cf['Soil']['TDR_a1']) TDR_b0 = float(cf['Soil']['TDR_b0']) TDR_b1 = float(cf['Soil']['TDR_b1']) TDR_t = float(cf['Soil']['TDR_t']) SWC_a0 = float(cf['Soil']['SWC_a0']) SWC_a1 = float(cf['Soil']['SWC_a1']) SWC_b0 = float(cf['Soil']['SWC_b0']) SWC_b1 = float(cf['Soil']['SWC_b1']) SWC_t = float(cf['Soil']['SWC_t']) for i in range(len(SWCempList)): log.info(' Applying empirical correction to '+SWCempList[i]) invar = SWCempList[i] outvar = SWCoutList[i] attr = SWCattr[i] Sws,f,a = qcutils.GetSeriesasMA(ds,invar) nRecs = len(Sws) Sws_out = numpy.ma.empty(nRecs,float) Sws_out.fill(c.missing_value) Sws_out.mask = numpy.ma.empty(nRecs,bool) Sws_out.mask.fill(True) index_high = numpy.ma.where((Sws.mask == False) & (Sws > SWC_t))[0] index_low = numpy.ma.where((Sws.mask == False) & (Sws < SWC_t))[0] Sws_out[index_low] = SWC_b0 * numpy.exp(SWC_b1 * Sws[index_low]) Sws_out[index_high] = (SWC_a1 * numpy.log(Sws[index_high])) + SWC_a0 attr = qcutils.MakeAttributeDictionary(long_name=attr,units='cm3 water/cm3 soil',standard_name='soil_moisture_content') qcutils.CreateSeries(ds,outvar,Sws_out,FList=[invar],Attr=attr) if cf['Soil']['TDR']=='Yes': for i in range(len(TDRempList)): log.info(' Applying empirical correction to '+TDRempList[i]) invar = TDRempList[i] outvar = TDRoutList[i] attr = TDRattr[i] Sws,f,a = qcutils.GetSeriesasMA(ds,invar) nRecs = len(Sws) Sws_out = numpy.ma.empty(nRecs,float) Sws_out.fill(c.missing_value) Sws_out.mask = numpy.ma.empty(nRecs,bool) Sws_out.mask.fill(True) index_high = numpy.ma.where((Sws.mask == False) & (Sws > TDR_t))[0] index_low = numpy.ma.where((Sws.mask == False) & (Sws < TDR_t))[0] Sws_out[index_low] = TDR_b0 * numpy.exp(TDR_b1 * Sws[index_low]) Sws_out[index_high] = (TDR_a1 * numpy.log(Sws[index_high])) + TDR_a0 attr = qcutils.MakeAttributeDictionary(long_name=attr,units='cm3 water/cm3 soil',standard_name='soil_moisture_content') qcutils.CreateSeries(ds,outvar,Sws_out,FList=[invar],Attr=attr) def CorrectWindDirection(cf,ds,Wd_in): """ Correct wind direction for mis-aligned sensor direction. Usage qcts.CorrectWindDirection(cf,ds,Wd_in) cf: control file ds: data structure Wd_in: input/output wind direction variable in ds. Example: 'Wd_CSAT' """ log.info(' Correcting wind direction') Wd,f,a = qcutils.GetSeriesasMA(ds,Wd_in) ldt = ds.series['DateTime']['Data'] KeyList = cf['Variables'][Wd_in]['CorrectWindDirection'].keys() for i in range(len(KeyList)): ItemList = ast.literal_eval(cf['Variables'][Wd_in]['CorrectWindDirection'][str(i)]) try: si = ldt.index(datetime.datetime.strptime(ItemList[0],'%Y-%m-%d %H:%M')) except ValueError: si = 0 try: ei = ldt.index(datetime.datetime.strptime(ItemList[1],'%Y-%m-%d %H:%M')) + 1 except ValueError: ei = -1 Correction = float(ItemList[2]) Wd[si:ei] = Wd[si:ei] + Correction Wd = numpy.mod(Wd,float(360)) ds.series[Wd_in]['Data'] = numpy.ma.filled(Wd,float(c.missing_value)) def LowPassFilterSws(cf,ds,Sws_out='Sws_LP',Sws_in='Sws',npoles=5,co_ny=0.05): ''' Create a series of daily averaged soil moisture data and then interpolate this back on to the time step of the data. This result is a time series of soil moisture data that is less noisy than the data at the original time step but still resolves day-to-day changes and seasonal trends. ''' b,a = butter(npoles,co_ny) Sws,f,a = qcutils.GetSeries(ds,Sws_in) Sws_LP = filtfilt(b,a,Sws) attr = qcutils.MakeAttributeDictionary(long_name=attr,units='cm3 water/cm3 soil',standard_name='soil_moisture_content') qcutils.CreateSeries(ds,outvar,Sws_out,FList=[invar],Attr=attr) def do_attributes(cf,ds): """ Import attriubes in L1 control file to netCDF dataset. Included global and variable attributes. Also attach flag definitions to global meta-data for reference. Usage qcts.do_attributes(cf,ds) cf: control file ds: data structure """ log.info(' Getting the attributes given in control file') if 'Global' in cf.keys(): for gattr in cf['Global'].keys(): ds.globalattributes[gattr] = cf['Global'][gattr] ds.globalattributes['Flag00'] = 'Good data' ds.globalattributes['Flag10'] = 'Corrections: Apply Linear' ds.globalattributes['Flag20'] = 'GapFilling: Driver gap filled using ACCESS' ds.globalattributes['Flag30'] = 'GapFilling: Flux gap filled by ANN (SOLO)' ds.globalattributes['Flag40'] = 'GapFilling: Gap filled by climatology' ds.globalattributes['Flag50'] = 'GapFilling: Gap filled by interpolation' ds.globalattributes['Flag60'] = 'GapFilling: Flux gap filled using ratios' ds.globalattributes['Flag01'] = 'QA/QC: Missing value in L1 dataset' ds.globalattributes['Flag02'] = 'QA/QC: L2 Range Check' ds.globalattributes['Flag03'] = 'QA/QC: CSAT Diagnostic' ds.globalattributes['Flag04'] = 'QA/QC: LI7500 Diagnostic' ds.globalattributes['Flag05'] = 'QA/QC: L2 Diurnal SD Check' ds.globalattributes['Flag06'] = 'QA/QC: Excluded Dates' ds.globalattributes['Flag07'] = 'QA/QC: Excluded Hours' ds.globalattributes['Flag08'] = 'QA/QC: Missing value found with QC flag = 0' ds.globalattributes['Flag11'] = 'Corrections/Combinations: Coordinate Rotation (Ux, Uy, Uz, UxT, UyT, UzT, UxA, UyA, UzA, UxC, UyC, UzC, UxUz, UxUx, UxUy, UyUz, UxUy, UyUy)' ds.globalattributes['Flag12'] = 'Corrections/Combinations: Massman Frequency Attenuation Correction (Coord Rotation, Tv_CSAT, Ah_HMP, ps)' ds.globalattributes['Flag13'] = 'Corrections/Combinations: Virtual to Actual Fh (Coord Rotation, Massman, Ta_HMP)' ds.globalattributes['Flag14'] = 'Corrections/Combinations: WPL correction for flux effects on density measurements (Coord Rotation, Massman, Fhv to Fh, Cc_7500_Av)' ds.globalattributes['Flag15'] = 'Corrections/Combinations: Ta from Tv' ds.globalattributes['Flag16'] = 'Corrections/Combinations: L3 Range Check' ds.globalattributes['Flag17'] = 'Corrections/Combinations: L3 Diurnal SD Check' ds.globalattributes['Flag18'] = 'Corrections/Combinations: u* filter' ds.globalattributes['Flag19'] = 'Corrections/Combinations: Gap coordination' ds.globalattributes['Flag21'] = 'GapFilling: Used non-rotated covariance' ds.globalattributes['Flag31'] = 'GapFilling: Flux gap not filled by ANN' ds.globalattributes['Flag38'] = 'GapFilling: L4 Range Check' ds.globalattributes['Flag39'] = 'GapFilling: L4 Diurnal SD Check' # the following flags are used by James Cleverly's version but not # by the standard OzFlux version. #ds.globalattributes['Flag51'] = 'albedo: bad Fsd < threshold (290 W/m2 default) only if bad time flag (31) not set' #ds.globalattributes['Flag52'] = 'albedo: bad time flag (not midday 10.00 to 14.00)' #ds.globalattributes['Flag61'] = 'Penman-Monteith: bad rst (rst < 0) only if bad Uavg (35), bad Fe (33) and bad Fsd (34) flags not set' #ds.globalattributes['Flag62'] = 'Penman-Monteith: bad Fe < threshold (0 W/m2 default) only if bad Fsd (34) flag not set' #ds.globalattributes['Flag63'] = 'Penman-Monteith: bad Fsd < threshold (10 W/m2 default)' #ds.globalattributes['Flag64'] = 'Penman-Monteith: Uavg == 0 (undefined aerodynamic resistance under calm conditions) only if bad Fe (33) and bad Fsd (34) flags not set' #ds.globalattributes['Flag70'] = 'Partitioning Night: Re computed from exponential temperature response curves' #ds.globalattributes['Flag80'] = 'Partitioning Day: GPP/Re computed from light-response curves, GPP = Re - Fc' #ds.globalattributes['Flag81'] = 'Partitioning Day: GPP night mask' #ds.globalattributes['Flag82'] = 'Partitioning Day: Fc > Re, GPP = 0, Re = Fc' for ThisOne in ds.series.keys(): if ThisOne in cf['Variables']: if 'Attr' in cf['Variables'][ThisOne].keys(): ds.series[ThisOne]['Attr'] = {} for attr in cf['Variables'][ThisOne]['Attr'].keys(): ds.series[ThisOne]['Attr'][attr] = cf['Variables'][ThisOne]['Attr'][attr] if "missing_value" not in ds.series[ThisOne]['Attr'].keys(): ds.series[ThisOne]['Attr']["missing_value"] = numpy.int32(c.missing_value) def DoFunctions(cf,ds): """ Purpose: Evaluate functions used in the L1 control file. Usage: Author: PRI Date: September 2015 """ implemented_functions = [name for name,data in inspect.getmembers(qcfunc,inspect.isfunction)] for var in cf["Variables"].keys(): # datetime functions handled elsewhere for now if var=="DateTime": continue if "Function" not in cf["Variables"][var].keys(): continue if "func" not in cf["Variables"][var]["Function"].keys(): msg = " DoFunctions: 'func' keyword not found in [Functions] for "+var log.error(msg) continue function_string = cf["Variables"][var]["Function"]["func"] function_name = function_string.split("(")[0] if function_name not in implemented_functions: msg = " DoFunctions: Requested function "+function_name+" not imlemented, skipping ..." log.error(msg) continue function_args = function_string.split("(")[1].replace(")","").split(",") result = getattr(qcfunc,function_name)(ds,var,*function_args) msg = " Completed function for "+var log.info(msg) def CalculateStandardDeviations(cf,ds): log.info(' Getting variances from standard deviations & vice versa') if 'AhAh' in ds.series.keys() and 'Ah_7500_Sd' not in ds.series.keys(): AhAh,flag,attr = qcutils.GetSeriesasMA(ds,'AhAh') Ah_7500_Sd = numpy.ma.sqrt(AhAh) attr = qcutils.MakeAttributeDictionary(long_name='Absolute humidity from IRGA, standard deviation',units='g/m3') qcutils.CreateSeries(ds,'Ah_7500_Sd',Ah_7500_Sd,Flag=flag,Attr=attr) if 'H2O_IRGA_Vr' in ds.series.keys() and 'H2O_IRGA_Sd' not in ds.series.keys(): H2O_IRGA_Vr,flag,attr = qcutils.GetSeriesasMA(ds,'H2O_IRGA_Vr') H2O_IRGA_Sd = numpy.ma.sqrt(H2O_IRGA_Vr) attr = qcutils.MakeAttributeDictionary(long_name='Absolute humidity from IRGA, standard deviation',units='g/m3') qcutils.CreateSeries(ds,'H2O_IRGA_Sd',H2O_IRGA_Sd,Flag=flag,Attr=attr) if 'Ah_7500_Sd' in ds.series.keys() and 'AhAh' not in ds.series.keys(): Ah_7500_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'Ah_7500_Sd') AhAh = Ah_7500_Sd*Ah_7500_Sd attr = qcutils.MakeAttributeDictionary(long_name='Absolute humidity from IRGA, variance',units='(g/m3)2') qcutils.CreateSeries(ds,'AhAh',AhAh,Flag=flag,Attr=attr) if 'H2O_IRGA_Sd' in ds.series.keys() and 'H2O_IRGA_Vr' not in ds.series.keys(): H2O_IRGA_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'H2O_IRGA_Sd') H2O_IRGA_Vr = H2O_IRGA_Sd*H2O_IRGA_Sd attr = qcutils.MakeAttributeDictionary(long_name='Absolute humidity from IRGA, variance',units='(g/m3)2') qcutils.CreateSeries(ds,'H2O_IRGA_Vr',H2O_IRGA_Vr,Flag=flag,Attr=attr) if 'CcCc' in ds.series.keys() and 'Cc_7500_Sd' not in ds.series.keys(): CcCc,flag,attr = qcutils.GetSeriesasMA(ds,'CcCc') Cc_7500_Sd = numpy.ma.sqrt(CcCc) attr = qcutils.MakeAttributeDictionary(long_name='CO2 concentration from IRGA, standard deviation',units='mg/m3') qcutils.CreateSeries(ds,'Cc_7500_Sd',Cc_7500_Sd,Flag=flag,Attr=attr) if 'CO2_IRGA_Sd' in ds.series.keys() and 'CO2_IRGA_Vr' not in ds.series.keys(): CO2_IRGA_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'CO2_IRGA_Sd') CO2_IRGA_Vr = CO2_IRGA_Sd*CO2_IRGA_Sd attr = qcutils.MakeAttributeDictionary(long_name='CO2 concentration from IRGA, variance',units='(mg/m3)2') qcutils.CreateSeries(ds,'CO2_IRGA_Vr',CO2_IRGA_Vr,Flag=flag,Attr=attr) if 'Cc_7500_Sd' in ds.series.keys() and 'CcCc' not in ds.series.keys(): Cc_7500_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'Cc_7500_Sd') CcCc = Cc_7500_Sd*Cc_7500_Sd attr = qcutils.MakeAttributeDictionary(long_name='CO2 concentration from IRGA, variance',units='(mg/m3)2') qcutils.CreateSeries(ds,'CcCc',CcCc,Flag=flag,Attr=attr) if 'CO2_IRGA_Vr' in ds.series.keys() and 'CO2_IRGA_Sd' not in ds.series.keys(): CO2_IRGA_Vr,flag,attr = qcutils.GetSeriesasMA(ds,'CO2_IRGA_Vr') CO2_IRGA_Sd = numpy.ma.sqrt(CO2_IRGA_Vr) attr = qcutils.MakeAttributeDictionary(long_name='CO2 concentration from IRGA, standard deviation',units='mg/m3') qcutils.CreateSeries(ds,'CO2_IRGA_Sd',CO2_IRGA_Sd,Flag=flag,Attr=attr) if 'Ux_Sd' in ds.series.keys() and 'UxUx' not in ds.series.keys(): Ux_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'Ux_Sd') UxUx = Ux_Sd*Ux_Sd attr = qcutils.MakeAttributeDictionary(long_name='Longitudinal velocity component from CSAT, variance',units='(m/s)2') qcutils.CreateSeries(ds,'UxUx',UxUx,Flag=flag,Attr=attr) if 'UxUx' in ds.series.keys() and 'Ux_Sd' not in ds.series.keys(): UxUx,flag,attr = qcutils.GetSeriesasMA(ds,'UxUx') Ux_Sd = numpy.ma.sqrt(UxUx) attr = qcutils.MakeAttributeDictionary(long_name='Longitudinal velocity component from CSAT, standard deviation',units='m/s') qcutils.CreateSeries(ds,'Ux_Sd',Ux_Sd,Flag=flag,Attr=attr) if 'Uy_Sd' in ds.series.keys() and 'UyUy' not in ds.series.keys(): Uy_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'Uy_Sd') UyUy = Uy_Sd*Uy_Sd attr = qcutils.MakeAttributeDictionary(long_name='Lateral velocity component from CSAT, variance',units='(m/s)2') qcutils.CreateSeries(ds,'UyUy',UyUy,Flag=flag,Attr=attr) if 'UyUy' in ds.series.keys() and 'Uy_Sd' not in ds.series.keys(): UyUy,flag,attr = qcutils.GetSeriesasMA(ds,'UyUy') Uy_Sd = numpy.ma.sqrt(UyUy) attr = qcutils.MakeAttributeDictionary(long_name='Lateral velocity component from CSAT, standard deviation',units='m/s') qcutils.CreateSeries(ds,'Uy_Sd',Uy_Sd,Flag=flag,Attr=attr) if 'Uz_Sd' in ds.series.keys() and 'UzUz' not in ds.series.keys(): Uz_Sd,flag,attr = qcutils.GetSeriesasMA(ds,'Uz_Sd') UzUz = Uz_Sd*Uz_Sd attr = qcutils.MakeAttributeDictionary(long_name='Vertical velocity component from CSAT, variance',units='(m/s)2') qcutils.CreateSeries(ds,'UzUz',UzUz,Flag=flag,Attr=attr) if 'UzUz' in ds.series.keys() and 'Uz_Sd' not in ds.series.keys(): UzUz,flag,attr = qcutils.GetSeriesasMA(ds,'UzUz') Uz_Sd = numpy.ma.sqrt(UzUz) attr = qcutils.MakeAttributeDictionary(long_name='Vertical velocity component from CSAT, standard deviation',units='m/s') qcutils.CreateSeries(ds,'Uz_Sd',Uz_Sd,Flag=flag,Attr=attr) def do_mergeseries(ds,target,srclist,mode="verbose"): if mode.lower()!="quiet": log.info(' Merging '+str(srclist)+' ==> '+target) if srclist[0] not in ds.series.keys(): if mode.lower()!="quiet": log.error(' MergeSeries: primary input series '+srclist[0]+' not found') return data = ds.series[srclist[0]]['Data'].copy() flag1 = ds.series[srclist[0]]['Flag'].copy() flag2 = ds.series[srclist[0]]['Flag'].copy() attr = ds.series[srclist[0]]['Attr'].copy() SeriesNameString = srclist[0] tmplist = list(srclist) tmplist.remove(tmplist[0]) for label in tmplist: if label in ds.series.keys(): SeriesNameString = SeriesNameString+', '+label index = numpy.where(numpy.mod(flag1,10)==0)[0] # find the elements with flag = 0, 10, 20 etc flag2[index] = 0 # set them all to 0 if label=="Fg": index = numpy.where(flag2==22)[0] if len(index)!=0: flag2[index] = 0 index = numpy.where(flag2!=0)[0] # index of flag values other than 0,10,20,30 ... data[index] = ds.series[label]['Data'][index].copy() # replace bad primary with good secondary flag1[index] = ds.series[label]['Flag'][index].copy() else: log.error(" MergeSeries: secondary input series "+label+" not found") attr["long_name"] = attr["long_name"]+", merged from " + SeriesNameString qcutils.CreateSeries(ds,target,data,Flag=flag1,Attr=attr) def do_solo(cf,ds4,Fc_in='Fc',Fe_in='Fe',Fh_in='Fh',Fc_out='Fc',Fe_out='Fe',Fh_out='Fh'): ''' duplicate gapfilled fluxes for graphing comparison''' if qcutils.cfkeycheck(cf,Base='FunctionArgs',ThisOne='SOLOvars'): invars = ast.literal_eval(cf['FunctionArgs']['SOLOvars']) Fc_in = invars[0] Fe_in = invars[1] Fh_in = invars[2] if qcutils.cfkeycheck(cf,Base='FunctionArgs',ThisOne='SOLOplot'): outvars = ast.literal_eval(cf['FunctionArgs']['SOLOplot']) Fc_out = outvars[0] Fe_out = outvars[1] Fh_out = outvars[2] # add relevant meteorological values to L3 data log.info(' Adding standard met variables to database') CalculateMeteorologicalVariables(ds4) ds4.globalattributes['L4Functions'] = ds4.globalattributes['L4Functions']+', CalculateMetVars' if Fe_in in ds4.series.keys(): Fe,flag,attr = qcutils.GetSeriesasMA(ds4,Fe_in) attr = qcutils.MakeAttributeDictionary(long_name='ANN gapfilled Latent Heat Flux',units='W/m2',standard_name='surface_upward_latent_heat_flux') qcutils.CreateSeries(ds4,Fe_out,Fe,Flag=flag,Attr=attr) if Fc_in in ds4.series.keys(): Fc,flag,attr = qcutils.GetSeriesasMA(ds4,Fc_in) attr = qcutils.MakeAttributeDictionary(long_name='ANN gapfilled Carbon Flux',units='mg/m2/s') qcutils.CreateSeries(ds4,Fc_out,Fc,Flag=flag,Attr=attr) if Fh_in in ds4.series.keys(): Fh,flag,attr = qcutils.GetSeriesasMA(ds4,Fh_in) attr = qcutils.MakeAttributeDictionary(long_name='ANN gapfilled Sensible Heat Flux',units='W/m2',standard_name='surface_upward_sensible_heat_flux') qcutils.CreateSeries(ds4,Fh_out,Fh,Flag=flag,Attr=attr) def Fc_WPL(cf,ds,Fc_wpl_out='Fc',Fc_raw_in='Fc',Fh_in='Fh',Fe_in='Fe',Ta_in='Ta',Ah_in='Ah',Cc_in='Cc',ps_in='ps'): """ Apply Webb, Pearman and Leuning correction to carbon flux. This correction is necessary to account for flux effects on density measurements. Original formulation: Campbell Scientific Usage qcts.Fc_WPL(ds,Fc_wpl_out,Fc_raw_in,Fh_in,Fe_raw_in,Ta_in,Ah_in,Cc_in,ps_in) ds: data structure Fc_wpl_out: output corrected carbon flux variable to ds. Example: 'Fc' Fc_raw_in: input carbon flux in ds. Example: 'Fc' Fh_in: input sensible heat flux in ds. Example: 'Fh' Fe_raw_in: input uncorrected latent heat flux in ds. Example: 'Fe_raw' Ta_in: input air temperature in ds. Example: 'Ta' Ah_in: input absolute humidity in ds. Example: 'Ah' Cc_in: input co2 density in ds. Example: 'Cc' ps_in: input atmospheric pressure in ds. Example: 'ps' Used for fluxes that are raw or rotated. Pre-requisite: CalculateFluxes, CalculateFluxes_Unrotated or CalculateFluxesRM Pre-requisite: FhvtoFh Pre-requisite: Fe_WPL Accepts meteorological constants or variables """ if 'DisableFcWPL' in cf['Options'] and cf['Options'].as_bool('DisableFcWPL'): log.warning(" WPL correction for Fc disabled in control file") return log.info(' Applying WPL correction to Fc') Fc_raw,Fc_raw_flag,Fc_raw_attr = qcutils.GetSeriesasMA(ds,Fc_raw_in) Fh,f,a = qcutils.GetSeriesasMA(ds,Fh_in) Fe,f,a = qcutils.GetSeriesasMA(ds,Fe_in) ps,f,a = qcutils.GetSeriesasMA(ds,ps_in) Ta,f,a = qcutils.GetSeriesasMA(ds,Ta_in) TaK = Ta+c.C2K # air temperature from C to K Ah,Ah_flag,Ah_attr = qcutils.GetSeriesasMA(ds,Ah_in) if Ah_attr["units"]!="g/m3": msg = " Fc_WPL: units for Ah ("+Ah_attr["units"]+") are incorrect" log.error(msg) sys.exit() Ah = Ah*c.g2kg # absolute humidity from g/m3 to kg/m3 Cc,Cc_flag,Cc_attr = qcutils.GetSeriesasMA(ds,Cc_in) if Cc_attr["units"]!="mg/m3": if Cc_attr["units"]=="umol/mol": msg = " Fc_WPL: CO2 units ("+Cc_attr["units"]+") converted to mg/m3" log.warning(msg) Cc = mf.co2_mgpm3fromppm(Cc,Ta,ps) else: msg = " Fc_WPL: unrecognised units ("+Cc_attr["units"]+") for Cc" log.error(msg) sys.exit() rhod,f,a = qcutils.GetSeriesasMA(ds,'rhod') RhoCp,f,a = qcutils.GetSeriesasMA(ds,'RhoCp') Lv,f,a = qcutils.GetSeriesasMA(ds,'Lv') sigma = Ah/rhod co2_wpl_Fe = (c.mu/(1+c.mu*sigma))*(Cc/rhod)*(Fe/Lv) co2_wpl_Fh = (Cc/TaK)*(Fh/RhoCp) Fc_wpl_data = Fc_raw+co2_wpl_Fe+co2_wpl_Fh Fc_wpl_flag = numpy.zeros(len(Fc_wpl_data)) index = numpy.where(numpy.ma.getmaskarray(Fc_wpl_data)==True)[0] Fc_wpl_flag[index] = numpy.int32(14) attr = qcutils.MakeAttributeDictionary(long_name='WPL corrected Fc',units='mg/m2/s') if "height" in Fc_raw_attr: attr["height"] = Fc_raw_attr["height"] qcutils.CreateSeries(ds,Fc_wpl_out,Fc_wpl_data,Flag=Fc_wpl_flag,Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='WPL correction to Fc due to Fe',units='mg/m2/s') if "height" in Fc_raw_attr: attr["height"] = Fc_raw_attr["height"] qcutils.CreateSeries(ds,'co2_wpl_Fe',co2_wpl_Fe,Flag=Fc_wpl_flag,Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='WPL correction to Fc due to Fh',units='mg/m2/s') if "height" in Fc_raw_attr: attr["height"] = Fc_raw_attr["height"] qcutils.CreateSeries(ds,'co2_wpl_Fh',co2_wpl_Fh,Flag=Fc_wpl_flag,Attr=attr) def Fe_WPL(cf,ds,Fe_wpl_out='Fe',Fe_raw_in='Fe',Fh_in='Fh',Ta_in='Ta',Ah_in='Ah',ps_in='ps'): """ Apply Webb, Pearman and Leuning correction to vapour flux. This correction is necessary to account for flux effects on density measurements. Original formulation: Campbell Scientific Usage qcts.Fe_WPL(ds,Fe_wpl_out,Fe_raw_in,Fh_in,Ta_in,Ah_in,ps_in) ds: data structure Fe_wpl_out: output corrected water vapour flux variable to ds. Example: 'Fe' Fe_raw_in: input water vapour flux in ds. Example: 'Fe' Fh_in: input sensible heat flux in ds. Example: 'Fh' Ta_in: input air temperature in ds. Example: 'Ta' Ah_in: input absolute humidity in ds. Example: 'Ah' ps_in: input atmospheric pressure in ds. Example: 'ps' Used for fluxes that are raw or rotated. Pre-requisite: CalculateFluxes, CalculateFluxes_Unrotated or CalculateFluxesRM Pre-requisite: FhvtoFh Accepts meteorological constants or variables """ if 'DisableFeWPL' in cf['Options'] and cf['Options'].as_bool('DisableFeWPL'): log.warning(" WPL correction for Fe disabled in control file") return log.info(' Applying WPL correction to Fe') if qcutils.cfkeycheck(cf,Base='FunctionArgs',ThisOne='EWPL'): Eargs = ast.literal_eval(cf['FunctionArgs']['EWPL']) Fe_wpl_out = Eargs[0] Fe_raw_in = Eargs[1] Fh_in = Eargs[2] Ta_in = Eargs[3] Ah_in = Eargs[4] ps_in = Eargs[5] Fe_raw,Fe_raw_flag,Fe_raw_attr = qcutils.GetSeriesasMA(ds,Fe_raw_in) Fh,f,a = qcutils.GetSeriesasMA(ds,Fh_in) Ta,f,a = qcutils.GetSeriesasMA(ds,Ta_in) TaK = Ta + c.C2K # air temperature from C to K Ah,Ah_flag,Ah_attr = qcutils.GetSeriesasMA(ds,Ah_in) if Ah_attr["units"]!="g/m3": msg = " Fe_WPL: incorrect units for Ah" log.error(msg) sys.exit() ps,f,a = qcutils.GetSeriesasMA(ds,ps_in) rhod,f,a = qcutils.GetSeriesasMA(ds,'rhod') # density dry air rhom,f,a = qcutils.GetSeriesasMA(ds,'rhom') # density moist air RhoCp,f,a = qcutils.GetSeriesasMA(ds,'RhoCp') Lv,f,a = qcutils.GetSeriesasMA(ds,'Lv') Ah = Ah*c.g2kg # absolute humidity from g/m3 to kg/m3 sigma = Ah/rhod h2o_wpl_Fe = c.mu*sigma*Fe_raw h2o_wpl_Fh = (1+c.mu*sigma)*Ah*Lv*(Fh/RhoCp)/TaK Fe_wpl_data = Fe_raw+h2o_wpl_Fe+h2o_wpl_Fh Fe_wpl_flag = numpy.zeros(len(Fe_wpl_data)) mask = numpy.ma.getmask(Fe_wpl_data) index = numpy.where(numpy.ma.getmaskarray(Fe_wpl_data)==True)[0] Fe_wpl_flag[index] = numpy.int32(14) attr = qcutils.MakeAttributeDictionary(long_name='WPL corrected Fe', standard_name='surface_upward_latent_heat_flux', units='W/m2') if "height" in Fe_raw_attr: attr["height"] = Fe_raw_attr["height"] qcutils.CreateSeries(ds,Fe_wpl_out,Fe_wpl_data,Flag=Fe_wpl_flag,Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Fe (uncorrected for WPL)',units='W/m2') if "height" in Fe_raw_attr: attr["height"] = Fe_raw_attr["height"] qcutils.CreateSeries(ds,'Fe_raw',Fe_raw,Flag=Fe_raw_flag,Attr=attr) if qcutils.cfoptionskeylogical(cf,Key='RelaxFeWPL'): ReplaceWhereMissing(ds.series['Fe'],ds.series['Fe'],ds.series['Fe_raw'],FlagValue=20) if 'RelaxFeWPL' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', RelaxFeWPL' def FhvtoFh(cf,ds,Fh_out='Fh',Fhv_in='Fhv',Tv_in='Tv_CSAT',q_in='q',wA_in='wA',wT_in='wT'): ''' Convert the virtual heat flux to the sensible heat flux. USEAGE: qcts.FhvtoFh_EP(cf,ds,Fhv_in='Fhv',RhoCp_in='RhoCp',Tv_in='Tv_CSAT',wA_in='wA',rhom_in='rhom',q_in='q',wT_in='wT') INPUT: All inputs are read from the data structure. Fhv_in - label of the virtual heat flux series, default is 'Fhv' RhoCp_in - label of the RhoCp series, default is 'RhoCp' Tv_in - label of the virtual temperature series, default is 'Tv_CSAT' wA_in - label of the wA covariance series, default is 'wA' rhom_in - label of the moist air density series, default is 'rhom' q_in - label of the specific humidity series, default is 'q' wT_in - label of the wT covariance series, default is 'wT' OUTPUT: All outputs are written to the data structure. Fh_out - label of sensible heat flux, default is 'Fh' ''' log.info(' Converting virtual Fh to Fh') # get the input series Fhv,f,a = qcutils.GetSeriesasMA(ds,Fhv_in) # get the virtual heat flux Tv,f,a = qcutils.GetSeriesasMA(ds,Tv_in) # get the virtual temperature, C TvK = Tv + c.C2K # convert from C to K wA,f,a = qcutils.GetSeriesasMA(ds,wA_in) # get the wA covariance, g/m2/s wA = wA * c.g2kg # convert from g/m2/s to kg/m2/s q,f,a = qcutils.GetSeriesasMA(ds,q_in) # get the specific humidity, kg/kg wT,f,wT_a = qcutils.GetSeriesasMA(ds,wT_in) # get the wT covariance, mK/s # get the utility series RhoCp,f,a = qcutils.GetSeriesasMA(ds,'RhoCp') # get rho*Cp rhom,f,a = qcutils.GetSeriesasMA(ds,'rhom') # get the moist air density, kg/m3 # define local constants alpha = 0.51 # do the conversion Fh = Fhv - RhoCp*alpha*TvK*wA/rhom - RhoCp*alpha*q*wT # put the calculated sensible heat flux into the data structure attr = qcutils.MakeAttributeDictionary(long_name='Sensible heat flux from virtual heat flux', units='W/m2',standard_name='surface_upward_sensible_heat_flux') if "height" in wT_a: attr["height"] = wT_a["height"] qcutils.CreateSeries(ds,Fh_out,Fh,FList=[Fhv_in,Tv_in,wA_in,q_in,wT_in],Attr=attr) if 'FhvtoFh' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', FhvtoFh' if qcutils.cfoptionskeylogical(cf,Key='RelaxFhvtoFh'): ReplaceWhereMissing(ds.series['Fh'],ds.series['Fh'],ds.series['Fhv'],FlagValue=20) if 'RelaxFhvtoFh' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', RelaxFhvtoFh' def FilterUstar(cf,ds,ustar_in='ustar',ustar_out='ustar_filtered'): """ Filter ustar for low turbulence periods. The filtering is done by checking the friction velocity for each time period. If ustar is less than or equal to the threshold specified in the control file then ustar is set to missing. If the ustar is greater than the threshold, no action is taken. Filtering is not done "in place", a new series is created with the label given in the control file. The QC flag is set to 18 to indicate the missing low ustar values. Usage: qcts.FilterUstar(cf,ds) cf: control file object ds: data structure object """ if ustar_out not in cf['Variables'].keys(): return if 'ustar_threshold' in cf['Variables'][ustar_out].keys(): log.info(' Filtering ustar to remove values below threshold') ustar_threshold = float(cf['Variables'][ustar_out]['ustar_threshold']) ustar,ustar_flag,ustar_attr = qcutils.GetSeriesasMA(ds,ustar_in) index = numpy.ma.where(ustar<=ustar_threshold)[0] ustar = numpy.ma.masked_where(ustar<=ustar_threshold,ustar) ustar_flag[index] = 18 descr = 'ustar filtered for low turbulence conditions (<'+str(ustar_threshold)+')' units = qcutils.GetUnitsFromds(ds, ustar_in) attr = qcutils.MakeAttributeDictionary(long_name=descr,units=units) qcutils.CreateSeries(ds,ustar_out,ustar,Flag=ustar_flag,Attr=attr) else: log.error(' ustar threshold (ustar_threshold) not found in '+ustar_out+' section of control file') def get_averages(Data): """ Get daily averages on days when no 30-min observations are missing. Days with missing observations return a value of c.missing_value Values returned are sample size (Num) and average (Av) Usage qcts.get_averages(Data) Data: 1-day dataset """ li = numpy.ma.where(abs(Data-float(c.missing_value))>c.eps) Num = numpy.size(li) if Num == 0: Av = c.missing_value elif Num == 48: Av = numpy.ma.mean(Data[li]) else: x = 0 index = numpy.ma.where(Data.mask == True)[0] if len(index) == 1: x = 1 elif len(index) > 1: for i in range(len(Data)): if Data.mask[i] == True: x = x + 1 if x == 0: Av = numpy.ma.mean(Data[li]) else: Av = c.missing_value return Num, Av def get_laggedcorrelation(x_in,y_in,maxlags): """ Calculate the lagged cross-correlation between 2 1D arrays. Taken from the matplotlib.pyplot.xcorr source code. PRI added handling of masked arrays. """ lags = numpy.arange(-maxlags,maxlags+1) mask = numpy.ma.mask_or(x_in.mask,y_in.mask,copy=True,shrink=False) x = numpy.ma.array(x_in,mask=mask,copy=True) y = numpy.ma.array(y_in,mask=mask,copy=True) x = numpy.ma.compressed(x) y = numpy.ma.compressed(y) corr = numpy.correlate(x, y, mode=2) corr/= numpy.sqrt(numpy.dot(x,x) * numpy.dot(y,y)) if maxlags is None: maxlags = len(x) - 1 if maxlags >= len(x) or maxlags < 1: raise ValueError('qcts.get_laggedcorrelation: maxlags must be None or strictly positive < %d'%len(x)) corr = corr[len(x)-1-maxlags:len(x)+maxlags] return lags,corr def get_minmax(Data): """ Get daily minima and maxima on days when no 30-min observations are missing. Days with missing observations return a value of c.missing_value Values returned are sample size (Num), minimum (Min) and maximum (Max) Usage qcts.get_minmax(Data) Data: 1-day dataset """ li = numpy.ma.where(abs(Data-float(c.missing_value))>c.eps) Num = numpy.size(li) if Num == 0: Min = c.missing_value Max = c.missing_value elif Num == 48: Min = numpy.ma.min(Data[li]) Max = numpy.ma.max(Data[li]) else: x = 0 index = numpy.ma.where(Data.mask == True)[0] if len(index) == 1: x = 1 elif len(index) > 1: for i in range(len(Data)): if Data.mask[i] == True: x = x + 1 if x == 0: Min = numpy.ma.min(Data[li]) Max = numpy.ma.max(Data[li]) else: Min = c.missing_value Max = c.missing_value return Num, Min, Max def get_nightsums(Data): """ Get nightly sums and averages on nights when no 30-min observations are missing. Nights with missing observations return a value of c.missing_value Values returned are sample size (Num), sums (Sum) and average (Av) Usage qcts.get_nightsums(Data) Data: 1-day dataset """ li = numpy.ma.where(Data.mask == False)[0] Num = numpy.size(li) if Num == 0: Sum = c.missing_value Av = c.missing_value else: x = 0 for i in range(len(Data)): if Data.mask[i] == True: x = x + 1 if x == 0: Sum = numpy.ma.sum(Data[li]) Av = numpy.ma.mean(Data[li]) else: Sum = c.missing_value Av = c.missing_value return Num, Sum, Av def get_soilaverages(Data): """ Get daily averages of soil water content on days when 15 or fewer 30-min observations are missing. Days with 16 or more missing observations return a value of c.missing_value Values returned are sample size (Num) and average (Av) Usage qcts.get_soilaverages(Data) Data: 1-day dataset """ li = numpy.ma.where(abs(Data-float(c.missing_value))>c.eps) Num = numpy.size(li) if Num > 33: Av = numpy.ma.mean(Data[li]) else: Av = c.missing_value return Num, Av def get_subsums(Data): """ Get separate daily sums of positive and negative fluxes when no 30-min observations are missing. Days with missing observations return a value of c.missing_value Values returned are positive and negative sample sizes (PosNum and NegNum) and sums (SumPos and SumNeg) Usage qcts.get_subsums(Data) Data: 1-day dataset """ li = numpy.ma.where(abs(Data-float(c.missing_value))>c.eps) Num = numpy.size(li) if Num == 48: pi = numpy.ma.where(Data[li]>0) ni = numpy.ma.where(Data[li]<0) PosNum = numpy.size(pi) NegNum = numpy.size(ni) if PosNum > 0: SumPos = numpy.ma.sum(Data[pi]) else: SumPos = 0 if NegNum > 0: SumNeg = numpy.ma.sum(Data[ni]) else: SumNeg = 0 else: pi = numpy.ma.where(Data[li]>0) ni = numpy.ma.where(Data[li]<0) PosNum = numpy.size(pi) NegNum = numpy.size(ni) SumPos = c.missing_value SumNeg = c.missing_value return PosNum, NegNum, SumPos, SumNeg def get_sums(Data): """ Get daily sums when no 30-min observations are missing. Days with missing observations return a value of c.missing_value Values returned are sample size (Num) and sum (Sum) Usage qcts.get_sums(Data) Data: 1-day dataset """ li = numpy.ma.where(abs(Data-float(c.missing_value))>c.eps) Num = numpy.size(li) if Num == 0: Sum = c.missing_value elif Num == 48: Sum = numpy.ma.sum(Data[li]) else: x = 0 index = numpy.ma.where(Data.mask == True)[0] if len(index) == 1: x = 1 elif len(index) > 1: for i in range(len(Data)): if Data.mask[i] == True: x = x + 1 if x == 0: Sum = numpy.ma.sum(Data[li]) else: Sum = c.missing_value return Num, Sum def get_qcflag(ds): """ Set up flags during ingest of L1 data. Identifies missing observations as c.missing_value and sets flag value 1 Usage qcts.get_qcflag(ds) ds: data structure """ log.info(' Setting up the QC flags') nRecs = len(ds.series['xlDateTime']['Data']) for ThisOne in ds.series.keys(): ds.series[ThisOne]['Flag'] = numpy.zeros(nRecs,dtype=numpy.int32) index = numpy.where(ds.series[ThisOne]['Data']==c.missing_value)[0] ds.series[ThisOne]['Flag'][index] = numpy.int32(1) def get_synthetic_fsd(ds): """ Purpose: Calculates a time series of synthetic downwelling shortwave radiation. The solar altitude is also output. Useage: qcts.get_synthetic_fsd(ds) Author: PRI Date: Sometime in 2014 """ log.info(' Calculating synthetic Fsd') # get the latitude and longitude lat = float(ds.globalattributes["latitude"]) lon = float(ds.globalattributes["longitude"]) # get the UTC time from the local time ldt_UTC = qcutils.get_UTCfromlocaltime(ds) # get the solar altitude alt_solar = [pysolar.GetAltitude(lat,lon,dt) for dt in ldt_UTC] # get the synthetic downwelling shortwave radiation Fsd_syn = [pysolar.GetRadiationDirect(dt,alt) for dt,alt in zip(ldt_UTC,alt_solar)] Fsd_syn = numpy.ma.array(Fsd_syn) # get the QC flag nRecs = len(Fsd_syn) flag = numpy.zeros(nRecs,dtype=numpy.int32) # add the synthetic downwelling shortwave radiation to the data structure attr = qcutils.MakeAttributeDictionary(long_name='Synthetic downwelling shortwave radiation',units='W/m2', standard_name='surface_downwelling_shortwave_flux_in_air') qcutils.CreateSeries(ds,"Fsd_syn",Fsd_syn,Flag=flag,Attr=attr) # add the solar altitude to the data structure attr = qcutils.MakeAttributeDictionary(long_name='Solar altitude',units='deg', standard_name='not defined') qcutils.CreateSeries(ds,"solar_altitude",alt_solar,Flag=flag,Attr=attr) def InvertSign(ds,ThisOne): log.info(' Inverting sign of '+ThisOne) index = numpy.where(abs(ds.series[ThisOne]['Data']-float(c.missing_value))>c.eps)[0] ds.series[ThisOne]['Data'][index] = float(-1)*ds.series[ThisOne]['Data'][index] def InterpolateOverMissing(ds,series='',maxlen=0): """ Purpose: Interpolate over periods of missing data. Uses linear interpolation. Usage: qcts.InterpolateOverMissing(ds,series=ThisOne,maxlen=0) where ds is the data structure ThisOne is a series label maxlen is the maximum gap length (hours) to be filled by interpolation Side effects: Fills gaps. Author: PRI Date: September 2014 """ # check to see if we need to do anything if maxlen==0: return # check that series is in the data structure if series not in ds.series.keys(): log.error("InterpolateOverMissing: series "+series+" not found in data structure") return # convert the Python datetime to a number DateNum = date2num(ds.series['DateTime']['Data']) # get the data data_org,flag_org,attr_org = qcutils.GetSeries(ds,series) # number of records nRecs = len(data_org) # index of good values iog = numpy.where(abs(data_org-float(c.missing_value))>c.eps)[0] # index of missing values iom = numpy.where(abs(data_org-float(c.missing_value))<=c.eps)[0] # return if there is not enough data to use if len(iog)<2: log.info(' InterpolateOverMissing: Less than 2 good points available for series '+str(series)) return # linear interpolation function f = interpolate.interp1d(DateNum[iog],data_org[iog],bounds_error=False,fill_value=float(c.missing_value)) # interpolate over the whole time series data_int = f(DateNum).astype(numpy.float64) # copy the original flag flag_int = numpy.copy(flag_org) # index of interpolates that are not equal to the missing value index = numpy.where(abs(data_int-float(c.missing_value))>c.eps)[0] # set the flag for these points if len(index)!=0: flag_int[index] = numpy.int32(50) # restore the original good data data_int[iog] = data_org[iog] flag_int[iog] = flag_org[iog] # now replace data in contiguous blocks of length > min with missing data # first, a conditional index, 0 where data is good, 1 where it is missing cond_ind = numpy.zeros(nRecs,dtype=numpy.int32) cond_ind[iom] = 1 cond_bool = (cond_ind==1) # start and stop indices of contiguous blocks for start, stop in qcutils.contiguous_regions(cond_bool): # code to handle minimum segment length goes here duration = stop - start if duration>maxlen: #data_int[start:stop+1] = numpy.float(c.missing_value) #flag_int[start:stop+1] = flag_org[start:stop+1] data_int[start:stop] = numpy.float64(c.missing_value) flag_int[start:stop] = flag_org[start:stop] # put data_int back into the data structure attr_int = dict(attr_org) qcutils.CreateSeries(ds,series,data_int,Flag=flag_int,Attr=attr_int) if 'InterpolateOverMissing2' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', InterpolateOverMissing2' def MassmanStandard(cf,ds,Ta_in='Ta',Ah_in='Ah',ps_in='ps',ustar_in='ustar',ustar_out='ustar',L_in='L',L_out ='L',uw_out='uw',vw_out='vw',wT_out='wT',wA_out='wA',wC_out='wC'): """ Massman corrections. The steps involved are as follows: 1) calculate ustar and L using rotated but otherwise uncorrected covariances """ #if not qcutils.cfoptionskeylogical(cf,Key='Massman'): #return if 'Massman' not in cf: log.info(' Massman section not found in control file, no corrections applied') return #if qcutils.cfkeycheck(cf,Base='FunctionArgs',ThisOne='MassmanVars'): #MArgs = ast.literal_eval(cf['FunctionArgs']['MassmanVars']) #Ta_in = MArgs[0] #Ah_in = MArgs[1] #ps_in = MArgs[2] #if qcutils.cfkeycheck(cf,Base='FunctionArgs',ThisOne='MassmanOuts'): #MOut = ast.literal_eval(cf['FunctionArgs']['MassmanOuts']) #ustar_in = MOut[0] #ustar_out = MOut[1] #L_in = MOut[2] #L_out = MOut[3] #uw_out = MOut[4] #vw_out = MOut[5] #wT_out = MOut[6] #wA_out = MOut[7] #wC_out = MOut[8] log.info(' Correcting for flux loss from spectral attenuation') zmd = float(cf['Massman']['zmd']) # z-d for site if ("angle" in cf["Massman"] and "CSATarm" in cf["Massman"] and "IRGAarm" in cf["Massman"]): # this is the original definition of lateral and longitudinal separation # as coded by James angle = float(cf['Massman']['angle']) # CSAT3-IRGA separation angle CSATarm = float(cf['Massman']['CSATarm']) # CSAT3 mounting distance IRGAarm = float(cf['Massman']['IRGAarm']) # IRGA mounting distance lLat = numpy.ma.sin(numpy.deg2rad(angle)) * IRGAarm lLong = CSATarm - (numpy.ma.cos(numpy.deg2rad(angle)) * IRGAarm) elif ("north_separation" in cf["Massman"] and "east_separation" in cf["Massman"]): # the following is the definition of lateral and longitudinal separation # used in EddyPro, it is not equivalent to the one used above nsep = numpy.float(cf["Massman"]["north_separation"]) esep = numpy.float(cf["Massman"]["east_separation"]) lLat = numpy.sqrt(nsep*nsep + esep*esep) lLong = numpy.float(0) else: msg = " Required separation information not found in Massman section of control file" log.error(msg) return # *** Massman_1stpass starts here *** # The code for the first and second passes is very similar. It would be useful to make them the # same and put into a loop to reduce the number of lines in this function. # calculate ustar and Monin-Obukhov length from rotated but otherwise uncorrected covariances Ta,f,a = qcutils.GetSeriesasMA(ds,Ta_in) Ah,f,a = qcutils.GetSeriesasMA(ds,Ah_in) ps,f,a = qcutils.GetSeriesasMA(ds,ps_in) nRecs = numpy.size(Ta) u,f,a = qcutils.GetSeriesasMA(ds,'u') uw,f,a = qcutils.GetSeriesasMA(ds,'uw') vw,f,a = qcutils.GetSeriesasMA(ds,'vw') wT,f,a = qcutils.GetSeriesasMA(ds,'wT') wC,f,a = qcutils.GetSeriesasMA(ds,'wC') wA,f,a = qcutils.GetSeriesasMA(ds,'wA') if ustar_in not in ds.series.keys(): ustarm = numpy.ma.sqrt(numpy.ma.sqrt(uw ** 2 + vw ** 2)) else: ustarm,f,a = qcutils.GetSeriesasMA(ds,ustar_in) if L_in not in ds.series.keys(): Lm = mf.molen(Ta, Ah, ps, ustarm, wT, fluxtype='kinematic') else: Lm,f,a = qcutils.GetSeriesasMA(ds,Lm_in) # now calculate z on L zoLm = zmd / Lm # start calculating the correction coefficients for approximate corrections # create nxMom, nxScalar and alpha series with their unstable values by default nxMom, nxScalar, alpha = qcutils.nxMom_nxScalar_alpha(zoLm) # now calculate the fxMom and fxScalar coefficients fxMom = nxMom * u / zmd fxScalar = nxScalar * u / zmd # compute spectral filters tau_sonic_law_4scalar = c.lwVert / (8.4 * u) tau_sonic_laT_4scalar = c.lTv / (4.0 * u) tau_irga_la = (c.lIRGA / (4.0 * u)) tau_irga_va = (0.2+0.4*c.dIRGA/c.lIRGA)*(c.lIRGA/u) tau_irga_bw = 0.016 tau_irga_lat = (lLat / (1.1 * u)) tau_irga_lon = (lLong / (1.05 * u)) tao_eMom = numpy.ma.sqrt(((c.lwVert / (5.7 * u)) ** 2) + ((c.lwHor / (2.8 * u)) ** 2)) tao_ewT = numpy.ma.sqrt((tau_sonic_law_4scalar ** 2) + (tau_sonic_laT_4scalar ** 2)) tao_ewIRGA = numpy.ma.sqrt((tau_sonic_law_4scalar ** 2) + (tau_irga_la ** 2) + (tau_irga_va ** 2) + (tau_irga_bw ** 2) + (tau_irga_lat ** 2) + (tau_irga_lon ** 2)) tao_b = c.Tb / 2.8 # calculate coefficients bMom = qcutils.bp(fxMom,tao_b) bScalar = qcutils.bp(fxScalar,tao_b) pMom = qcutils.bp(fxMom,tao_eMom) pwT = qcutils.bp(fxScalar,tao_ewT) # calculate corrections for momentum and scalars rMom = qcutils.r(bMom, pMom, alpha) # I suspect that rMom and rwT are the same functions rwT = qcutils.r(bScalar, pwT, alpha) # determine approximately-true Massman fluxes uwm = uw / rMom vwm = vw / rMom wTm = wT / rwT # *** Massman_1stpass ends here *** # *** Massman_2ndpass starts here *** # we have calculated the first pass corrected momentum and temperature covariances, now we use # these to calculate the final corrections # first, get the 2nd pass corrected friction velocity and Monin-Obukhov length ustarm = numpy.ma.sqrt(numpy.ma.sqrt(uwm ** 2 + vwm ** 2)) Lm = mf.molen(Ta, Ah, ps, ustarm, wTm, fluxtype='kinematic') zoLm = zmd / Lm nxMom, nxScalar, alpha = qcutils.nxMom_nxScalar_alpha(zoLm) fxMom = nxMom * (u / zmd) fxScalar = nxScalar * (u / zmd) # calculate coefficients bMom = qcutils.bp(fxMom,tao_b) bScalar = qcutils.bp(fxScalar,tao_b) pMom = qcutils.bp(fxMom,tao_eMom) pwT = qcutils.bp(fxScalar,tao_ewT) pwIRGA = qcutils.bp(fxScalar,tao_ewIRGA) # calculate corrections for momentum and scalars rMom = qcutils.r(bMom, pMom, alpha) rwT = qcutils.r(bScalar, pwT, alpha) rwIRGA = qcutils.r(bScalar, pwIRGA, alpha) # determine true fluxes uwM = uw / rMom vwM = vw / rMom wTM = wT / rwT wCM = wC / rwIRGA wAM = wA / rwIRGA ustarM = numpy.ma.sqrt(numpy.ma.sqrt(uwM ** 2 + vwM ** 2)) LM = mf.molen(Ta, Ah, ps, ustarM, wTM, fluxtype='kinematic') # write the 2nd pass Massman corrected covariances to the data structure attr = qcutils.MakeAttributeDictionary(long_name='Massman true ustar',units='m/s') qcutils.CreateSeries(ds,ustar_out,ustarM,FList=['uw','vw'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Massman true Obukhov Length',units='m') qcutils.CreateSeries(ds,L_out,LM,FList=[Ta_in,Ah_in,ps_in,'wT'],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Massman true Cov(uw)',units='m2/s2') qcutils.CreateSeries(ds,uw_out,uwM,FList=['uw',L_out],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Massman true Cov(vw)',units='m2/s2') qcutils.CreateSeries(ds,vw_out,vwM,FList=['vw',L_out],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Massman true Cov(wT)',units='mC/s') qcutils.CreateSeries(ds,wT_out,wTM,FList=['wT',L_out],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Massman true Cov(wA)',units='g/m2/s') qcutils.CreateSeries(ds,wA_out,wAM,FList=['wA',L_out],Attr=attr) attr = qcutils.MakeAttributeDictionary(long_name='Massman true Cov(wC)',units='mg/m2/s') qcutils.CreateSeries(ds,wC_out,wCM,FList=['wC',L_out],Attr=attr) # *** Massman_2ndpass ends here *** if qcutils.cfkeycheck(cf,Base='General',ThisOne='MassmanFlag') and cf['General']['MassmanFlag'] == 'True': keys = [ustar_out,L_out,uw_out,vw_out,wT_out,wA_out,wC_out] for ThisOne in keys: testseries,f,a = qcutils.GetSeriesasMA(ds,ThisOne) mask = numpy.ma.getmask(testseries) index = numpy.where(mask.astype(int)==1) ds.series[ThisOne]['Flag'][index] = numpy.int32(12) def MergeSeriesUsingDict(ds,merge_order=""): """ Merge series as defined in the ds.merge dictionary.""" # check that ds has a "merge" attribute if "merge" not in dir(ds): raise Exception("MergeSeriesUsingDict: No merge dictionary in ds") if merge_order not in ds.merge.keys(): msg = "MergeSeriesUsingDict: merge_order ("+merge_order+") not found in merge dictionary" log.info(msg) return # loop over the entries in ds.merge for target in ds.merge[merge_order].keys(): srclist = ds.merge[merge_order][target]["source"] log.info(' Merging '+str(srclist)+' ==> '+target) if srclist[0] not in ds.series.keys(): log.error(' MergeSeries: primary input series '+srclist[0]+' not found') continue data = ds.series[srclist[0]]['Data'].copy() flag1 = ds.series[srclist[0]]['Flag'].copy() flag2 = ds.series[srclist[0]]['Flag'].copy() attr = ds.series[srclist[0]]['Attr'].copy() SeriesNameString = srclist[0] tmplist = list(srclist) tmplist.remove(tmplist[0]) for label in tmplist: if label in ds.series.keys(): SeriesNameString = SeriesNameString+', '+label index = numpy.where(numpy.mod(flag1,10)==0)[0] # find the elements with flag = 0, 10, 20 etc flag2[index] = 0 # set them all to 0 if label=="Fg": index = numpy.where(flag2==22)[0] if len(index)!=0: flag2[index] = 0 index = numpy.where(flag2!=0)[0] # index of flag values other than 0,10,20,30 ... data[index] = ds.series[label]['Data'][index].copy() # replace bad primary with good secondary flag1[index] = ds.series[label]['Flag'][index].copy() else: log.error(" MergeSeries: secondary input series "+label+" not found") attr["long_name"] = attr["long_name"]+", merged from " + SeriesNameString qcutils.CreateSeries(ds,target,data,Flag=flag1,Attr=attr) del ds.merge[merge_order] def MergeHumidities(cf,ds,convert_units=False): if "Ah" not in cf["Variables"] and "RH" not in cf["Variables"] and "q" not in cf["Variables"]: log.error(" MergeHumidities: No humidities found in control file, returning ...") return if "Ah" in cf["Variables"]: MergeSeries(cf,ds,"Ah",[0,10],convert_units=convert_units) qcutils.CheckUnits(ds,"Ah","g/m3",convert_units=True) if "RH" in cf["Variables"]: MergeSeries(cf,ds,'RH',[0,10],convert_units=convert_units) qcutils.CheckUnits(ds,"RH","%",convert_units=True) if "q" in cf["Variables"]: MergeSeries(cf,ds,'q',[0,10],convert_units=convert_units) qcutils.CheckUnits(ds,"q","kg/kg",convert_units=False) def MergeSeries(cf,ds,series,okflags,convert_units=False): """ Merge two series of data to produce one series containing the best data from both. Calling syntax is: MergeSeries(cf,ds,series,okflags) where ds is the data structure containing all series series (str) is the label of the destination series okflags (list) is a list of QC flag values for which the data is considered acceptable If the QC flag for Primary is in okflags, the value from Primary is placed in destination. If the QC flag for Primary is not in okflags but the QC flag for Secondary is, the value from Secondary is placed in Destination. """ # check to see if the series is specified in the control file section = qcutils.get_cfsection(cf,series=series) if len(section)==0: return # check to see if the entry for series in the control file has the MergeSeries key if 'MergeSeries' not in cf[section][series].keys(): return # check to see if the series has already been merged if series in ds.mergeserieslist: return # now get the source list and the standard name srclist, standardname = qcutils.GetMergeSeriesKeys(cf,series,section=section) nSeries = len(srclist) if nSeries==0: log.warning(' MergeSeries: no input series specified for '+str(series)) return if nSeries==1: log.info(' Merging '+str(srclist)+'==>'+series) if srclist[0] not in ds.series.keys(): log.warning(' MergeSeries: primary input series '+srclist[0]+' not found for '+str(series)) return mdata,mflag,mattr = qcutils.GetSeriesasMA(ds,srclist[0]) SeriesNameString = srclist[0] else: log.info(' Merging '+str(srclist)+'==>'+series) if srclist[0] not in ds.series.keys(): log.warning(' MergeSeries: primary input series '+srclist[0]+' not found for '+str(series)) return primary_series = srclist[0] mdata,mflag,mattr = qcutils.GetSeriesasMA(ds,primary_series) SeriesNameString = primary_series srclist.remove(primary_series) for secondary_series in srclist: if secondary_series in ds.series.keys(): ndata,nflag,nattr = qcutils.GetSeriesasMA(ds,secondary_series) if nattr["units"]!=mattr["units"]: msg = " "+secondary_series+" units don't match "+primary_series+" units" log.warning(msg) if convert_units: msg = " "+secondary_series+" units converted from "+nattr["units"]+" to "+mattr["units"] log.info(msg) ndata = qcutils.convert_units_func(ds,ndata,nattr["units"],mattr["units"]) else: msg = " MergeSeries: "+secondary_series+" ignored" log.error(msg) continue SeriesNameString = SeriesNameString+', '+secondary_series indx1 = numpy.zeros(numpy.size(mdata),dtype=numpy.int) indx2 = numpy.zeros(numpy.size(ndata),dtype=numpy.int) for okflag in okflags: index = numpy.where(mflag==okflag)[0] # index of acceptable primary values indx1[index] = 1 # set primary index to 1 when primary good index = numpy.where(nflag==okflag)[0] # same process for secondary indx2[index] = 1 index = numpy.where((indx1!=1)&(indx2==1))[0] # index where primary bad but secondary good mdata[index] = ndata[index] # replace bad primary with good secondary mflag[index] = nflag[index] else: log.warning(' MergeSeries: secondary input series'+secondary_series+'not found') ds.mergeserieslist.append(series) mattr["long_name"] = mattr["long_name"]+", merged from " + SeriesNameString qcutils.CreateSeries(ds,series,mdata,Flag=mflag,Attr=mattr) def PT100(ds,T_out,R_in,m): log.info(' Calculating temperature from PT100 resistance') R,f,a = qcutils.GetSeriesasMA(ds,R_in) R = m*R T = (-c.PT100_alpha+numpy.sqrt(c.PT100_alpha**2-4*c.PT100_beta*(-R/100+1)))/(2*c.PT100_beta) attr = qcutils.MakeAttributeDictionary(long_name='Calculated PT100 temperature using '+str(R_in),units='degC') qcutils.CreateSeries(ds,T_out,T,FList=[R_in],Attr=attr) def ReplaceRotatedCovariance(cf,ds,rot_cov_label,non_cov_label): log.info(' Replacing missing '+rot_cov_label+' when '+non_cov_label+' is good') cr_data,cr_flag,cr_attr = qcutils.GetSeriesasMA(ds,rot_cov_label) cn_data,cn_flag,cn_attr = qcutils.GetSeriesasMA(ds,non_cov_label) index = numpy.where((numpy.ma.getmaskarray(cr_data)==True)& (numpy.ma.getmaskarray(cn_data)==False))[0] #index = numpy.ma.where((numpy.ma.getmaskarray(cr_data)==True)& #(numpy.ma.getmaskarray(cn_data)==False))[0] if len(index)!=0: ds.series[rot_cov_label]['Data'][index] = cn_data[index] ds.series[rot_cov_label]['Flag'][index] = numpy.int32(20) return def ReplaceOnDiff(cf,ds,series=''): # Gap fill using data from alternate sites specified in the control file ts = ds.globalattributes['time_step'] if len(series)!=0: ds_alt = {} # create a dictionary for the data from alternate sites open_ncfiles = [] # create an empty list of open netCDF files for ThisOne in series: # loop over variables in the series list # has ReplaceOnDiff been specified for this series? if qcutils.incf(cf,ThisOne) and qcutils.haskey(cf,ThisOne,'ReplaceOnDiff'): # loop over all entries in the ReplaceOnDiff section for Alt in cf['Variables'][ThisOne]['ReplaceOnDiff'].keys(): if 'FileName' in cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt].keys(): alt_filename = cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt]['FileName'] if 'AltVarName' in cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt].keys(): alt_varname = cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt]['AltVarName'] else: alt_varname = ThisOne if alt_filename not in open_ncfiles: n = len(open_ncfiles) open_ncfiles.append(alt_filename) ds_alt[n] = qcio.nc_read_series_file(alt_filename) else: n = open_ncfiles.index(alt_filename) if 'Transform' in cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt].keys(): AltDateTime = ds_alt[n].series['DateTime']['Data'] AltSeriesData = ds_alt[n].series[alt_varname]['Data'] TList = ast.literal_eval(cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt]['Transform']) for TListEntry in TList: qcts.TransformAlternate(TListEntry,AltDateTime,AltSeriesData,ts=ts) if 'Range' in cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt].keys(): RList = ast.literal_eval(cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt]['Range']) for RListEntry in RList: qcts.ReplaceWhenDiffExceedsRange(ds.series['DateTime']['Data'],ds.series[ThisOne], ds.series[ThisOne],ds_alt[n].series[alt_varname], RListEntry) elif 'AltVarName' in cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt].keys(): alt_varname = ThisOne if 'Range' in cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt].keys(): RList = ast.literal_eval(cf['Variables'][ThisOne]['ReplaceOnDiff'][Alt]['Range']) for RListEntry in RList: qcts.ReplaceWhenDiffExceedsRange(ds.series['DateTime']['Data'],ds.series[ThisOne], ds.series[ThisOne],ds.series[alt_varname], RListEntry) else: log.error('ReplaceOnDiff: Neither AltFileName nor AltVarName given in control file') else: log.error('ReplaceOnDiff: No input series specified') def ReplaceWhereMissing(Destination,Primary,Secondary,FlagOffset=None,FlagValue=None): #print time.strftime('%X')+' Merging series '+Primary+' and '+Secondary+' into '+Destination p_data = Primary['Data'].copy() p_flag = Primary['Flag'].copy() s_data = Secondary['Data'].copy() s_flag = Secondary['Flag'].copy() if numpy.size(p_data)>numpy.size(s_data): p_data = p_data[0:numpy.size(s_data)] if numpy.size(s_data)>numpy.size(p_data): s_data = s_data[0:numpy.size(p_data)] index = numpy.where((abs(p_data-float(c.missing_value))<c.eps)& (abs(s_data-float(c.missing_value))>c.eps))[0] p_data[index] = s_data[index] if FlagValue is None and FlagOffset is not None: p_flag[index] = s_flag[index] + numpy.int32(FlagOffset) elif FlagValue is not None and FlagOffset is None: p_flag[index] = numpy.int32(FlagValue) else: p_flag[index] = s_flag[index] Destination['Data'] = Primary['Data'].copy() Destination['Flag'] = Primary['Flag'].copy() Destination['Data'][0:len(p_data)] = p_data Destination['Flag'][0:len(p_flag)] = p_flag Destination['Attr']['long_name'] = 'Merged from original and alternate' Destination['Attr']['units'] = Primary['Attr']['units'] def ReplaceWhenDiffExceedsRange(DateTime,Destination,Primary,Secondary,RList): #print time.strftime('%X')+' Replacing '+Primary+' with '+Secondary+' when difference exceeds threshold' # get the primary data series p_data = numpy.ma.array(Primary['Data']) p_flag = Primary['Flag'].copy() # get the secondary data series s_data = numpy.ma.array(Secondary['Data']) s_flag = Secondary['Flag'].copy() # truncate the longest series if the sizes do not match if numpy.size(p_data)!=numpy.size(s_data): log.warning(' ReplaceWhenDiffExceedsRange: Series lengths differ, longest will be truncated') if numpy.size(p_data)>numpy.size(s_data): p_data = p_data[0:numpy.size(s_data)] if numpy.size(s_data)>numpy.size(p_data): s_data = s_data[0:numpy.size(p_data)] # get the difference between the two data series d_data = p_data-s_data # normalise the difference if requested if RList[3]=='s': d_data = (p_data-s_data)/s_data elif RList[3]=='p': d_data = (p_data-s_data)/p_data #si = qcutils.GetDateIndex(DateTime,RList[0],0) #ei = qcutils.GetDateIndex(DateTime,RList[1],0) Range = RList[2] Upper = float(Range[0]) Lower = float(Range[1]) index = numpy.ma.where((abs(d_data)<Lower)|(abs(d_data)>Upper)) p_data[index] = s_data[index] p_flag[index] = 35 Destination['Data'] = numpy.ma.filled(p_data,float(c.missing_value)) Destination['Flag'] = p_flag.copy() Destination['Attr']['long_name'] = 'Replaced original with alternate when difference exceeded threshold' Destination['Attr']['units'] = Primary['Attr']['units'] def savitzky_golay(y, window_size, order, deriv=0): ''' Apply Savitsky-Golay low-pass filter to data.''' try: window_size = numpy.abs(numpy.int(window_size)) order = numpy.abs(numpy.int(order)) except ValueError, msg: raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order+1) half_window = (window_size -1) // 2 # precompute coefficients b = numpy.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = numpy.linalg.pinv(b).A[deriv] # pad the signal at the extremes with # values taken from the signal itself firstvals = y[0] - numpy.abs( y[1:half_window+1][::-1] - y[0] ) lastvals = y[-1] + numpy.abs(y[-half_window-1:-1][::-1] - y[-1]) y = numpy.concatenate((firstvals, y, lastvals)) return numpy.convolve( m, y, mode='valid') def Square(Series): tmp = numpy.array([c.missing_value]*numpy.size(Series),Series.dtype) index = numpy.where(Series!=float(c.missing_value))[0] tmp[index] = Series[index] ** 2 return tmp def SquareRoot(Series): tmp = numpy.array([c.missing_value]*numpy.size(Series),Series.dtype) index = numpy.where(Series!=float(c.missing_value))[0] tmp[index] = Series[index] ** .5 return tmp def TaFromTv(cf,ds,Ta_out='Ta_CSAT',Tv_in='Tv_CSAT',Ah_in='Ah',RH_in='RH',q_in='q',ps_in='ps'): # Calculate the air temperature from the virtual temperature, the # absolute humidity and the pressure. # NOTE: the virtual temperature is used in place of the air temperature # to calculate the vapour pressure from the absolute humidity, the # approximation involved here is of the order of 1%. log.info(' Calculating Ta from Tv') # check to see if we have enough data to proceed if Tv_in not in ds.series.keys(): log.error(" TaFromTv: sonic virtual temperature ("+str(Tv_in)+") not found in data structure") return if Ah_in not in ds.series.keys() and RH_in not in ds.series.keys() and q_in not in ds.series.keys(): labstr = str(Ah_in)+","+str(RH_in)+","+str(q_in) log.error(" TaFromTv: no humidity data ("+labstr+") found in data structure") return if ps_in not in ds.series.keys(): log.error(" TaFromTv: pressure ("+str(ps_in)+") not found in data structure") return # we seem to have enough to continue Tv,f,a = qcutils.GetSeriesasMA(ds,Tv_in) ps,f,a = qcutils.GetSeriesasMA(ds,ps_in) if Ah_in in ds.series.keys(): Ah,f,a = qcutils.GetSeriesasMA(ds,Ah_in) vp = mf.vapourpressure(Ah,Tv) mr = mf.mixingratio(ps,vp) q = mf.specifichumidity(mr) elif RH_in in ds.series.keys(): RH,f,a = qcutils.GetSeriesasMA(ds,RH_in) q = mf.specifichumidityfromRH(RH,Tv,ps) elif q_in in ds.series.keys(): q,f,a = qcutils.GetSeriesasMA(ds,q_in) Ta_data = mf.tafromtv(Tv,q) nRecs = int(ds.globalattributes['nc_nrecs']) Ta_flag = numpy.zeros(nRecs,numpy.int32) mask = numpy.ma.getmask(Ta_data) index = numpy.where(mask.astype(numpy.int32)==1) Ta_flag[index] = 15 attr = qcutils.MakeAttributeDictionary(long_name='Ta calculated from Tv using '+Tv_in,units='C',standard_name='air_temperature') qcutils.CreateSeries(ds,Ta_out,Ta_data,Flag=Ta_flag,Attr=attr) if 'TaFromTv' not in ds.globalattributes['Functions']: ds.globalattributes['Functions'] = ds.globalattributes['Functions']+', TaFromTv' def TransformAlternate(TList,DateTime,Series,ts=30): # Apply polynomial transform to data series being used as replacement data for gap filling #print time.strftime('%X')+' Applying polynomial transform to '+ThisOne si = qcutils.GetDateIndex(DateTime,TList[0],ts=ts,default=0,match='exact') ei = qcutils.GetDateIndex(DateTime,TList[1],ts=ts,default=-1,match='exact') Series = numpy.ma.masked_where(abs(Series-float(c.missing_value))<c.eps,Series) Series[si:ei] = qcutils.polyval(TList[2],Series[si:ei]) Series = numpy.ma.filled(Series,float(c.missing_value))
OzFlux/OzFluxQC
scripts/qcts.py
Python
gpl-3.0
133,038
[ "NetCDF" ]
df051679f1726d4c656c44e697f4088a4f8ddf4438a49304d0a03af1caf406f7
# -*- coding: utf-8 -*- # TAMkin is a post-processing toolkit for normal mode analysis, thermochemistry # and reaction kinetics. # Copyright (C) 2008-2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, An Ghysels # <An.Ghysels@UGent.be> and Matthias Vandichel <Matthias.Vandichel@UGent.be> # Center for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all # rights reserved unless otherwise stated. # # This file is part of TAMkin. # # TAMkin is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your option) any later version. # # In addition to the regulations of the GNU General Public License, # publications and communications based in parts on this program or on # parts of this program are required to cite the following article: # # "TAMkin: A Versatile Package for Vibrational Analysis and Chemical Kinetics", # An Ghysels, Toon Verstraelen, Karen Hemelsoet, Michel Waroquier and Veronique # Van Speybroeck, Journal of Chemical Information and Modeling, 2010, 50, # 1736-1750W # http://dx.doi.org/10.1021/ci100099g # # TAMkin 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/> # # -- from __future__ import print_function, division from tamkin.nma import NMA from molmod import angstrom, lightspeed, centimeter from molmod.io import XYZWriter from molmod.periodic import periodic import numpy as np __all__ = ["dump_modes_xyz", "dump_modes_molden", "dump_modes_gaussian"] def dump_modes_xyz(nma, indexes=0, prefix="mode", amplitude=5.0*angstrom, frames=36): """Write XYZ trajectory file(s) that vizualize internal mode(s) Arguments: | nma -- an object that specifies the normal modes, several formats are supported: (i) a Tamkin NMA object, (ii) a 3-tuple with reference coordinates, mass-unweighted mode(s) and atom numbers or (iii) a 4-tuple with reference coordinates, mass- weighted mode(s), atom numbers and a masses3 vector. the latter is a vector with 3*N elements containing the masses of the atoms in groups of three. Optional arguments: | indexes -- the index or a list of indexes of modes that must be written to trajectory files [default=0] | prefix -- a prefix used for the output files. the generated trajectory filenames have the format prefix.index.xyz [default="mode"] | amplitude -- the amplitude of the normal mode vibration in atomic untis [default=5*angstrom] | frames -- the number of frames written to the trajectory file [default=36] """ if isinstance(nma, NMA): coordinates = nma.coordinates modes = nma.modes numbers = nma.numbers masses3 = nma.masses3 elif hasattr(nma, "__len__") and len(nma)==3: coordinates, modes, numbers = nma masses3 = None elif hasattr(nma, "__len__") and len(nma)==4: coordinates, modes, numbers, masses3 = nma else: raise TypeError("Could not understand first argument. Check documentation.") if not hasattr(indexes, "__len__"): indexes = [indexes] if len(modes.shape) == 1: modes = modes.reshape((-1,1)) symbols = [periodic[n].symbol for n in numbers] for index in indexes: filename = "%s.%i.xyz" % (prefix, index) mode = modes[:,index] if masses3 is not None: mode /= np.sqrt(masses3) mode /= np.linalg.norm(mode) xyz_writer = XYZWriter(filename, symbols) for frame in range(frames): factor = amplitude*np.sin(2*np.pi*float(frame)/frames) xyz_writer.dump("frame %i" % frame, coordinates + factor*mode.reshape((-1,3))) del xyz_writer def dump_modes_gaussian(filename, nma, selected=None): """Write freqs and modes to a file in the Gaussian log format. Arguments: | filename -- modes are written to this file, can be read by Molden (visualization program) | nma -- an NMA object or a tuple or list with five elements: modes, frequencies, masses, numbers, coordinates. See _make_moldenfile for details. Optional argument: | selected -- Selection of modes for which to make trajectories. This can be a list or array of mode indices (length <= N), or an array of booleans (length = N). The output file will look like a stripped Gaussian03 or Gaussian09 log file. It is sufficient to visualize the modes in Molden, Openbabel or Avogadro. """ ### A) Parse the NMA argument if isinstance(nma, NMA): # NMA object modes, freqs, masses, numbers, coordinates = \ nma.modes, nma.freqs, nma.masses, nma.numbers, nma.coordinates elif hasattr(nma, "__len__") and len(nma) == 5 and not isinstance(nma, np.ndarray): # [modes, freqs, ...] or (modes, freqs, ...) modes, freqs, masses, numbers, coordinates = nma else: raise TypeError("nma argument has wrong type") ### B) Select some modes if selected is not None: modes = np.take(modes, selected, 1) # modes in columns freqs = freqs[selected] masses = masses[selected] numbers = numbers[selected] coordinates = coordinates[selected] ### C) convert modes to the right convention masses3_sqrt1 = np.array(sum([[1/m,1/m,1/m] for m in np.sqrt(masses)],[])) nmode = modes.shape[1] modes = modes.copy() # avoid modifying the given modes for imode in range(nmode): modes[:,imode] *= masses3_sqrt1 modes[:,imode] /= np.linalg.norm(modes[:,imode]) ### D) Define some multiline text blobs that are used below. header = """\ Entering Gaussian System, Link 0=g09 This file is generated from the dump_modes_gaussian function in the file trajectory.py of TAMkin. Please note, that this is a "fake" output; TAMkin doesn't compute intensities. This file should be readable by Molden, Openbabel and Avogadro. Gaussian, Inc # Fake method line for openbabel """ header_coordinates = """\ Standard orientation: --------------------------------------------------------------------- Center Atomic Atomic Coordinates (Angstroms) Number Number Type X Y Z ---------------------------------------------------------------------""" header_basisfunctions = """\ --------------------------------------------------------------------- basis functions primitive gaussians alpha electrons beta electrons **********************************************************************""" header_freq = """\ Harmonic frequencies (cm**-1), IR intensities (KM/Mole), Raman scattering activities (A**4/AMU), Raman depolarization ratios, reduced masses (AMU), force constants (mDyne/A) and normal coordinates:""" txt_freqbelow_1 = """\ Red. masses -- 0.0000 Frc consts -- 0.0000 IR Inten -- 0.0000 Atom AN X Y Z""" txt_freqbelow_2 = """\ Red. masses -- 0.0000 0.0000 Frc consts -- 0.0000 0.0000 IR Inten -- 0.0000 0.0000 Atom AN X Y Z X Y Z""" txt_freqbelow_3 = """\ Red. masses -- 0.0000 0.0000 0.0000 Frc consts -- 0.0000 0.0000 0.0000 IR Inten -- 0.0000 0.0000 0.0000 Atom AN X Y Z X Y Z X Y Z""" txt_freqbelow = [txt_freqbelow_1, txt_freqbelow_2, txt_freqbelow_3] ### E) Actual writing of the fake log file with open(filename, "w") as f: print(header, file=f) ### E1) ATOM PART assert modes.shape[0] % 3 == 0 natom = modes.shape[0] // 3 print(header_coordinates, file=f) for iatom in range(natom): print('%5d %10d %13s %15f %11f %11f' %( iatom + 1, numbers[iatom], "0", coordinates[iatom,0]/angstrom, coordinates[iatom,1]/angstrom, coordinates[iatom,2]/angstrom), file=f) ### E2) ORBITAL PART print(header_basisfunctions, file=f) print(" ", file=f) # this part is just empty ### D3) FREQUENCY PART # Modes are written in sections with three columns each. print(header_freq, file=f) # istart: the current mode index, will be incremented by 3 in each iteration. istart = 0 while istart < nmode: # select modes and freqs for this block iend = min(istart+3, nmode) ncol = iend - istart # number of columns in section # print stuff to file # - mode indexes for imode in range(istart, iend): print('%22d' % (imode + 1), end="", file=f) print(file=f) # - (fake) symmetry info print(' '.join([" ?A"]*ncol), file=f) # - frequencies converted to inverse centimeters print(' Frequencies --', end="", file=f) for imode in range(istart, iend): print('{:11.4f}'.format(freqs[imode]/lightspeed*centimeter), end="", file=f) if imode != iend-1: print(' ', end="", file=f) print(file=f) # - a blob of text below the frequencies print(txt_freqbelow[ncol-1], file=f) # - the modes for iatom in range(natom): print('%6d %3d' % (iatom + 1, numbers[iatom]), end="", file=f) for imode in range(istart, iend): print('%8.2f %6.2f %6.2f' % ( modes[3*iatom, imode], modes[3*iatom+1, imode], modes[3*iatom+2, imode]), end="", file=f) print(file=f) # prepare for next iteration istart = iend print(" Normal termination of Gaussian 09.", file=f) # For backward compatibility with TAMkin before version 1.0.2 dump_modes_molden = dump_modes_gaussian
molmod/tamkin
tamkin/io/trajectory.py
Python
gpl-3.0
10,931
[ "Avogadro", "Gaussian" ]
8c1d7566ef71f5b3b074c47e3cfb72028f3fa007dee6e1154c60e8136226e40a
"""Test functions for linalg._solve_toeplitz module """ from __future__ import division, print_function, absolute_import import numpy as np from scipy.linalg._solve_toeplitz import levinson from scipy.linalg import solve, toeplitz, solve_toeplitz from numpy.testing import (run_module_suite, assert_equal, assert_allclose, assert_raises) from numpy.testing.decorators import knownfailureif def test_solve_equivalence(): # For toeplitz matrices, solve_toeplitz() should be equivalent to solve(). random = np.random.RandomState(1234) for n in (1, 2, 3, 10): c = random.randn(n) if random.rand() < 0.5: c = c + 1j * random.randn(n) r = random.randn(n) if random.rand() < 0.5: r = r + 1j * random.randn(n) y = random.randn(n) if random.rand() < 0.5: y = y + 1j * random.randn(n) # Check equivalence when both the column and row are provided. actual = solve_toeplitz((c,r), y) desired = solve(toeplitz(c, r=r), y) assert_allclose(actual, desired) # Check equivalence when the column is provided but not the row. actual = solve_toeplitz(c, b=y) desired = solve(toeplitz(c), y) assert_allclose(actual, desired) def test_multiple_rhs(): random = np.random.RandomState(1234) c = random.randn(4) r = random.randn(4) for offset in [0, 1j]: for yshape in ((4,), (4, 3), (4, 3, 2)): y = random.randn(*yshape) + offset actual = solve_toeplitz((c,r), b=y) desired = solve(toeplitz(c, r=r), y) assert_equal(actual.shape, yshape) assert_equal(desired.shape, yshape) assert_allclose(actual, desired) def test_zero_diag_error(): # The Levinson-Durbin implementation fails when the diagonal is zero. random = np.random.RandomState(1234) n = 4 c = random.randn(n) r = random.randn(n) y = random.randn(n) c[0] = 0 assert_raises(np.linalg.LinAlgError, solve_toeplitz, (c, r), b=y) def test_wikipedia_counterexample(): # The Levinson-Durbin implementation also fails in other cases. # This example is from the talk page of the wikipedia article. random = np.random.RandomState(1234) c = [2, 2, 1] y = random.randn(3) assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y) def test_reflection_coeffs(): # check that that the partial solutions are given by the reflection # coefficients random = np.random.RandomState(1234) y_d = random.randn(10) y_z = random.randn(10) + 1j reflection_coeffs_d = [1] reflection_coeffs_z = [1] for i in range(2, 10): reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1]) reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1]) y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1])) y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1])) _, ref_d = levinson(y_d_concat, b=y_d[1:]) _, ref_z = levinson(y_z_concat, b=y_z[1:]) assert_allclose(reflection_coeffs_d, ref_d[:-1]) assert_allclose(reflection_coeffs_z, ref_z[:-1]) @knownfailureif(True, 'Instability of Levinson iteraton') def test_unstable(): # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with # Partial Pivoting for Matrices with Displacement Structure" # Mathematics of Computation, 64, 212 (1995), pp 1557-1576 # which can be unstable for levinson recursion. # other fast toeplitz solvers such as GKO or Burg should be better. random = np.random.RandomState(1234) n = 100 c = 0.9 ** (np.arange(n)**2) y = random.randn(n) solution1 = solve_toeplitz(c, b=y) solution2 = solve(toeplitz(c), y) assert_allclose(solution1, solution2) if __name__ == '__main__': run_module_suite()
valexandersaulys/airbnb_kaggle_contest
venv/lib/python3.4/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
Python
gpl-2.0
3,975
[ "Gaussian" ]
c7a0167d8422c100aa63563cd5f1748ed985e7465793614d98054c94cff2f60c
""" .. _statsrefmanual: ========================================== Statistical functions (:mod:`scipy.stats`) ========================================== .. currentmodule:: scipy.stats This module contains a large number of probability distributions as well as a growing library of statistical functions. Each univariate distribution is an instance of a subclass of `rv_continuous` (`rv_discrete` for discrete distributions): .. autosummary:: :toctree: generated/ rv_continuous rv_discrete rv_histogram Continuous distributions ======================== .. autosummary:: :toctree: generated/ alpha -- Alpha anglit -- Anglit arcsine -- Arcsine argus -- Argus beta -- Beta betaprime -- Beta Prime bradford -- Bradford burr -- Burr (Type III) burr12 -- Burr (Type XII) cauchy -- Cauchy chi -- Chi chi2 -- Chi-squared cosine -- Cosine crystalball -- Crystalball dgamma -- Double Gamma dweibull -- Double Weibull erlang -- Erlang expon -- Exponential exponnorm -- Exponentially Modified Normal exponweib -- Exponentiated Weibull exponpow -- Exponential Power f -- F (Snecdor F) fatiguelife -- Fatigue Life (Birnbaum-Saunders) fisk -- Fisk foldcauchy -- Folded Cauchy foldnorm -- Folded Normal frechet_r -- Deprecated. Alias for weibull_min frechet_l -- Deprecated. Alias for weibull_max genlogistic -- Generalized Logistic gennorm -- Generalized normal genpareto -- Generalized Pareto genexpon -- Generalized Exponential genextreme -- Generalized Extreme Value gausshyper -- Gauss Hypergeometric gamma -- Gamma gengamma -- Generalized gamma genhalflogistic -- Generalized Half Logistic geninvgauss -- Generalized Inverse Gaussian gilbrat -- Gilbrat gompertz -- Gompertz (Truncated Gumbel) gumbel_r -- Right Sided Gumbel, Log-Weibull, Fisher-Tippett, Extreme Value Type I gumbel_l -- Left Sided Gumbel, etc. halfcauchy -- Half Cauchy halflogistic -- Half Logistic halfnorm -- Half Normal halfgennorm -- Generalized Half Normal hypsecant -- Hyperbolic Secant invgamma -- Inverse Gamma invgauss -- Inverse Gaussian invweibull -- Inverse Weibull johnsonsb -- Johnson SB johnsonsu -- Johnson SU kappa4 -- Kappa 4 parameter kappa3 -- Kappa 3 parameter ksone -- Kolmogorov-Smirnov one-sided (no stats) kstwobign -- Kolmogorov-Smirnov two-sided test for Large N (no stats) laplace -- Laplace levy -- Levy levy_l levy_stable logistic -- Logistic loggamma -- Log-Gamma loglaplace -- Log-Laplace (Log Double Exponential) lognorm -- Log-Normal loguniform -- Log-Uniform lomax -- Lomax (Pareto of the second kind) maxwell -- Maxwell mielke -- Mielke's Beta-Kappa moyal -- Moyal nakagami -- Nakagami ncx2 -- Non-central chi-squared ncf -- Non-central F nct -- Non-central Student's T norm -- Normal (Gaussian) norminvgauss -- Normal Inverse Gaussian pareto -- Pareto pearson3 -- Pearson type III powerlaw -- Power-function powerlognorm -- Power log normal powernorm -- Power normal rdist -- R-distribution rayleigh -- Rayleigh rice -- Rice recipinvgauss -- Reciprocal Inverse Gaussian semicircular -- Semicircular skewnorm -- Skew normal t -- Student's T trapz -- Trapezoidal triang -- Triangular truncexpon -- Truncated Exponential truncnorm -- Truncated Normal tukeylambda -- Tukey-Lambda uniform -- Uniform vonmises -- Von-Mises (Circular) vonmises_line -- Von-Mises (Line) wald -- Wald weibull_min -- Minimum Weibull (see Frechet) weibull_max -- Maximum Weibull (see Frechet) wrapcauchy -- Wrapped Cauchy Multivariate distributions ========================== .. autosummary:: :toctree: generated/ multivariate_normal -- Multivariate normal distribution matrix_normal -- Matrix normal distribution dirichlet -- Dirichlet wishart -- Wishart invwishart -- Inverse Wishart multinomial -- Multinomial distribution special_ortho_group -- SO(N) group ortho_group -- O(N) group unitary_group -- U(N) group random_correlation -- random correlation matrices Discrete distributions ====================== .. autosummary:: :toctree: generated/ bernoulli -- Bernoulli betabinom -- Beta-Binomial binom -- Binomial boltzmann -- Boltzmann (Truncated Discrete Exponential) dlaplace -- Discrete Laplacian geom -- Geometric hypergeom -- Hypergeometric logser -- Logarithmic (Log-Series, Series) nbinom -- Negative Binomial planck -- Planck (Discrete Exponential) poisson -- Poisson randint -- Discrete Uniform skellam -- Skellam zipf -- Zipf yulesimon -- Yule-Simon An overview of statistical functions is given below. Several of these functions have a similar version in `scipy.stats.mstats` which work for masked arrays. Summary statistics ================== .. autosummary:: :toctree: generated/ describe -- Descriptive statistics gmean -- Geometric mean hmean -- Harmonic mean kurtosis -- Fisher or Pearson kurtosis mode -- Modal value moment -- Central moment skew -- Skewness kstat -- kstatvar -- tmean -- Truncated arithmetic mean tvar -- Truncated variance tmin -- tmax -- tstd -- tsem -- variation -- Coefficient of variation find_repeats trim_mean gstd -- Geometric Standard Deviation iqr sem bayes_mvs mvsdist entropy median_absolute_deviation Frequency statistics ==================== .. autosummary:: :toctree: generated/ cumfreq itemfreq percentileofscore scoreatpercentile relfreq .. autosummary:: :toctree: generated/ binned_statistic -- Compute a binned statistic for a set of data. binned_statistic_2d -- Compute a 2-D binned statistic for a set of data. binned_statistic_dd -- Compute a d-D binned statistic for a set of data. Correlation functions ===================== .. autosummary:: :toctree: generated/ f_oneway pearsonr spearmanr pointbiserialr kendalltau weightedtau linregress siegelslopes theilslopes multiscale_graphcorr Statistical tests ================= .. autosummary:: :toctree: generated/ ttest_1samp ttest_ind ttest_ind_from_stats ttest_rel kstest chisquare power_divergence ks_2samp epps_singleton_2samp mannwhitneyu tiecorrect rankdata ranksums wilcoxon kruskal friedmanchisquare brunnermunzel combine_pvalues jarque_bera .. autosummary:: :toctree: generated/ ansari bartlett levene shapiro anderson anderson_ksamp binom_test fligner median_test mood skewtest kurtosistest normaltest Transformations =============== .. autosummary:: :toctree: generated/ boxcox boxcox_normmax boxcox_llf yeojohnson yeojohnson_normmax yeojohnson_llf obrientransform sigmaclip trimboth trim1 zmap zscore Statistical distances ===================== .. autosummary:: :toctree: generated/ wasserstein_distance energy_distance Random variate generation ========================= .. autosummary:: :toctree: generated/ rvs_ratio_uniforms Circular statistical functions ============================== .. autosummary:: :toctree: generated/ circmean circvar circstd Contingency table functions =========================== .. autosummary:: :toctree: generated/ chi2_contingency contingency.expected_freq contingency.margins fisher_exact Plot-tests ========== .. autosummary:: :toctree: generated/ ppcc_max ppcc_plot probplot boxcox_normplot yeojohnson_normplot Masked statistics functions =========================== .. toctree:: stats.mstats Univariate and multivariate kernel density estimation ===================================================== .. autosummary:: :toctree: generated/ gaussian_kde Warnings used in :mod:`scipy.stats` =================================== .. autosummary:: :toctree: generated/ PearsonRConstantInputWarning PearsonRNearConstantInputWarning SpearmanRConstantInputWarning For many more stat related functions install the software R and the interface package rpy. """ from __future__ import division, print_function, absolute_import from .stats import * from .distributions import * from .morestats import * from ._binned_statistic import * from .kde import gaussian_kde from . import mstats from .contingency import chi2_contingency from ._multivariate import * __all__ = [s for s in dir() if not s.startswith("_")] # Remove dunders. from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
arokem/scipy
scipy/stats/__init__.py
Python
bsd-3-clause
10,098
[ "Gaussian" ]
2cb61c75a87bfa15e50f6958252642c31f49fa538a82d08441e97938658facae
""" Test class for Stalled Job Agent """ # imports from __future__ import absolute_import from __future__ import division from __future__ import print_function from mock import MagicMock # DIRAC Components from DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent import StalledJobAgent from DIRAC import gLogger # Mock Objects mockAM = MagicMock() mockNone = MagicMock() mockNone.return_value = None gLogger.setLevel('DEBUG') def test__failSubmittingJobs(mocker): """ Testing StalledJobAgent()._failSubmittingJobs() """ mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule.__init__") mocker.patch( "DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule._AgentModule__moduleProperties", side_effect=lambda x, y=None: y, create=True ) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobDB.__init__", side_effect=mockNone) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobLoggingDB.__init__", side_effect=mockNone) stalledJobAgent = StalledJobAgent() stalledJobAgent._AgentModule__configDefaults = mockAM stalledJobAgent.log = gLogger stalledJobAgent.initialize() stalledJobAgent.jobDB.log = gLogger stalledJobAgent.log.setLevel('DEBUG') result = stalledJobAgent._failSubmittingJobs() assert not result['OK'] def test__kickStuckJobs(mocker): """ Testing StalledJobAgent()._kickStuckJobs() """ mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule.__init__") mocker.patch( "DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule._AgentModule__moduleProperties", side_effect=lambda x, y=None: y, create=True ) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobDB.__init__", side_effect=mockNone) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobLoggingDB.__init__", side_effect=mockNone) stalledJobAgent = StalledJobAgent() stalledJobAgent._AgentModule__configDefaults = mockAM stalledJobAgent.log = gLogger stalledJobAgent.initialize() stalledJobAgent.jobDB.log = gLogger stalledJobAgent.log.setLevel('DEBUG') result = stalledJobAgent._kickStuckJobs() assert not result['OK'] def test__failStalledJobs(mocker): """ Testing StalledJobAgent()._failStalledJobs() """ mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule.__init__") mocker.patch( "DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule._AgentModule__moduleProperties", side_effect=lambda x, y=None: y, create=True ) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobDB.__init__", side_effect=mockNone) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobLoggingDB.__init__", side_effect=mockNone) stalledJobAgent = StalledJobAgent() stalledJobAgent._AgentModule__configDefaults = mockAM stalledJobAgent.log = gLogger stalledJobAgent.initialize() stalledJobAgent.jobDB.log = gLogger stalledJobAgent.log.setLevel('DEBUG') result = stalledJobAgent._failStalledJobs(0) assert not result['OK'] def test__markStalledJobs(mocker): """ Testing StalledJobAgent()._markStalledJobs() """ mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule.__init__") mocker.patch( "DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.AgentModule._AgentModule__moduleProperties", side_effect=lambda x, y=None: y, create=True ) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobDB.__init__", side_effect=mockNone) mocker.patch("DIRAC.WorkloadManagementSystem.Agent.StalledJobAgent.JobLoggingDB.__init__", side_effect=mockNone) stalledJobAgent = StalledJobAgent() stalledJobAgent._AgentModule__configDefaults = mockAM stalledJobAgent.log = gLogger stalledJobAgent.initialize() stalledJobAgent.jobDB.log = gLogger stalledJobAgent.log.setLevel('DEBUG') stalledJobAgent.stalledTime = 120 result = stalledJobAgent._markStalledJobs(0) assert not result['OK']
yujikato/DIRAC
src/DIRAC/WorkloadManagementSystem/Agent/test/Test_Agent_StalledJobAgent.py
Python
gpl-3.0
4,056
[ "DIRAC" ]
a85df69525c16d46a3a4f826ec7c8505888a0c913c3188c87579bdd119cc83b5
# !usr/bin/env python2 # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2017-05-07 16:40:21 # @Last modified by: Brian Cherinka # @Last Modified time: 2017-09-28 17:17:58 from __future__ import print_function, division, absolute_import from marvin.tests.api.conftest import ApiPage from marvin.tools.query import Query from marvin.utils.datamodel.query.base import bestparams import pytest import yaml import os # @pytest.fixture() # def page(client, request, init_api): # blue, endpoint = request.param # page = ApiPage(client, 'api', endpoint) # yield page query_data = yaml.load(open(os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/query_test_data.dat')))) @pytest.fixture() def params(release): return {'release': release} @pytest.fixture() def data(release): return query_data[release] def get_query_params(release, paramdisplay): q = Query(mode='local', release=release) if paramdisplay == 'best': qparams = bestparams else: qparams = q.get_available_params('all') return qparams @pytest.mark.parametrize('page', [('api', 'QueryView:index')], ids=['query'], indirect=True) class TestQueryView(object): def test_get_query_success(self, page, params): page.load_page('get', page.url, params=params) data = 'this is a query' page.assert_success(data) @pytest.mark.parametrize('page', [('api', 'querycubes')], ids=['querycubes'], indirect=True) class TestQueryCubes(object): @pytest.mark.parametrize('reqtype', [('get'), ('post')]) @pytest.mark.parametrize('searchfilter', [('nsa.z < 0.1')]) def test_query_success(self, page, params, reqtype, searchfilter, data): params.update({'searchfilter': searchfilter}) expdata = data['queries'][searchfilter]['top5'] page.load_page(reqtype, page.url, params=params) page.assert_success(expdata, issubset=True) @pytest.mark.parametrize('reqtype', [('get'), ('post')]) @pytest.mark.parametrize('name, missing, errmsg', [(None, 'release', 'Missing data for required field.'), (None, 'searchfilter', 'Missing data for required field.')], ids=['norelease', 'nosearchfilter']) def test_query_failure(self, page, reqtype, params, name, missing, errmsg): page.route_no_valid_params(page.url, missing, reqtype=reqtype, errmsg=errmsg) @pytest.mark.parametrize('page', [('api', 'getparams')], ids=['getparams'], indirect=True) class TestQueryGetParams(object): @pytest.mark.parametrize('reqtype', [('get'), ('post')]) @pytest.mark.parametrize('paramdisplay', [('all'), ('best')]) def test_getparams_success(self, release, page, params, reqtype, paramdisplay): params.update({'paramdisplay': paramdisplay}) expdata = get_query_params(release, paramdisplay) page.load_page(reqtype, page.url, params=params) page.assert_success(expdata, keys=True) @pytest.mark.parametrize('reqtype', [('get'), ('post')]) @pytest.mark.parametrize('name, missing, errmsg', [(None, 'release', 'Missing data for required field.'), (None, 'paramdisplay', 'Missing data for required field.')], ids=['norelease', 'noparamdisplay']) def test_plateifu_failure(self, page, reqtype, params, name, missing, errmsg): page.route_no_valid_params(page.url, missing, reqtype=reqtype, errmsg=errmsg)
albireox/marvin
python/marvin/tests/api/test_query.py
Python
bsd-3-clause
3,570
[ "Brian" ]
6b297075b490f88be7a5e2e73d9c2b185b1460926569303ad8936a4ac245b5ab
#!/usr/bin/python from ase import Atoms from ase.visualize import view from ase.calculators.emt import EMT from ase.constraints import FixAtoms from ase.io import write from ase.io import read import sys nargs = len(sys.argv) argv = sys.argv[1] print 'argv: ',argv fname = 'structure'+argv slab = read(fname) slab.set_calculator(EMT()) energy = slab.get_potential_energy() grads = slab.get_forces() #print grads f = open('GRAD'+argv, 'w') f.write(str(energy)) f.write('\n') f.write(str(grads)) f.write('\n') f.close()
ZimmermanGroup/molecularGSM
GSM/grad.py
Python
mit
522
[ "ASE" ]
8b7a0023f84609961255759284d00fb94e1ef53ed83b8bedad963e387e1ec067
#!/usr/bin/env python # encoding: utf-8 from ast import literal_eval import codecs import io from nose.tools import * from nose import SkipTest import networkx as nx from networkx.readwrite.gml import literal_stringizer, literal_destringizer import os import tempfile try: unicode except NameError: unicode = str try: unichr except NameError: unichr = chr class TestGraph(object): def setUp(self): self.simple_data = """Creator "me" Version "xx" graph [ comment "This is a sample graph" directed 1 IsPlanar 1 pos [ x 0 y 1 ] node [ id 1 label "Node 1" pos [ x 1 y 1 ] ] node [ id 2 pos [ x 1 y 2 ] label "Node 2" ] node [ id 3 label "Node 3" pos [ x 1 y 3 ] ] edge [ source 1 target 2 label "Edge from node 1 to node 2" color [line "blue" thickness 3] ] edge [ source 2 target 3 label "Edge from node 2 to node 3" ] edge [ source 3 target 1 label "Edge from node 3 to node 1" ] ] """ def test_parse_gml_cytoscape_bug(self): # example from issue #321, originally #324 in trac cytoscape_example = """ Creator "Cytoscape" Version 1.0 graph [ node [ root_index -3 id -3 graphics [ x -96.0 y -67.0 w 40.0 h 40.0 fill "#ff9999" type "ellipse" outline "#666666" outline_width 1.5 ] label "node2" ] node [ root_index -2 id -2 graphics [ x 63.0 y 37.0 w 40.0 h 40.0 fill "#ff9999" type "ellipse" outline "#666666" outline_width 1.5 ] label "node1" ] node [ root_index -1 id -1 graphics [ x -31.0 y -17.0 w 40.0 h 40.0 fill "#ff9999" type "ellipse" outline "#666666" outline_width 1.5 ] label "node0" ] edge [ root_index -2 target -2 source -1 graphics [ width 1.5 fill "#0000ff" type "line" Line [ ] source_arrow 0 target_arrow 3 ] label "DirectedEdge" ] edge [ root_index -1 target -1 source -3 graphics [ width 1.5 fill "#0000ff" type "line" Line [ ] source_arrow 0 target_arrow 3 ] label "DirectedEdge" ] ] """ nx.parse_gml(cytoscape_example) def test_parse_gml(self): G = nx.parse_gml(self.simple_data, label='label') assert_equals(sorted(G.nodes()), ['Node 1', 'Node 2', 'Node 3']) assert_equals([e for e in sorted(G.edges())], [('Node 1', 'Node 2'), ('Node 2', 'Node 3'), ('Node 3', 'Node 1')]) assert_equals([e for e in sorted(G.edges(data=True))], [('Node 1', 'Node 2', {'color': {'line': 'blue', 'thickness': 3}, 'label': 'Edge from node 1 to node 2'}), ('Node 2', 'Node 3', {'label': 'Edge from node 2 to node 3'}), ('Node 3', 'Node 1', {'label': 'Edge from node 3 to node 1'})]) def test_read_gml(self): (fd, fname) = tempfile.mkstemp() fh = open(fname, 'w') fh.write(self.simple_data) fh.close() Gin = nx.read_gml(fname, label='label') G = nx.parse_gml(self.simple_data, label='label') assert_equals(sorted(G.nodes(data=True)), sorted(Gin.nodes(data=True))) assert_equals(sorted(G.edges(data=True)), sorted(Gin.edges(data=True))) os.close(fd) os.unlink(fname) def test_labels_are_strings(self): # GML requires labels to be strings (i.e., in quotes) answer = """graph [ node [ id 0 label "1203" ] ]""" G = nx.Graph() G.add_node(1203) data = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer)) assert_equal(data, answer) def test_relabel_duplicate(self): data = """ graph [ label "" directed 1 node [ id 0 label "same" ] node [ id 1 label "same" ] ] """ fh = io.BytesIO(data.encode('UTF-8')) fh.seek(0) assert_raises( nx.NetworkXError, nx.read_gml, fh, label='label') def test_tuplelabels(self): # https://github.com/networkx/networkx/pull/1048 # Writing tuple labels to GML failed. G = nx.OrderedGraph() G.add_edge((0, 1), (1, 0)) data = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer)) answer = """graph [ node [ id 0 label "(0,1)" ] node [ id 1 label "(1,0)" ] edge [ source 0 target 1 ] ]""" assert_equal(data, answer) def test_quotes(self): # https://github.com/networkx/networkx/issues/1061 # Encoding quotes as HTML entities. G = nx.path_graph(1) G.name = "path_graph(1)" attr = 'This is "quoted" and this is a copyright: ' + unichr(169) G.nodes[0]['demo'] = attr fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ name "path_graph(1)" node [ id 0 label "0" demo "This is &#34;quoted&#34; and this is a copyright: &#169;" ] ]""" assert_equal(data, answer) def test_unicode_node(self): node = 'node' + unichr(169) G = nx.Graph() G.add_node(node) fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ node [ id 0 label "node&#169;" ] ]""" assert_equal(data, answer) def test_float_label(self): node = 1.0 G = nx.Graph() G.add_node(node) fobj = tempfile.NamedTemporaryFile() nx.write_gml(G, fobj) fobj.seek(0) # Should be bytes in 2.x and 3.x data = fobj.read().strip().decode('ascii') answer = """graph [ node [ id 0 label "1.0" ] ]""" assert_equal(data, answer) def test_name(self): G = nx.parse_gml('graph [ name "x" node [ id 0 label "x" ] ]') assert_equal('x', G.graph['name']) G = nx.parse_gml('graph [ node [ id 0 label "x" ] ]') assert_equal('', G.name) assert_not_in('name', G.graph) def test_graph_types(self): for directed in [None, False, True]: for multigraph in [None, False, True]: gml = 'graph [' if directed is not None: gml += ' directed ' + str(int(directed)) if multigraph is not None: gml += ' multigraph ' + str(int(multigraph)) gml += ' node [ id 0 label "0" ]' gml += ' edge [ source 0 target 0 ]' gml += ' ]' G = nx.parse_gml(gml) assert_equal(bool(directed), G.is_directed()) assert_equal(bool(multigraph), G.is_multigraph()) gml = 'graph [\n' if directed is True: gml += ' directed 1\n' if multigraph is True: gml += ' multigraph 1\n' gml += """ node [ id 0 label "0" ] edge [ source 0 target 0 """ if multigraph: gml += ' key 0\n' gml += ' ]\n]' assert_equal(gml, '\n'.join(nx.generate_gml(G))) def test_data_types(self): data = [True, False, 10 ** 20, -2e33, "'", '"&&amp;&&#34;"', [{(b'\xfd',): '\x7f', unichr(0x4444): (1, 2)}, (2, "3")]] try: data.append(unichr(0x14444)) # fails under IronPython except ValueError: data.append(unichr(0x1444)) try: data.append(literal_eval('{2.3j, 1 - 2.3j, ()}')) # fails under Python 2.7 except ValueError: data.append([2.3j, 1 - 2.3j, ()]) G = nx.Graph() G.name = data G.graph['data'] = data G.add_node(0, int=-1, data=dict(data=data)) G.add_edge(0, 0, float=-2.5, data=data) gml = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer)) G = nx.parse_gml(gml, destringizer=literal_destringizer) assert_equal(data, G.name) assert_equal({'name': data, unicode('data'): data}, G.graph) assert_equal(list(G.nodes(data=True)), [(0, dict(int=-1, data=dict(data=data)))]) assert_equal(list(G.edges(data=True)), [(0, 0, dict(float=-2.5, data=data))]) G = nx.Graph() G.graph['data'] = 'frozenset([1, 2, 3])' G = nx.parse_gml(nx.generate_gml(G), destringizer=literal_eval) assert_equal(G.graph['data'], 'frozenset([1, 2, 3])') def test_escape_unescape(self): gml = """graph [ name "&amp;&#34;&#xf;&#x4444;&#1234567890;&#x1234567890abcdef;&unknown;" ]""" G = nx.parse_gml(gml) assert_equal( '&"\x0f' + unichr(0x4444) + '&#1234567890;&#x1234567890abcdef;&unknown;', G.name) gml = '\n'.join(nx.generate_gml(G)) assert_equal("""graph [ name "&#38;&#34;&#15;&#17476;&#38;#1234567890;&#38;#x1234567890abcdef;&#38;unknown;" ]""", gml) def test_exceptions(self): assert_raises(ValueError, literal_destringizer, '(') assert_raises(ValueError, literal_destringizer, 'frozenset([1, 2, 3])') assert_raises(ValueError, literal_destringizer, literal_destringizer) assert_raises(ValueError, literal_stringizer, frozenset([1, 2, 3])) assert_raises(ValueError, literal_stringizer, literal_stringizer) with tempfile.TemporaryFile() as f: f.write(codecs.BOM_UTF8 + 'graph[]'.encode('ascii')) f.seek(0) assert_raises(nx.NetworkXError, nx.read_gml, f) def assert_parse_error(gml): assert_raises(nx.NetworkXError, nx.parse_gml, gml) assert_parse_error(['graph [\n\n', unicode(']')]) assert_parse_error('') assert_parse_error('Creator ""') assert_parse_error('0') assert_parse_error('graph ]') assert_parse_error('graph [ 1 ]') assert_parse_error('graph [ 1.E+2 ]') assert_parse_error('graph [ "A" ]') assert_parse_error('graph [ ] graph ]') assert_parse_error('graph [ ] graph [ ]') assert_parse_error('graph [ data [1, 2, 3] ]') assert_parse_error('graph [ node [ ] ]') assert_parse_error('graph [ node [ id 0 ] ]') nx.parse_gml('graph [ node [ id "a" ] ]', label='id') assert_parse_error( 'graph [ node [ id 0 label 0 ] node [ id 0 label 1 ] ]') assert_parse_error( 'graph [ node [ id 0 label 0 ] node [ id 1 label 0 ] ]') assert_parse_error('graph [ node [ id 0 label 0 ] edge [ ] ]') assert_parse_error('graph [ node [ id 0 label 0 ] edge [ source 0 ] ]') nx.parse_gml( 'graph [edge [ source 0 target 0 ] node [ id 0 label 0 ] ]') assert_parse_error( 'graph [ node [ id 0 label 0 ] edge [ source 1 target 0 ] ]') assert_parse_error( 'graph [ node [ id 0 label 0 ] edge [ source 0 target 1 ] ]') assert_parse_error( 'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] ' 'edge [ source 0 target 1 ] edge [ source 1 target 0 ] ]') nx.parse_gml( 'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] ' 'edge [ source 0 target 1 ] edge [ source 1 target 0 ] ' 'directed 1 ]') nx.parse_gml( 'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] ' 'edge [ source 0 target 1 ] edge [ source 0 target 1 ]' 'multigraph 1 ]') nx.parse_gml( 'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] ' 'edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 ]' 'multigraph 1 ]') assert_parse_error( 'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] ' 'edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 0 ]' 'multigraph 1 ]') nx.parse_gml( 'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] ' 'edge [ source 0 target 1 key 0 ] edge [ source 1 target 0 key 0 ]' 'directed 1 multigraph 1 ]') def assert_generate_error(*args, **kwargs): assert_raises(nx.NetworkXError, lambda: list(nx.generate_gml(*args, **kwargs))) G = nx.Graph() G.graph[3] = 3 assert_generate_error(G) G = nx.Graph() G.graph['3'] = 3 assert_generate_error(G) G = nx.Graph() G.graph['data'] = frozenset([1, 2, 3]) assert_generate_error(G, stringizer=literal_stringizer) G = nx.Graph() G.graph['data'] = [] assert_generate_error(G) assert_generate_error(G, stringizer=len)
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/networkx/readwrite/tests/test_gml.py
Python
gpl-3.0
13,834
[ "Cytoscape" ]
bda17853b85365df7a7c3b6dabbab17ba78613487b64d13387e3bbb161f2ce98
input_name = '../examples/biot/biot.py' output_name = 'test_biot.vtk' from testsBasic import TestInput class Test( TestInput ): pass
olivierverdier/sfepy
tests/test_input_biot.py
Python
bsd-3-clause
139
[ "VTK" ]
aab6b2f66ba535f6f756432a1e2b454e39ec2a649e96a59b79f0facd25e10ed8
# Natural Language Toolkit: Feature Structures # # Copyright (C) 2001-2013 NLTK Project # Author: Edward Loper <edloper@gradient.cis.upenn.edu>, # Rob Speer, # Steven Bird <stevenbird1@gmail.com> # URL: <http://nltk.sourceforge.net> # For license information, see LICENSE.TXT """ Basic data classes for representing feature structures, and for performing basic operations on those feature structures. A feature structure is a mapping from feature identifiers to feature values, where each feature value is either a basic value (such as a string or an integer), or a nested feature structure. There are two types of feature structure, implemented by two subclasses of ``FeatStruct``: - feature dictionaries, implemented by ``FeatDict``, act like Python dictionaries. Feature identifiers may be strings or instances of the ``Feature`` class. - feature lists, implemented by ``FeatList``, act like Python lists. Feature identifiers are integers. Feature structures are typically used to represent partial information about objects. A feature identifier that is not mapped to a value stands for a feature whose value is unknown (*not* a feature without a value). Two feature structures that represent (potentially overlapping) information about the same object can be combined by unification. When two inconsistent feature structures are unified, the unification fails and returns None. Features can be specified using "feature paths", or tuples of feature identifiers that specify path through the nested feature structures to a value. Feature structures may contain reentrant feature values. A "reentrant feature value" is a single feature value that can be accessed via multiple feature paths. Unification preserves the reentrance relations imposed by both of the unified feature structures. In the feature structure resulting from unification, any modifications to a reentrant feature value will be visible using any of its feature paths. Feature structure variables are encoded using the ``nltk.sem.Variable`` class. The variables' values are tracked using a bindings dictionary, which maps variables to their values. When two feature structures are unified, a fresh bindings dictionary is created to track their values; and before unification completes, all bound variables are replaced by their values. Thus, the bindings dictionaries are usually strictly internal to the unification process. However, it is possible to track the bindings of variables if you choose to, by supplying your own initial bindings dictionary to the ``unify()`` function. When unbound variables are unified with one another, they become aliased. This is encoded by binding one variable to the other. Lightweight Feature Structures ============================== Many of the functions defined by ``nltk.featstruct`` can be applied directly to simple Python dictionaries and lists, rather than to full-fledged ``FeatDict`` and ``FeatList`` objects. In other words, Python ``dicts`` and ``lists`` can be used as "light-weight" feature structures. >>> from nltk.featstruct import unify >>> unify(dict(x=1, y=dict()), dict(a='a', y=dict(b='b'))) # doctest: +SKIP {'y': {'b': 'b'}, 'x': 1, 'a': 'a'} However, you should keep in mind the following caveats: - Python dictionaries & lists ignore reentrance when checking for equality between values. But two FeatStructs with different reentrances are considered nonequal, even if all their base values are equal. - FeatStructs can be easily frozen, allowing them to be used as keys in hash tables. Python dictionaries and lists can not. - FeatStructs display reentrance in their string representations; Python dictionaries and lists do not. - FeatStructs may *not* be mixed with Python dictionaries and lists (e.g., when performing unification). - FeatStructs provide a number of useful methods, such as ``walk()`` and ``cyclic()``, which are not available for Python dicts and lists. In general, if your feature structures will contain any reentrances, or if you plan to use them as dictionary keys, it is strongly recommended that you use full-fledged ``FeatStruct`` objects. """ from __future__ import print_function, unicode_literals, division import re import copy from nltk.internals import parse_str, raise_unorderable_types from nltk.sem.logic import (Variable, Expression, SubstituteBindingsI, LogicParser, ParseException) from nltk.compat import (string_types, integer_types, total_ordering, python_2_unicode_compatible, unicode_repr) ###################################################################### # Feature Structure ###################################################################### @total_ordering class FeatStruct(SubstituteBindingsI): """ A mapping from feature identifiers to feature values, where each feature value is either a basic value (such as a string or an integer), or a nested feature structure. There are two types of feature structure: - feature dictionaries, implemented by ``FeatDict``, act like Python dictionaries. Feature identifiers may be strings or instances of the ``Feature`` class. - feature lists, implemented by ``FeatList``, act like Python lists. Feature identifiers are integers. Feature structures may be indexed using either simple feature identifiers or 'feature paths.' A feature path is a sequence of feature identifiers that stand for a corresponding sequence of indexing operations. In particular, ``fstruct[(f1,f2,...,fn)]`` is equivalent to ``fstruct[f1][f2]...[fn]``. Feature structures may contain reentrant feature structures. A "reentrant feature structure" is a single feature structure object that can be accessed via multiple feature paths. Feature structures may also be cyclic. A feature structure is "cyclic" if there is any feature path from the feature structure to itself. Two feature structures are considered equal if they assign the same values to all features, and have the same reentrancies. By default, feature structures are mutable. They may be made immutable with the ``freeze()`` method. Once they have been frozen, they may be hashed, and thus used as dictionary keys. """ _frozen = False """:ivar: A flag indicating whether this feature structure is frozen or not. Once this flag is set, it should never be un-set; and no further modification should be made to this feature structue.""" ##//////////////////////////////////////////////////////////// #{ Constructor ##//////////////////////////////////////////////////////////// def __new__(cls, features=None, **morefeatures): """ Construct and return a new feature structure. If this constructor is called directly, then the returned feature structure will be an instance of either the ``FeatDict`` class or the ``FeatList`` class. :param features: The initial feature values for this feature structure: - FeatStruct(string) -> FeatStructParser().parse(string) - FeatStruct(mapping) -> FeatDict(mapping) - FeatStruct(sequence) -> FeatList(sequence) - FeatStruct() -> FeatDict() :param morefeatures: If ``features`` is a mapping or None, then ``morefeatures`` provides additional features for the ``FeatDict`` constructor. """ # If the FeatStruct constructor is called directly, then decide # whether to create a FeatDict or a FeatList, based on the # contents of the `features` argument. if cls is FeatStruct: if features is None: return FeatDict.__new__(FeatDict, **morefeatures) elif _is_mapping(features): return FeatDict.__new__(FeatDict, features, **morefeatures) elif morefeatures: raise TypeError('Keyword arguments may only be specified ' 'if features is None or is a mapping.') if isinstance(features, string_types): if FeatStructParser._START_FDICT_RE.match(features): return FeatDict.__new__(FeatDict, features, **morefeatures) else: return FeatList.__new__(FeatList, features, **morefeatures) elif _is_sequence(features): return FeatList.__new__(FeatList, features) else: raise TypeError('Expected string or mapping or sequence') # Otherwise, construct the object as normal. else: return super(FeatStruct, cls).__new__(cls, features, **morefeatures) ##//////////////////////////////////////////////////////////// #{ Uniform Accessor Methods ##//////////////////////////////////////////////////////////// # These helper functions allow the methods defined by FeatStruct # to treat all feature structures as mappings, even if they're # really lists. (Lists are treated as mappings from ints to vals) def _keys(self): """Return an iterable of the feature identifiers used by this FeatStruct.""" raise NotImplementedError() # Implemented by subclasses. def _values(self): """Return an iterable of the feature values directly defined by this FeatStruct.""" raise NotImplementedError() # Implemented by subclasses. def _items(self): """Return an iterable of (fid,fval) pairs, where fid is a feature identifier and fval is the corresponding feature value, for all features defined by this FeatStruct.""" raise NotImplementedError() # Implemented by subclasses. ##//////////////////////////////////////////////////////////// #{ Equality & Hashing ##//////////////////////////////////////////////////////////// def equal_values(self, other, check_reentrance=False): """ Return True if ``self`` and ``other`` assign the same value to to every feature. In particular, return true if ``self[p]==other[p]`` for every feature path *p* such that ``self[p]`` or ``other[p]`` is a base value (i.e., not a nested feature structure). :param check_reentrance: If True, then also return False if there is any difference between the reentrances of ``self`` and ``other``. :note: the ``==`` is equivalent to ``equal_values()`` with ``check_reentrance=True``. """ return self._equal(other, check_reentrance, set(), set(), set()) def __eq__(self, other): """ Return true if ``self`` and ``other`` are both feature structures, assign the same values to all features, and contain the same reentrances. I.e., return ``self.equal_values(other, check_reentrance=True)``. :see: ``equal_values()`` """ return self._equal(other, True, set(), set(), set()) def __ne__(self, other): return not self == other def __lt__(self, other): if not isinstance(other, FeatStruct): # raise_unorderable_types("<", self, other) # Sometimes feature values can be pure strings, # so we need to be able to compare with non-featstructs: return self.__class__.__name__ < other.__class__.__name__ else: return len(self) < len(other) def __hash__(self): """ If this feature structure is frozen, return its hash value; otherwise, raise ``TypeError``. """ if not self._frozen: raise TypeError('FeatStructs must be frozen before they ' 'can be hashed.') try: return self._hash except AttributeError: self._hash = self._calculate_hashvalue(set()) return self._hash def _equal(self, other, check_reentrance, visited_self, visited_other, visited_pairs): """ Return True iff self and other have equal values. :param visited_self: A set containing the ids of all ``self`` feature structures we've already visited. :param visited_other: A set containing the ids of all ``other`` feature structures we've already visited. :param visited_pairs: A set containing ``(selfid, otherid)`` pairs for all pairs of feature structures we've already visited. """ # If we're the same object, then we're equal. if self is other: return True # If we have different classes, we're definitely not equal. if self.__class__ != other.__class__: return False # If we define different features, we're definitely not equal. # (Perform len test first because it's faster -- we should # do profiling to see if this actually helps) if len(self) != len(other): return False if set(self._keys()) != set(other._keys()): return False # If we're checking reentrance, then any time we revisit a # structure, make sure that it was paired with the same # feature structure that it is now. Note: if check_reentrance, # then visited_pairs will never contain two pairs whose first # values are equal, or two pairs whose second values are equal. if check_reentrance: if id(self) in visited_self or id(other) in visited_other: return (id(self), id(other)) in visited_pairs # If we're not checking reentrance, then we still need to deal # with cycles. If we encounter the same (self, other) pair a # second time, then we won't learn anything more by examining # their children a second time, so just return true. else: if (id(self), id(other)) in visited_pairs: return True # Keep track of which nodes we've visited. visited_self.add(id(self)) visited_other.add(id(other)) visited_pairs.add( (id(self), id(other)) ) # Now we have to check all values. If any of them don't match, # then return false. for (fname, self_fval) in self._items(): other_fval = other[fname] if isinstance(self_fval, FeatStruct): if not self_fval._equal(other_fval, check_reentrance, visited_self, visited_other, visited_pairs): return False else: if self_fval != other_fval: return False # Everything matched up; return true. return True def _calculate_hashvalue(self, visited): """ Return a hash value for this feature structure. :require: ``self`` must be frozen. :param visited: A set containing the ids of all feature structures we've already visited while hashing. """ if id(self) in visited: return 1 visited.add(id(self)) hashval = 5831 for (fname, fval) in sorted(self._items()): hashval *= 37 hashval += hash(fname) hashval *= 37 if isinstance(fval, FeatStruct): hashval += fval._calculate_hashvalue(visited) else: hashval += hash(fval) # Convert to a 32 bit int. hashval = int(hashval & 0x7fffffff) return hashval ##//////////////////////////////////////////////////////////// #{ Freezing ##//////////////////////////////////////////////////////////// #: Error message used by mutating methods when called on a frozen #: feature structure. _FROZEN_ERROR = "Frozen FeatStructs may not be modified." def freeze(self): """ Make this feature structure, and any feature structures it contains, immutable. Note: this method does not attempt to 'freeze' any feature value that is not a ``FeatStruct``; it is recommended that you use only immutable feature values. """ if self._frozen: return self._freeze(set()) def frozen(self): """ Return True if this feature structure is immutable. Feature structures can be made immutable with the ``freeze()`` method. Immutable feature structures may not be made mutable again, but new mutable copies can be produced with the ``copy()`` method. """ return self._frozen def _freeze(self, visited): """ Make this feature structure, and any feature structure it contains, immutable. :param visited: A set containing the ids of all feature structures we've already visited while freezing. """ if id(self) in visited: return visited.add(id(self)) self._frozen = True for (fname, fval) in sorted(self._items()): if isinstance(fval, FeatStruct): fval._freeze(visited) ##//////////////////////////////////////////////////////////// #{ Copying ##//////////////////////////////////////////////////////////// def copy(self, deep=True): """ Return a new copy of ``self``. The new copy will not be frozen. :param deep: If true, create a deep copy; if false, create a shallow copy. """ if deep: return copy.deepcopy(self) else: return self.__class__(self) # Subclasses should define __deepcopy__ to ensure that the new # copy will not be frozen. def __deepcopy__(self, memo): raise NotImplementedError() # Implemented by subclasses. ##//////////////////////////////////////////////////////////// #{ Structural Information ##//////////////////////////////////////////////////////////// def cyclic(self): """ Return True if this feature structure contains itself. """ return self._find_reentrances({})[id(self)] def walk(self): """ Return an iterator that generates this feature structure, and each feature structure it contains. Each feature structure will be generated exactly once. """ return self._walk(set()) def _walk(self, visited): """ Return an iterator that generates this feature structure, and each feature structure it contains. :param visited: A set containing the ids of all feature structures we've already visited while freezing. """ raise NotImplementedError() # Implemented by subclasses. def _walk(self, visited): if id(self) in visited: return visited.add(id(self)) yield self for fval in self._values(): if isinstance(fval, FeatStruct): for elt in fval._walk(visited): yield elt # Walk through the feature tree. The first time we see a feature # value, map it to False (not reentrant). If we see a feature # value more than once, then map it to True (reentrant). def _find_reentrances(self, reentrances): """ Return a dictionary that maps from the ``id`` of each feature structure contained in ``self`` (including ``self``) to a boolean value, indicating whether it is reentrant or not. """ if id(self) in reentrances: # We've seen it more than once. reentrances[id(self)] = True else: # This is the first time we've seen it. reentrances[id(self)] = False # Recurse to contained feature structures. for fval in self._values(): if isinstance(fval, FeatStruct): fval._find_reentrances(reentrances) return reentrances ##//////////////////////////////////////////////////////////// #{ Variables & Bindings ##//////////////////////////////////////////////////////////// def substitute_bindings(self, bindings): """:see: ``nltk.featstruct.substitute_bindings()``""" return substitute_bindings(self, bindings) def retract_bindings(self, bindings): """:see: ``nltk.featstruct.retract_bindings()``""" return retract_bindings(self, bindings) def variables(self): """:see: ``nltk.featstruct.find_variables()``""" return find_variables(self) def rename_variables(self, vars=None, used_vars=(), new_vars=None): """:see: ``nltk.featstruct.rename_variables()``""" return rename_variables(self, vars, used_vars, new_vars) def remove_variables(self): """ Return the feature structure that is obtained by deleting any feature whose value is a ``Variable``. :rtype: FeatStruct """ return remove_variables(self) ##//////////////////////////////////////////////////////////// #{ Unification ##//////////////////////////////////////////////////////////// def unify(self, other, bindings=None, trace=False, fail=None, rename_vars=True): return unify(self, other, bindings, trace, fail, rename_vars) def subsumes(self, other): """ Return True if ``self`` subsumes ``other``. I.e., return true If unifying ``self`` with ``other`` would result in a feature structure equal to ``other``. """ return subsumes(self, other) ##//////////////////////////////////////////////////////////// #{ String Representations ##//////////////////////////////////////////////////////////// def __repr__(self): """ Display a single-line representation of this feature structure, suitable for embedding in other representations. """ return self._repr(self._find_reentrances({}), {}) def _repr(self, reentrances, reentrance_ids): """ Return a string representation of this feature structure. :param reentrances: A dictionary that maps from the ``id`` of each feature value in self, indicating whether that value is reentrant or not. :param reentrance_ids: A dictionary mapping from each ``id`` of a feature value to a unique identifier. This is modified by ``repr``: the first time a reentrant feature value is displayed, an identifier is added to ``reentrance_ids`` for it. """ raise NotImplementedError() # Mutation: disable if frozen. _FROZEN_ERROR = "Frozen FeatStructs may not be modified." _FROZEN_NOTICE = "\n%sIf self is frozen, raise ValueError." def _check_frozen(method, indent=''): """ Given a method function, return a new method function that first checks if ``self._frozen`` is true; and if so, raises ``ValueError`` with an appropriate message. Otherwise, call the method and return its result. """ def wrapped(self, *args, **kwargs): if self._frozen: raise ValueError(_FROZEN_ERROR) else: return method(self, *args, **kwargs) wrapped.__name__ = method.__name__ wrapped.__doc__ = (method.__doc__ or '') + (_FROZEN_NOTICE % indent) return wrapped ###################################################################### # Feature Dictionary ###################################################################### @python_2_unicode_compatible class FeatDict(FeatStruct, dict): """ A feature structure that acts like a Python dictionary. I.e., a mapping from feature identifiers to feature values, where a feature identifier can be a string or a ``Feature``; and where a feature value can be either a basic value (such as a string or an integer), or a nested feature structure. A feature identifiers for a ``FeatDict`` is sometimes called a "feature name". Two feature dicts are considered equal if they assign the same values to all features, and have the same reentrances. :see: ``FeatStruct`` for information about feature paths, reentrance, cyclic feature structures, mutability, freezing, and hashing. """ def __init__(self, features=None, **morefeatures): """ Create a new feature dictionary, with the specified features. :param features: The initial value for this feature dictionary. If ``features`` is a ``FeatStruct``, then its features are copied (shallow copy). If ``features`` is a dict, then a feature is created for each item, mapping its key to its value. If ``features`` is a string, then it is parsed using ``FeatStructParser``. If ``features`` is a list of tuples ``(name, val)``, then a feature is created for each tuple. :param morefeatures: Additional features for the new feature dictionary. If a feature is listed under both ``features`` and ``morefeatures``, then the value from ``morefeatures`` will be used. """ if isinstance(features, string_types): FeatStructParser().parse(features, self) self.update(**morefeatures) else: # update() checks the types of features. self.update(features, **morefeatures) #//////////////////////////////////////////////////////////// #{ Dict methods #//////////////////////////////////////////////////////////// _INDEX_ERROR = str("Expected feature name or path. Got %r.") def __getitem__(self, name_or_path): """If the feature with the given name or path exists, return its value; otherwise, raise ``KeyError``.""" if isinstance(name_or_path, (string_types, Feature)): return dict.__getitem__(self, name_or_path) elif isinstance(name_or_path, tuple): try: val = self for fid in name_or_path: if not isinstance(val, FeatStruct): raise KeyError # path contains base value val = val[fid] return val except (KeyError, IndexError): raise KeyError(name_or_path) else: raise TypeError(self._INDEX_ERROR % name_or_path) def get(self, name_or_path, default=None): """If the feature with the given name or path exists, return its value; otherwise, return ``default``.""" try: return self[name_or_path] except KeyError: return default def __contains__(self, name_or_path): """Return true if a feature with the given name or path exists.""" try: self[name_or_path]; return True except KeyError: return False def has_key(self, name_or_path): """Return true if a feature with the given name or path exists.""" return name_or_path in self def __delitem__(self, name_or_path): """If the feature with the given name or path exists, delete its value; otherwise, raise ``KeyError``.""" if self._frozen: raise ValueError(_FROZEN_ERROR) if isinstance(name_or_path, (string_types, Feature)): return dict.__delitem__(self, name_or_path) elif isinstance(name_or_path, tuple): if len(name_or_path) == 0: raise ValueError("The path () can not be set") else: parent = self[name_or_path[:-1]] if not isinstance(parent, FeatStruct): raise KeyError(name_or_path) # path contains base value del parent[name_or_path[-1]] else: raise TypeError(self._INDEX_ERROR % name_or_path) def __setitem__(self, name_or_path, value): """Set the value for the feature with the given name or path to ``value``. If ``name_or_path`` is an invalid path, raise ``KeyError``.""" if self._frozen: raise ValueError(_FROZEN_ERROR) if isinstance(name_or_path, (string_types, Feature)): return dict.__setitem__(self, name_or_path, value) elif isinstance(name_or_path, tuple): if len(name_or_path) == 0: raise ValueError("The path () can not be set") else: parent = self[name_or_path[:-1]] if not isinstance(parent, FeatStruct): raise KeyError(name_or_path) # path contains base value parent[name_or_path[-1]] = value else: raise TypeError(self._INDEX_ERROR % name_or_path) clear = _check_frozen(dict.clear) pop = _check_frozen(dict.pop) popitem = _check_frozen(dict.popitem) setdefault = _check_frozen(dict.setdefault) def update(self, features=None, **morefeatures): if self._frozen: raise ValueError(_FROZEN_ERROR) if features is None: items = () elif hasattr(features, 'items') and callable(features.items): items = features.items() elif hasattr(features, '__iter__'): items = features else: raise ValueError('Expected mapping or list of tuples') for key, val in items: if not isinstance(key, (string_types, Feature)): raise TypeError('Feature names must be strings') self[key] = val for key, val in morefeatures.items(): if not isinstance(key, (string_types, Feature)): raise TypeError('Feature names must be strings') self[key] = val ##//////////////////////////////////////////////////////////// #{ Copying ##//////////////////////////////////////////////////////////// def __deepcopy__(self, memo): memo[id(self)] = selfcopy = self.__class__() for (key, val) in self._items(): selfcopy[copy.deepcopy(key,memo)] = copy.deepcopy(val,memo) return selfcopy ##//////////////////////////////////////////////////////////// #{ Uniform Accessor Methods ##//////////////////////////////////////////////////////////// def _keys(self): return self.keys() def _values(self): return self.values() def _items(self): return self.items() ##//////////////////////////////////////////////////////////// #{ String Representations ##//////////////////////////////////////////////////////////// def __str__(self): """ Display a multi-line representation of this feature dictionary as an FVM (feature value matrix). """ return '\n'.join(self._str(self._find_reentrances({}), {})) def _repr(self, reentrances, reentrance_ids): segments = [] prefix = '' suffix = '' # If this is the first time we've seen a reentrant structure, # then assign it a unique identifier. if reentrances[id(self)]: assert id(self) not in reentrance_ids reentrance_ids[id(self)] = repr(len(reentrance_ids)+1) # sorting note: keys are unique strings, so we'll never fall # through to comparing values. for (fname, fval) in sorted(self.items()): display = getattr(fname, 'display', None) if id(fval) in reentrance_ids: segments.append('%s->(%s)' % (fname, reentrance_ids[id(fval)])) elif (display == 'prefix' and not prefix and isinstance(fval, (Variable, string_types))): prefix = '%s' % fval elif display == 'slash' and not suffix: if isinstance(fval, Variable): suffix = '/%s' % fval.name else: suffix = '/%s' % unicode_repr(fval) elif isinstance(fval, Variable): segments.append('%s=%s' % (fname, fval.name)) elif fval is True: segments.append('+%s' % fname) elif fval is False: segments.append('-%s' % fname) elif isinstance(fval, Expression): segments.append('%s=<%s>' % (fname, fval)) elif not isinstance(fval, FeatStruct): segments.append('%s=%s' % (fname, unicode_repr(fval))) else: fval_repr = fval._repr(reentrances, reentrance_ids) segments.append('%s=%s' % (fname, fval_repr)) # If it's reentrant, then add on an identifier tag. if reentrances[id(self)]: prefix = '(%s)%s' % (reentrance_ids[id(self)], prefix) return '%s[%s]%s' % (prefix, ', '.join(segments), suffix) def _str(self, reentrances, reentrance_ids): """ :return: A list of lines composing a string representation of this feature dictionary. :param reentrances: A dictionary that maps from the ``id`` of each feature value in self, indicating whether that value is reentrant or not. :param reentrance_ids: A dictionary mapping from each ``id`` of a feature value to a unique identifier. This is modified by ``repr``: the first time a reentrant feature value is displayed, an identifier is added to ``reentrance_ids`` for it. """ # If this is the first time we've seen a reentrant structure, # then tack on an id string. if reentrances[id(self)]: assert id(self) not in reentrance_ids reentrance_ids[id(self)] = repr(len(reentrance_ids)+1) # Special case: empty feature dict. if len(self) == 0: if reentrances[id(self)]: return ['(%s) []' % reentrance_ids[id(self)]] else: return ['[]'] # What's the longest feature name? Use this to align names. maxfnamelen = max(len("%s" % k) for k in self.keys()) lines = [] # sorting note: keys are unique strings, so we'll never fall # through to comparing values. for (fname, fval) in sorted(self.items()): fname = ("%s" % fname).ljust(maxfnamelen) if isinstance(fval, Variable): lines.append('%s = %s' % (fname,fval.name)) elif isinstance(fval, Expression): lines.append('%s = <%s>' % (fname, fval)) elif isinstance(fval, FeatList): fval_repr = fval._repr(reentrances, reentrance_ids) lines.append('%s = %s' % (fname, unicode_repr(fval_repr))) elif not isinstance(fval, FeatDict): # It's not a nested feature structure -- just print it. lines.append('%s = %s' % (fname, unicode_repr(fval))) elif id(fval) in reentrance_ids: # It's a feature structure we've seen before -- print # the reentrance id. lines.append('%s -> (%s)' % (fname, reentrance_ids[id(fval)])) else: # It's a new feature structure. Separate it from # other values by a blank line. if lines and lines[-1] != '': lines.append('') # Recursively print the feature's value (fval). fval_lines = fval._str(reentrances, reentrance_ids) # Indent each line to make room for fname. fval_lines = [(' '*(maxfnamelen+3))+l for l in fval_lines] # Pick which line we'll display fname on, & splice it in. nameline = (len(fval_lines)-1) // 2 fval_lines[nameline] = ( fname+' ='+fval_lines[nameline][maxfnamelen+2:]) # Add the feature structure to the output. lines += fval_lines # Separate FeatStructs by a blank line. lines.append('') # Get rid of any excess blank lines. if lines[-1] == '': lines.pop() # Add brackets around everything. maxlen = max(len(line) for line in lines) lines = ['[ %s%s ]' % (line, ' '*(maxlen-len(line))) for line in lines] # If it's reentrant, then add on an identifier tag. if reentrances[id(self)]: idstr = '(%s) ' % reentrance_ids[id(self)] lines = [(' '*len(idstr))+l for l in lines] idline = (len(lines)-1) // 2 lines[idline] = idstr + lines[idline][len(idstr):] return lines ###################################################################### # Feature List ###################################################################### class FeatList(FeatStruct, list): """ A list of feature values, where each feature value is either a basic value (such as a string or an integer), or a nested feature structure. Feature lists may contain reentrant feature values. A "reentrant feature value" is a single feature value that can be accessed via multiple feature paths. Feature lists may also be cyclic. Two feature lists are considered equal if they assign the same values to all features, and have the same reentrances. :see: ``FeatStruct`` for information about feature paths, reentrance, cyclic feature structures, mutability, freezing, and hashing. """ def __init__(self, features=()): """ Create a new feature list, with the specified features. :param features: The initial list of features for this feature list. If ``features`` is a string, then it is paresd using ``FeatStructParser``. Otherwise, it should be a sequence of basic values and nested feature structures. """ if isinstance(features, string_types): FeatStructParser().parse(features, self) else: list.__init__(self, features) #//////////////////////////////////////////////////////////// #{ List methods #//////////////////////////////////////////////////////////// _INDEX_ERROR = "Expected int or feature path. Got %r." def __getitem__(self, name_or_path): if isinstance(name_or_path, integer_types): return list.__getitem__(self, name_or_path) elif isinstance(name_or_path, tuple): try: val = self for fid in name_or_path: if not isinstance(val, FeatStruct): raise KeyError # path contains base value val = val[fid] return val except (KeyError, IndexError): raise KeyError(name_or_path) else: raise TypeError(self._INDEX_ERROR % name_or_path) def __delitem__(self, name_or_path): """If the feature with the given name or path exists, delete its value; otherwise, raise ``KeyError``.""" if self._frozen: raise ValueError(_FROZEN_ERROR) if isinstance(name_or_path, (integer_types, slice)): return list.__delitem__(self, name_or_path) elif isinstance(name_or_path, tuple): if len(name_or_path) == 0: raise ValueError("The path () can not be set") else: parent = self[name_or_path[:-1]] if not isinstance(parent, FeatStruct): raise KeyError(name_or_path) # path contains base value del parent[name_or_path[-1]] else: raise TypeError(self._INDEX_ERROR % name_or_path) def __setitem__(self, name_or_path, value): """Set the value for the feature with the given name or path to ``value``. If ``name_or_path`` is an invalid path, raise ``KeyError``.""" if self._frozen: raise ValueError(_FROZEN_ERROR) if isinstance(name_or_path, (integer_types, slice)): return list.__setitem__(self, name_or_path, value) elif isinstance(name_or_path, tuple): if len(name_or_path) == 0: raise ValueError("The path () can not be set") else: parent = self[name_or_path[:-1]] if not isinstance(parent, FeatStruct): raise KeyError(name_or_path) # path contains base value parent[name_or_path[-1]] = value else: raise TypeError(self._INDEX_ERROR % name_or_path) # __delslice__ = _check_frozen(list.__delslice__, ' ') # __setslice__ = _check_frozen(list.__setslice__, ' ') __iadd__ = _check_frozen(list.__iadd__) __imul__ = _check_frozen(list.__imul__) append = _check_frozen(list.append) extend = _check_frozen(list.extend) insert = _check_frozen(list.insert) pop = _check_frozen(list.pop) remove = _check_frozen(list.remove) reverse = _check_frozen(list.reverse) sort = _check_frozen(list.sort) ##//////////////////////////////////////////////////////////// #{ Copying ##//////////////////////////////////////////////////////////// def __deepcopy__(self, memo): memo[id(self)] = selfcopy = self.__class__() selfcopy.extend(copy.deepcopy(fval,memo) for fval in self) return selfcopy ##//////////////////////////////////////////////////////////// #{ Uniform Accessor Methods ##//////////////////////////////////////////////////////////// def _keys(self): return list(range(len(self))) def _values(self): return self def _items(self): return enumerate(self) ##//////////////////////////////////////////////////////////// #{ String Representations ##//////////////////////////////////////////////////////////// # Special handling for: reentrances, variables, expressions. def _repr(self, reentrances, reentrance_ids): # If this is the first time we've seen a reentrant structure, # then assign it a unique identifier. if reentrances[id(self)]: assert id(self) not in reentrance_ids reentrance_ids[id(self)] = repr(len(reentrance_ids)+1) prefix = '(%s)' % reentrance_ids[id(self)] else: prefix = '' segments = [] for fval in self: if id(fval) in reentrance_ids: segments.append('->(%s)' % reentrance_ids[id(fval)]) elif isinstance(fval, Variable): segments.append(fval.name) elif isinstance(fval, Expression): segments.append('%s' % fval) elif isinstance(fval, FeatStruct): segments.append(fval._repr(reentrances, reentrance_ids)) else: segments.append('%s' % unicode_repr(fval)) return '%s[%s]' % (prefix, ', '.join(segments)) ###################################################################### # Variables & Bindings ###################################################################### def substitute_bindings(fstruct, bindings, fs_class='default'): """ Return the feature structure that is obtained by replacing each variable bound by ``bindings`` with its binding. If a variable is aliased to a bound variable, then it will be replaced by that variable's value. If a variable is aliased to an unbound variable, then it will be replaced by that variable. :type bindings: dict(Variable -> any) :param bindings: A dictionary mapping from variables to values. """ if fs_class == 'default': fs_class = _default_fs_class(fstruct) fstruct = copy.deepcopy(fstruct) _substitute_bindings(fstruct, bindings, fs_class, set()) return fstruct def _substitute_bindings(fstruct, bindings, fs_class, visited): # Visit each node only once: if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = fstruct.items() elif _is_sequence(fstruct): items = enumerate(fstruct) else: raise ValueError('Expected mapping or sequence') for (fname, fval) in items: while (isinstance(fval, Variable) and fval in bindings): fval = fstruct[fname] = bindings[fval] if isinstance(fval, fs_class): _substitute_bindings(fval, bindings, fs_class, visited) elif isinstance(fval, SubstituteBindingsI): fstruct[fname] = fval.substitute_bindings(bindings) def retract_bindings(fstruct, bindings, fs_class='default'): """ Return the feature structure that is obtained by replacing each feature structure value that is bound by ``bindings`` with the variable that binds it. A feature structure value must be identical to a bound value (i.e., have equal id) to be replaced. ``bindings`` is modified to point to this new feature structure, rather than the original feature structure. Feature structure values in ``bindings`` may be modified if they are contained in ``fstruct``. """ if fs_class == 'default': fs_class = _default_fs_class(fstruct) (fstruct, new_bindings) = copy.deepcopy((fstruct, bindings)) bindings.update(new_bindings) inv_bindings = dict((id(val),var) for (var,val) in bindings.items()) _retract_bindings(fstruct, inv_bindings, fs_class, set()) return fstruct def _retract_bindings(fstruct, inv_bindings, fs_class, visited): # Visit each node only once: if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = fstruct.items() elif _is_sequence(fstruct): items = enumerate(fstruct) else: raise ValueError('Expected mapping or sequence') for (fname, fval) in items: if isinstance(fval, fs_class): if id(fval) in inv_bindings: fstruct[fname] = inv_bindings[id(fval)] _retract_bindings(fval, inv_bindings, fs_class, visited) def find_variables(fstruct, fs_class='default'): """ :return: The set of variables used by this feature structure. :rtype: set(Variable) """ if fs_class == 'default': fs_class = _default_fs_class(fstruct) return _variables(fstruct, set(), fs_class, set()) def _variables(fstruct, vars, fs_class, visited): # Visit each node only once: if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = fstruct.items() elif _is_sequence(fstruct): items = enumerate(fstruct) else: raise ValueError('Expected mapping or sequence') for (fname, fval) in items: if isinstance(fval, Variable): vars.add(fval) elif isinstance(fval, fs_class): _variables(fval, vars, fs_class, visited) elif isinstance(fval, SubstituteBindingsI): vars.update(fval.variables()) return vars def rename_variables(fstruct, vars=None, used_vars=(), new_vars=None, fs_class='default'): """ Return the feature structure that is obtained by replacing any of this feature structure's variables that are in ``vars`` with new variables. The names for these new variables will be names that are not used by any variable in ``vars``, or in ``used_vars``, or in this feature structure. :type vars: set :param vars: The set of variables that should be renamed. If not specified, ``find_variables(fstruct)`` is used; i.e., all variables will be given new names. :type used_vars: set :param used_vars: A set of variables whose names should not be used by the new variables. :type new_vars: dict(Variable -> Variable) :param new_vars: A dictionary that is used to hold the mapping from old variables to new variables. For each variable *v* in this feature structure: - If ``new_vars`` maps *v* to *v'*, then *v* will be replaced by *v'*. - If ``new_vars`` does not contain *v*, but ``vars`` does contain *v*, then a new entry will be added to ``new_vars``, mapping *v* to the new variable that is used to replace it. To consistently rename the variables in a set of feature structures, simply apply rename_variables to each one, using the same dictionary: >>> from nltk.featstruct import FeatStruct >>> fstruct1 = FeatStruct('[subj=[agr=[gender=?y]], obj=[agr=[gender=?y]]]') >>> fstruct2 = FeatStruct('[subj=[agr=[number=?z,gender=?y]], obj=[agr=[number=?z,gender=?y]]]') >>> new_vars = {} # Maps old vars to alpha-renamed vars >>> fstruct1.rename_variables(new_vars=new_vars) [obj=[agr=[gender=?y2]], subj=[agr=[gender=?y2]]] >>> fstruct2.rename_variables(new_vars=new_vars) [obj=[agr=[gender=?y2, number=?z2]], subj=[agr=[gender=?y2, number=?z2]]] If new_vars is not specified, then an empty dictionary is used. """ if fs_class == 'default': fs_class = _default_fs_class(fstruct) # Default values: if new_vars is None: new_vars = {} if vars is None: vars = find_variables(fstruct, fs_class) else: vars = set(vars) # Add our own variables to used_vars. used_vars = find_variables(fstruct, fs_class).union(used_vars) # Copy ourselves, and rename variables in the copy. return _rename_variables(copy.deepcopy(fstruct), vars, used_vars, new_vars, fs_class, set()) def _rename_variables(fstruct, vars, used_vars, new_vars, fs_class, visited): if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = fstruct.items() elif _is_sequence(fstruct): items = enumerate(fstruct) else: raise ValueError('Expected mapping or sequence') for (fname, fval) in items: if isinstance(fval, Variable): # If it's in new_vars, then rebind it. if fval in new_vars: fstruct[fname] = new_vars[fval] # If it's in vars, pick a new name for it. elif fval in vars: new_vars[fval] = _rename_variable(fval, used_vars) fstruct[fname] = new_vars[fval] used_vars.add(new_vars[fval]) elif isinstance(fval, fs_class): _rename_variables(fval, vars, used_vars, new_vars, fs_class, visited) elif isinstance(fval, SubstituteBindingsI): # Pick new names for any variables in `vars` for var in fval.variables(): if var in vars and var not in new_vars: new_vars[var] = _rename_variable(var, used_vars) used_vars.add(new_vars[var]) # Replace all variables in `new_vars`. fstruct[fname] = fval.substitute_bindings(new_vars) return fstruct def _rename_variable(var, used_vars): name, n = re.sub('\d+$', '', var.name), 2 if not name: name = '?' while Variable('%s%s' % (name, n)) in used_vars: n += 1 return Variable('%s%s' % (name, n)) def remove_variables(fstruct, fs_class='default'): """ :rtype: FeatStruct :return: The feature structure that is obtained by deleting all features whose values are ``Variables``. """ if fs_class == 'default': fs_class = _default_fs_class(fstruct) return _remove_variables(copy.deepcopy(fstruct), fs_class, set()) def _remove_variables(fstruct, fs_class, visited): if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = list(fstruct.items()) elif _is_sequence(fstruct): items = list(enumerate(fstruct)) else: raise ValueError('Expected mapping or sequence') for (fname, fval) in items: if isinstance(fval, Variable): del fstruct[fname] elif isinstance(fval, fs_class): _remove_variables(fval, fs_class, visited) return fstruct ###################################################################### # Unification ###################################################################### @python_2_unicode_compatible class _UnificationFailure(object): def __repr__(self): return 'nltk.featstruct.UnificationFailure' UnificationFailure = _UnificationFailure() """A unique value used to indicate unification failure. It can be returned by ``Feature.unify_base_values()`` or by custom ``fail()`` functions to indicate that unificaiton should fail.""" # The basic unification algorithm: # 1. Make copies of self and other (preserving reentrance) # 2. Destructively unify self and other # 3. Apply forward pointers, to preserve reentrance. # 4. Replace bound variables with their values. def unify(fstruct1, fstruct2, bindings=None, trace=False, fail=None, rename_vars=True, fs_class='default'): """ Unify ``fstruct1`` with ``fstruct2``, and return the resulting feature structure. This unified feature structure is the minimal feature structure that contains all feature value assignments from both ``fstruct1`` and ``fstruct2``, and that preserves all reentrancies. If no such feature structure exists (because ``fstruct1`` and ``fstruct2`` specify incompatible values for some feature), then unification fails, and ``unify`` returns None. Bound variables are replaced by their values. Aliased variables are replaced by their representative variable (if unbound) or the value of their representative variable (if bound). I.e., if variable *v* is in ``bindings``, then *v* is replaced by ``bindings[v]``. This will be repeated until the variable is replaced by an unbound variable or a non-variable value. Unbound variables are bound when they are unified with values; and aliased when they are unified with variables. I.e., if variable *v* is not in ``bindings``, and is unified with a variable or value *x*, then ``bindings[v]`` is set to *x*. If ``bindings`` is unspecified, then all variables are assumed to be unbound. I.e., ``bindings`` defaults to an empty dict. >>> from nltk.featstruct import FeatStruct >>> FeatStruct('[a=?x]').unify(FeatStruct('[b=?x]')) [a=?x, b=?x2] :type bindings: dict(Variable -> any) :param bindings: A set of variable bindings to be used and updated during unification. :type trace: bool :param trace: If true, generate trace output. :type rename_vars: bool :param rename_vars: If True, then rename any variables in ``fstruct2`` that are also used in ``fstruct1``, in order to avoid collisions on variable names. """ # Decide which class(es) will be treated as feature structures, # for the purposes of unification. if fs_class == 'default': fs_class = _default_fs_class(fstruct1) if _default_fs_class(fstruct2) != fs_class: raise ValueError("Mixing FeatStruct objects with Python " "dicts and lists is not supported.") assert isinstance(fstruct1, fs_class) assert isinstance(fstruct2, fs_class) # If bindings are unspecified, use an empty set of bindings. user_bindings = (bindings is not None) if bindings is None: bindings = {} # Make copies of fstruct1 and fstruct2 (since the unification # algorithm is destructive). Do it all at once, to preserve # reentrance links between fstruct1 and fstruct2. Copy bindings # as well, in case there are any bound vars that contain parts # of fstruct1 or fstruct2. (fstruct1copy, fstruct2copy, bindings_copy) = ( copy.deepcopy((fstruct1, fstruct2, bindings))) # Copy the bindings back to the original bindings dict. bindings.update(bindings_copy) if rename_vars: vars1 = find_variables(fstruct1copy, fs_class) vars2 = find_variables(fstruct2copy, fs_class) _rename_variables(fstruct2copy, vars1, vars2, {}, fs_class, set()) # Do the actual unification. If it fails, return None. forward = {} if trace: _trace_unify_start((), fstruct1copy, fstruct2copy) try: result = _destructively_unify(fstruct1copy, fstruct2copy, bindings, forward, trace, fail, fs_class, ()) except _UnificationFailureError: return None # _destructively_unify might return UnificationFailure, e.g. if we # tried to unify a mapping with a sequence. if result is UnificationFailure: if fail is None: return None else: return fail(fstruct1copy, fstruct2copy, ()) # Replace any feature structure that has a forward pointer # with the target of its forward pointer. result = _apply_forwards(result, forward, fs_class, set()) if user_bindings: _apply_forwards_to_bindings(forward, bindings) # Replace bound vars with values. _resolve_aliases(bindings) _substitute_bindings(result, bindings, fs_class, set()) # Return the result. if trace: _trace_unify_succeed((), result) if trace: _trace_bindings((), bindings) return result class _UnificationFailureError(Exception): """An exception that is used by ``_destructively_unify`` to abort unification when a failure is encountered.""" def _destructively_unify(fstruct1, fstruct2, bindings, forward, trace, fail, fs_class, path): """ Attempt to unify ``fstruct1`` and ``fstruct2`` by modifying them in-place. If the unification succeeds, then ``fstruct1`` will contain the unified value, the value of ``fstruct2`` is undefined, and forward[id(fstruct2)] is set to fstruct1. If the unification fails, then a _UnificationFailureError is raised, and the values of ``fstruct1`` and ``fstruct2`` are undefined. :param bindings: A dictionary mapping variables to values. :param forward: A dictionary mapping feature structures ids to replacement structures. When two feature structures are merged, a mapping from one to the other will be added to the forward dictionary; and changes will be made only to the target of the forward dictionary. ``_destructively_unify`` will always 'follow' any links in the forward dictionary for fstruct1 and fstruct2 before actually unifying them. :param trace: If true, generate trace output :param path: The feature path that led us to this unification step. Used for trace output. """ # If fstruct1 is already identical to fstruct2, we're done. # Note: this, together with the forward pointers, ensures # that unification will terminate even for cyclic structures. if fstruct1 is fstruct2: if trace: _trace_unify_identity(path, fstruct1) return fstruct1 # Set fstruct2's forward pointer to point to fstruct1; this makes # fstruct1 the canonical copy for fstruct2. Note that we need to # do this before we recurse into any child structures, in case # they're cyclic. forward[id(fstruct2)] = fstruct1 # Unifying two mappings: if _is_mapping(fstruct1) and _is_mapping(fstruct2): for fname in fstruct1: if getattr(fname, 'default', None) is not None: fstruct2.setdefault(fname, fname.default) for fname in fstruct2: if getattr(fname, 'default', None) is not None: fstruct1.setdefault(fname, fname.default) # Unify any values that are defined in both fstruct1 and # fstruct2. Copy any values that are defined in fstruct2 but # not in fstruct1 to fstruct1. Note: sorting fstruct2's # features isn't actually necessary; but we do it to give # deterministic behavior, e.g. for tracing. for fname, fval2 in sorted(fstruct2.items()): if fname in fstruct1: fstruct1[fname] = _unify_feature_values( fname, fstruct1[fname], fval2, bindings, forward, trace, fail, fs_class, path+(fname,)) else: fstruct1[fname] = fval2 return fstruct1 # Contains the unified value. # Unifying two sequences: elif _is_sequence(fstruct1) and _is_sequence(fstruct2): # If the lengths don't match, fail. if len(fstruct1) != len(fstruct2): return UnificationFailure # Unify corresponding values in fstruct1 and fstruct2. for findex in range(len(fstruct1)): fstruct1[findex] = _unify_feature_values( findex, fstruct1[findex], fstruct2[findex], bindings, forward, trace, fail, fs_class, path+(findex,)) return fstruct1 # Contains the unified value. # Unifying sequence & mapping: fail. The failure function # doesn't get a chance to recover in this case. elif ((_is_sequence(fstruct1) or _is_mapping(fstruct1)) and (_is_sequence(fstruct2) or _is_mapping(fstruct2))): return UnificationFailure # Unifying anything else: not allowed! raise TypeError('Expected mappings or sequences') def _unify_feature_values(fname, fval1, fval2, bindings, forward, trace, fail, fs_class, fpath): """ Attempt to unify ``fval1`` and and ``fval2``, and return the resulting unified value. The method of unification will depend on the types of ``fval1`` and ``fval2``: 1. If they're both feature structures, then destructively unify them (see ``_destructively_unify()``. 2. If they're both unbound variables, then alias one variable to the other (by setting bindings[v2]=v1). 3. If one is an unbound variable, and the other is a value, then bind the unbound variable to the value. 4. If one is a feature structure, and the other is a base value, then fail. 5. If they're both base values, then unify them. By default, this will succeed if they are equal, and fail otherwise. """ if trace: _trace_unify_start(fpath, fval1, fval2) # Look up the "canonical" copy of fval1 and fval2 while id(fval1) in forward: fval1 = forward[id(fval1)] while id(fval2) in forward: fval2 = forward[id(fval2)] # If fval1 or fval2 is a bound variable, then # replace it by the variable's bound value. This # includes aliased variables, which are encoded as # variables bound to other variables. fvar1 = fvar2 = None while isinstance(fval1, Variable) and fval1 in bindings: fvar1 = fval1 fval1 = bindings[fval1] while isinstance(fval2, Variable) and fval2 in bindings: fvar2 = fval2 fval2 = bindings[fval2] # Case 1: Two feature structures (recursive case) if isinstance(fval1, fs_class) and isinstance(fval2, fs_class): result = _destructively_unify(fval1, fval2, bindings, forward, trace, fail, fs_class, fpath) # Case 2: Two unbound variables (create alias) elif (isinstance(fval1, Variable) and isinstance(fval2, Variable)): if fval1 != fval2: bindings[fval2] = fval1 result = fval1 # Case 3: An unbound variable and a value (bind) elif isinstance(fval1, Variable): bindings[fval1] = fval2 result = fval1 elif isinstance(fval2, Variable): bindings[fval2] = fval1 result = fval2 # Case 4: A feature structure & a base value (fail) elif isinstance(fval1, fs_class) or isinstance(fval2, fs_class): result = UnificationFailure # Case 5: Two base values else: # Case 5a: Feature defines a custom unification method for base values if isinstance(fname, Feature): result = fname.unify_base_values(fval1, fval2, bindings) # Case 5b: Feature value defines custom unification method elif isinstance(fval1, CustomFeatureValue): result = fval1.unify(fval2) # Sanity check: unify value should be symmetric if (isinstance(fval2, CustomFeatureValue) and result != fval2.unify(fval1)): raise AssertionError( 'CustomFeatureValue objects %r and %r disagree ' 'about unification value: %r vs. %r' % (fval1, fval2, result, fval2.unify(fval1))) elif isinstance(fval2, CustomFeatureValue): result = fval2.unify(fval1) # Case 5c: Simple values -- check if they're equal. else: if fval1 == fval2: result = fval1 else: result = UnificationFailure # If either value was a bound variable, then update the # bindings. (This is really only necessary if fname is a # Feature or if either value is a CustomFeatureValue.) if result is not UnificationFailure: if fvar1 is not None: bindings[fvar1] = result result = fvar1 if fvar2 is not None and fvar2 != fvar1: bindings[fvar2] = result result = fvar2 # If we unification failed, call the failure function; it # might decide to continue anyway. if result is UnificationFailure: if fail is not None: result = fail(fval1, fval2, fpath) if trace: _trace_unify_fail(fpath[:-1], result) if result is UnificationFailure: raise _UnificationFailureError # Normalize the result. if isinstance(result, fs_class): result = _apply_forwards(result, forward, fs_class, set()) if trace: _trace_unify_succeed(fpath, result) if trace and isinstance(result, fs_class): _trace_bindings(fpath, bindings) return result def _apply_forwards_to_bindings(forward, bindings): """ Replace any feature structure that has a forward pointer with the target of its forward pointer (to preserve reentrancy). """ for (var, value) in bindings.items(): while id(value) in forward: value = forward[id(value)] bindings[var] = value def _apply_forwards(fstruct, forward, fs_class, visited): """ Replace any feature structure that has a forward pointer with the target of its forward pointer (to preserve reentrancy). """ # Follow our own forwards pointers (if any) while id(fstruct) in forward: fstruct = forward[id(fstruct)] # Visit each node only once: if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = fstruct.items() elif _is_sequence(fstruct): items = enumerate(fstruct) else: raise ValueError('Expected mapping or sequence') for fname, fval in items: if isinstance(fval, fs_class): # Replace w/ forwarded value. while id(fval) in forward: fval = forward[id(fval)] fstruct[fname] = fval # Recurse to child. _apply_forwards(fval, forward, fs_class, visited) return fstruct def _resolve_aliases(bindings): """ Replace any bound aliased vars with their binding; and replace any unbound aliased vars with their representative var. """ for (var, value) in bindings.items(): while isinstance(value, Variable) and value in bindings: value = bindings[var] = bindings[value] def _trace_unify_start(path, fval1, fval2): if path == (): print('\nUnification trace:') else: fullname = '.'.join("%s" % n for n in path) print(' '+'| '*(len(path)-1)+'|') print(' '+'| '*(len(path)-1)+'| Unify feature: %s' % fullname) print(' '+'| '*len(path)+' / '+_trace_valrepr(fval1)) print(' '+'| '*len(path)+'|\\ '+_trace_valrepr(fval2)) def _trace_unify_identity(path, fval1): print(' '+'| '*len(path)+'|') print(' '+'| '*len(path)+'| (identical objects)') print(' '+'| '*len(path)+'|') print(' '+'| '*len(path)+'+-->'+unicode_repr(fval1)) def _trace_unify_fail(path, result): if result is UnificationFailure: resume = '' else: resume = ' (nonfatal)' print(' '+'| '*len(path)+'| |') print(' '+'X '*len(path)+'X X <-- FAIL'+resume) def _trace_unify_succeed(path, fval1): # Print the result. print(' '+'| '*len(path)+'|') print(' '+'| '*len(path)+'+-->'+unicode_repr(fval1)) def _trace_bindings(path, bindings): # Print the bindings (if any). if len(bindings) > 0: binditems = sorted(bindings.items(), key=lambda v:v[0].name) bindstr = '{%s}' % ', '.join( '%s: %s' % (var, _trace_valrepr(val)) for (var, val) in binditems) print(' '+'| '*len(path)+' Bindings: '+bindstr) def _trace_valrepr(val): if isinstance(val, Variable): return '%s' % val else: return '%s' % unicode_repr(val) def subsumes(fstruct1, fstruct2): """ Return True if ``fstruct1`` subsumes ``fstruct2``. I.e., return true if unifying ``fstruct1`` with ``fstruct2`` would result in a feature structure equal to ``fstruct2.`` :rtype: bool """ return fstruct2 == unify(fstruct1, fstruct2) def conflicts(fstruct1, fstruct2, trace=0): """ Return a list of the feature paths of all features which are assigned incompatible values by ``fstruct1`` and ``fstruct2``. :rtype: list(tuple) """ conflict_list = [] def add_conflict(fval1, fval2, path): conflict_list.append(path) return fval1 unify(fstruct1, fstruct2, fail=add_conflict, trace=trace) return conflict_list ###################################################################### # Helper Functions ###################################################################### def _is_mapping(v): return hasattr(v, '__contains__') and hasattr(v, 'keys') def _is_sequence(v): return (hasattr(v, '__iter__') and hasattr(v, '__len__') and not isinstance(v, string_types)) def _default_fs_class(obj): if isinstance(obj, FeatStruct): return FeatStruct if isinstance(obj, (dict, list)): return (dict, list) else: raise ValueError('To unify objects of type %s, you must specify ' 'fs_class explicitly.' % obj.__class__.__name__) ###################################################################### # FeatureValueSet & FeatureValueTuple ###################################################################### class SubstituteBindingsSequence(SubstituteBindingsI): """ A mixin class for sequence clases that distributes variables() and substitute_bindings() over the object's elements. """ def variables(self): return ([elt for elt in self if isinstance(elt, Variable)] + sum([list(elt.variables()) for elt in self if isinstance(elt, SubstituteBindingsI)], [])) def substitute_bindings(self, bindings): return self.__class__([self.subst(v, bindings) for v in self]) def subst(self, v, bindings): if isinstance(v, SubstituteBindingsI): return v.substitute_bindings(bindings) else: return bindings.get(v, v) @python_2_unicode_compatible class FeatureValueTuple(SubstituteBindingsSequence, tuple): """ A base feature value that is a tuple of other base feature values. FeatureValueTuple implements ``SubstituteBindingsI``, so it any variable substitutions will be propagated to the elements contained by the set. A ``FeatureValueTuple`` is immutable. """ def __repr__(self): # [xx] really use %s here? if len(self) == 0: return '()' return '(%s)' % ', '.join('%s' % (b,) for b in self) @python_2_unicode_compatible class FeatureValueSet(SubstituteBindingsSequence, frozenset): """ A base feature value that is a set of other base feature values. FeatureValueSet implements ``SubstituteBindingsI``, so it any variable substitutions will be propagated to the elements contained by the set. A ``FeatureValueSet`` is immutable. """ def __repr__(self): # [xx] really use %s here? if len(self) == 0: return '{/}' # distinguish from dict. # n.b., we sort the string reprs of our elements, to ensure # that our own repr is deterministic. return '{%s}' % ', '.join(sorted('%s' % (b,) for b in self)) __str__ = __repr__ @python_2_unicode_compatible class FeatureValueUnion(SubstituteBindingsSequence, frozenset): """ A base feature value that represents the union of two or more ``FeatureValueSet`` or ``Variable``. """ def __new__(cls, values): # If values contains FeatureValueUnions, then collapse them. values = _flatten(values, FeatureValueUnion) # If the resulting list contains no variables, then # use a simple FeatureValueSet instead. if sum(isinstance(v, Variable) for v in values) == 0: values = _flatten(values, FeatureValueSet) return FeatureValueSet(values) # If we contain a single variable, return that variable. if len(values) == 1: return list(values)[0] # Otherwise, build the FeatureValueUnion. return frozenset.__new__(cls, values) def __repr__(self): # n.b., we sort the string reprs of our elements, to ensure # that our own repr is deterministic. also, note that len(self) # is guaranteed to be 2 or more. return '{%s}' % '+'.join(sorted('%s' % (b,) for b in self)) @python_2_unicode_compatible class FeatureValueConcat(SubstituteBindingsSequence, tuple): """ A base feature value that represents the concatenation of two or more ``FeatureValueTuple`` or ``Variable``. """ def __new__(cls, values): # If values contains FeatureValueConcats, then collapse them. values = _flatten(values, FeatureValueConcat) # If the resulting list contains no variables, then # use a simple FeatureValueTuple instead. if sum(isinstance(v, Variable) for v in values) == 0: values = _flatten(values, FeatureValueTuple) return FeatureValueTuple(values) # If we contain a single variable, return that variable. if len(values) == 1: return list(values)[0] # Otherwise, build the FeatureValueConcat. return tuple.__new__(cls, values) def __repr__(self): # n.b.: len(self) is guaranteed to be 2 or more. return '(%s)' % '+'.join('%s' % (b,) for b in self) def _flatten(lst, cls): """ Helper function -- return a copy of list, with all elements of type ``cls`` spliced in rather than appended in. """ result = [] for elt in lst: if isinstance(elt, cls): result.extend(elt) else: result.append(elt) return result ###################################################################### # Specialized Features ###################################################################### @total_ordering @python_2_unicode_compatible class Feature(object): """ A feature identifier that's specialized to put additional constraints, default values, etc. """ def __init__(self, name, default=None, display=None): assert display in (None, 'prefix', 'slash') self._name = name # [xx] rename to .identifier? self._default = default # [xx] not implemented yet. self._display = display if self._display == 'prefix': self._sortkey = (-1, self._name) elif self._display == 'slash': self._sortkey = (1, self._name) else: self._sortkey = (0, self._name) @property def name(self): """The name of this feature.""" return self._name @property def default(self): """Default value for this feature.""" return self._default @property def display(self): """Custom display location: can be prefix, or slash.""" return self._display def __repr__(self): return '*%s*' % self.name def __lt__(self, other): if isinstance(other, string_types): return True if not isinstance(other, Feature): raise_unorderable_types("<", self, other) return self._sortkey < other._sortkey def __eq__(self, other): return type(self) == type(other) and self._name == other._name def __ne__(self, other): return not self == other def __hash__(self): return hash(self._name) #//////////////////////////////////////////////////////////// # These can be overridden by subclasses: #//////////////////////////////////////////////////////////// def parse_value(self, s, position, reentrances, parser): return parser.parse_value(s, position, reentrances) def unify_base_values(self, fval1, fval2, bindings): """ If possible, return a single value.. If not, return the value ``UnificationFailure``. """ if fval1 == fval2: return fval1 else: return UnificationFailure class SlashFeature(Feature): def parse_value(self, s, position, reentrances, parser): return parser.partial_parse(s, position, reentrances) class RangeFeature(Feature): RANGE_RE = re.compile('(-?\d+):(-?\d+)') def parse_value(self, s, position, reentrances, parser): m = self.RANGE_RE.match(s, position) if not m: raise ValueError('range', position) return (int(m.group(1)), int(m.group(2))), m.end() def unify_base_values(self, fval1, fval2, bindings): if fval1 is None: return fval2 if fval2 is None: return fval1 rng = max(fval1[0], fval2[0]), min(fval1[1], fval2[1]) if rng[1] < rng[0]: return UnificationFailure return rng SLASH = SlashFeature('slash', default=False, display='slash') TYPE = Feature('type', display='prefix') ###################################################################### # Specialized Feature Values ###################################################################### @total_ordering class CustomFeatureValue(object): """ An abstract base class for base values that define a custom unification method. The custom unification method of ``CustomFeatureValue`` will be used during unification if: - The ``CustomFeatureValue`` is unified with another base value. - The ``CustomFeatureValue`` is not the value of a customized ``Feature`` (which defines its own unification method). If two ``CustomFeatureValue`` objects are unified with one another during feature structure unification, then the unified base values they return *must* be equal; otherwise, an ``AssertionError`` will be raised. Subclasses must define ``unify()``, ``__eq__()`` and ``__lt__()``. Subclasses may also wish to define ``__hash__()``. """ def unify(self, other): """ If this base value unifies with ``other``, then return the unified value. Otherwise, return ``UnificationFailure``. """ raise NotImplementedError('abstract base class') def __eq__(self, other): raise NotImplementedError('abstract base class') def __ne__(self, other): return not self == other def __lt__(self, other): raise NotImplementedError('abstract base class') def __hash__(self): raise TypeError('%s objects or unhashable' % self.__class__.__name__) ###################################################################### # Feature Structure Parser ###################################################################### class FeatStructParser(object): def __init__(self, features=(SLASH, TYPE), fdict_class=FeatStruct, flist_class=FeatList, logic_parser=None): self._features = dict((f.name,f) for f in features) self._fdict_class = fdict_class self._flist_class = flist_class self._prefix_feature = None self._slash_feature = None for feature in features: if feature.display == 'slash': if self._slash_feature: raise ValueError('Multiple features w/ display=slash') self._slash_feature = feature if feature.display == 'prefix': if self._prefix_feature: raise ValueError('Multiple features w/ display=prefix') self._prefix_feature = feature self._features_with_defaults = [feature for feature in features if feature.default is not None] if logic_parser is None: logic_parser = LogicParser() self._logic_parser = logic_parser def parse(self, s, fstruct=None): """ Convert a string representation of a feature structure (as displayed by repr) into a ``FeatStruct``. This parse imposes the following restrictions on the string representation: - Feature names cannot contain any of the following: whitespace, parentheses, quote marks, equals signs, dashes, commas, and square brackets. Feature names may not begin with plus signs or minus signs. - Only the following basic feature value are supported: strings, integers, variables, None, and unquoted alphanumeric strings. - For reentrant values, the first mention must specify a reentrance identifier and a value; and any subsequent mentions must use arrows (``'->'``) to reference the reentrance identifier. """ s = s.strip() value, position = self.partial_parse(s, 0, {}, fstruct) if position != len(s): self._error(s, 'end of string', position) return value _START_FSTRUCT_RE = re.compile(r'\s*(?:\((\d+)\)\s*)?(\??[\w-]+)?(\[)') _END_FSTRUCT_RE = re.compile(r'\s*]\s*') _SLASH_RE = re.compile(r'/') _FEATURE_NAME_RE = re.compile(r'\s*([+-]?)([^\s\(\)<>"\'\-=\[\],]+)\s*') _REENTRANCE_RE = re.compile(r'\s*->\s*') _TARGET_RE = re.compile(r'\s*\((\d+)\)\s*') _ASSIGN_RE = re.compile(r'\s*=\s*') _COMMA_RE = re.compile(r'\s*,\s*') _BARE_PREFIX_RE = re.compile(r'\s*(?:\((\d+)\)\s*)?(\??[\w-]+\s*)()') # This one is used to distinguish fdicts from flists: _START_FDICT_RE = re.compile(r'(%s)|(%s\s*(%s\s*(=|->)|[+-]%s|\]))' % ( _BARE_PREFIX_RE.pattern, _START_FSTRUCT_RE.pattern, _FEATURE_NAME_RE.pattern, _FEATURE_NAME_RE.pattern)) def partial_parse(self, s, position=0, reentrances=None, fstruct=None): """ Helper function that parses a feature structure. :param s: The string to parse. :param position: The position in the string to start parsing. :param reentrances: A dictionary from reentrance ids to values. Defaults to an empty dictionary. :return: A tuple (val, pos) of the feature structure created by parsing and the position where the parsed feature structure ends. :rtype: bool """ if reentrances is None: reentrances = {} try: return self._partial_parse(s, position, reentrances, fstruct) except ValueError as e: if len(e.args) != 2: raise self._error(s, *e.args) def _partial_parse(self, s, position, reentrances, fstruct=None): # Create the new feature structure if fstruct is None: if self._START_FDICT_RE.match(s, position): fstruct = self._fdict_class() else: fstruct = self._flist_class() # Read up to the open bracket. match = self._START_FSTRUCT_RE.match(s, position) if not match: match = self._BARE_PREFIX_RE.match(s, position) if not match: raise ValueError('open bracket or identifier', position) position = match.end() # If there as an identifier, record it. if match.group(1): identifier = match.group(1) if identifier in reentrances: raise ValueError('new identifier', match.start(1)) reentrances[identifier] = fstruct if isinstance(fstruct, FeatDict): fstruct.clear() return self._partial_parse_featdict(s, position, match, reentrances, fstruct) else: del fstruct[:] return self._partial_parse_featlist(s, position, match, reentrances, fstruct) def _partial_parse_featlist(self, s, position, match, reentrances, fstruct): # Prefix features are not allowed: if match.group(2): raise ValueError('open bracket') # Bare prefixes are not allowed: if not match.group(3): raise ValueError('open bracket') # Build a list of the features defined by the structure. while position < len(s): # Check for the close bracket. match = self._END_FSTRUCT_RE.match(s, position) if match is not None: return fstruct, match.end() # Reentances have the form "-> (target)" match = self._REENTRANCE_RE.match(s, position) if match: position = match.end() match = self._TARGET_RE.match(s, position) if not match: raise ValueError('identifier', position) target = match.group(1) if target not in reentrances: raise ValueError('bound identifier', position) position = match.end() fstruct.append(reentrances[target]) # Anything else is a value. else: value, position = ( self._parse_value(0, s, position, reentrances)) fstruct.append(value) # If there's a close bracket, handle it at the top of the loop. if self._END_FSTRUCT_RE.match(s, position): continue # Otherwise, there should be a comma match = self._COMMA_RE.match(s, position) if match is None: raise ValueError('comma', position) position = match.end() # We never saw a close bracket. raise ValueError('close bracket', position) def _partial_parse_featdict(self, s, position, match, reentrances, fstruct): # If there was a prefix feature, record it. if match.group(2): if self._prefix_feature is None: raise ValueError('open bracket or identifier', match.start(2)) prefixval = match.group(2).strip() if prefixval.startswith('?'): prefixval = Variable(prefixval) fstruct[self._prefix_feature] = prefixval # If group 3 is empty, then we just have a bare prefix, so # we're done. if not match.group(3): return self._finalize(s, match.end(), reentrances, fstruct) # Build a list of the features defined by the structure. # Each feature has one of the three following forms: # name = value # name -> (target) # +name # -name while position < len(s): # Use these variables to hold info about each feature: name = value = None # Check for the close bracket. match = self._END_FSTRUCT_RE.match(s, position) if match is not None: return self._finalize(s, match.end(), reentrances, fstruct) # Get the feature name's name match = self._FEATURE_NAME_RE.match(s, position) if match is None: raise ValueError('feature name', position) name = match.group(2) position = match.end() # Check if it's a special feature. if name[0] == '*' and name[-1] == '*': name = self._features.get(name[1:-1]) if name is None: raise ValueError('known special feature', match.start(2)) # Check if this feature has a value already. if name in fstruct: raise ValueError('new name', match.start(2)) # Boolean value ("+name" or "-name") if match.group(1) == '+': value = True if match.group(1) == '-': value = False # Reentrance link ("-> (target)") if value is None: match = self._REENTRANCE_RE.match(s, position) if match is not None: position = match.end() match = self._TARGET_RE.match(s, position) if not match: raise ValueError('identifier', position) target = match.group(1) if target not in reentrances: raise ValueError('bound identifier', position) position = match.end() value = reentrances[target] # Assignment ("= value"). if value is None: match = self._ASSIGN_RE.match(s, position) if match: position = match.end() value, position = ( self._parse_value(name, s, position, reentrances)) # None of the above: error. else: raise ValueError('equals sign', position) # Store the value. fstruct[name] = value # If there's a close bracket, handle it at the top of the loop. if self._END_FSTRUCT_RE.match(s, position): continue # Otherwise, there should be a comma match = self._COMMA_RE.match(s, position) if match is None: raise ValueError('comma', position) position = match.end() # We never saw a close bracket. raise ValueError('close bracket', position) def _finalize(self, s, pos, reentrances, fstruct): """ Called when we see the close brace -- checks for a slash feature, and adds in default values. """ # Add the slash feature (if any) match = self._SLASH_RE.match(s, pos) if match: name = self._slash_feature v, pos = self._parse_value(name, s, match.end(), reentrances) fstruct[name] = v ## Add any default features. -- handle in unficiation instead? #for feature in self._features_with_defaults: # fstruct.setdefault(feature, feature.default) # Return the value. return fstruct, pos def _parse_value(self, name, s, position, reentrances): if isinstance(name, Feature): return name.parse_value(s, position, reentrances, self) else: return self.parse_value(s, position, reentrances) def parse_value(self, s, position, reentrances): for (handler, regexp) in self.VALUE_HANDLERS: match = regexp.match(s, position) if match: handler_func = getattr(self, handler) return handler_func(s, position, reentrances, match) raise ValueError('value', position) def _error(self, s, expected, position): lines = s.split('\n') while position > len(lines[0]): position -= len(lines.pop(0))+1 # +1 for the newline. estr = ('Error parsing feature structure\n ' + lines[0] + '\n ' + ' '*position + '^ ' + 'Expected %s' % expected) raise ValueError(estr) #//////////////////////////////////////////////////////////// #{ Value Parsers #//////////////////////////////////////////////////////////// #: A table indicating how feature values should be parsed. Each #: entry in the table is a pair (handler, regexp). The first entry #: with a matching regexp will have its handler called. Handlers #: should have the following signature:: #: #: def handler(s, position, reentrances, match): ... #: #: and should return a tuple (value, position), where position is #: the string position where the value ended. (n.b.: order is #: important here!) VALUE_HANDLERS = [ ('parse_fstruct_value', _START_FSTRUCT_RE), ('parse_var_value', re.compile(r'\?[a-zA-Z_][a-zA-Z0-9_]*')), ('parse_str_value', re.compile("[uU]?[rR]?(['\"])")), ('parse_int_value', re.compile(r'-?\d+')), ('parse_sym_value', re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')), ('parse_app_value', re.compile(r'<(app)\((\?[a-z][a-z]*)\s*,' r'\s*(\?[a-z][a-z]*)\)>')), # ('parse_logic_value', re.compile(r'<([^>]*)>')), #lazily match any character after '<' until we hit a '>' not preceded by '-' ('parse_logic_value', re.compile(r'<(.*?)(?<!-)>')), ('parse_set_value', re.compile(r'{')), ('parse_tuple_value', re.compile(r'\(')), ] def parse_fstruct_value(self, s, position, reentrances, match): return self.partial_parse(s, position, reentrances) def parse_str_value(self, s, position, reentrances, match): return parse_str(s, position) def parse_int_value(self, s, position, reentrances, match): return int(match.group()), match.end() # Note: the '?' is included in the variable name. def parse_var_value(self, s, position, reentrances, match): return Variable(match.group()), match.end() _SYM_CONSTS = {'None':None, 'True':True, 'False':False} def parse_sym_value(self, s, position, reentrances, match): val, end = match.group(), match.end() return self._SYM_CONSTS.get(val, val), end def parse_app_value(self, s, position, reentrances, match): """Mainly included for backwards compat.""" return self._logic_parser.parse('%s(%s)' % match.group(2,3)), match.end() def parse_logic_value(self, s, position, reentrances, match): try: try: expr = self._logic_parser.parse(match.group(1)) except ParseException: raise ValueError() return expr, match.end() except ValueError: raise ValueError('logic expression', match.start(1)) def parse_tuple_value(self, s, position, reentrances, match): return self._parse_seq_value(s, position, reentrances, match, ')', FeatureValueTuple, FeatureValueConcat) def parse_set_value(self, s, position, reentrances, match): return self._parse_seq_value(s, position, reentrances, match, '}', FeatureValueSet, FeatureValueUnion) def _parse_seq_value(self, s, position, reentrances, match, close_paren, seq_class, plus_class): """ Helper function used by parse_tuple_value and parse_set_value. """ cp = re.escape(close_paren) position = match.end() # Special syntax fo empty tuples: m = re.compile(r'\s*/?\s*%s' % cp).match(s, position) if m: return seq_class(), m.end() # Read values: values = [] seen_plus = False while True: # Close paren: return value. m = re.compile(r'\s*%s' % cp).match(s, position) if m: if seen_plus: return plus_class(values), m.end() else: return seq_class(values), m.end() # Read the next value. val, position = self.parse_value(s, position, reentrances) values.append(val) # Comma or looking at close paren m = re.compile(r'\s*(,|\+|(?=%s))\s*' % cp).match(s, position) if m.group(1) == '+': seen_plus = True if not m: raise ValueError("',' or '+' or '%s'" % cp, position) position = m.end() ###################################################################### #{ Demo ###################################################################### def display_unification(fs1, fs2, indent=' '): # Print the two input feature structures, side by side. fs1_lines = ("%s" % fs1).split('\n') fs2_lines = ("%s" % fs2).split('\n') if len(fs1_lines) > len(fs2_lines): blankline = '['+' '*(len(fs2_lines[0])-2)+']' fs2_lines += [blankline]*len(fs1_lines) else: blankline = '['+' '*(len(fs1_lines[0])-2)+']' fs1_lines += [blankline]*len(fs2_lines) for (fs1_line, fs2_line) in zip(fs1_lines, fs2_lines): print(indent + fs1_line + ' ' + fs2_line) print(indent+'-'*len(fs1_lines[0])+' '+'-'*len(fs2_lines[0])) linelen = len(fs1_lines[0])*2+3 print(indent+'| |'.center(linelen)) print(indent+'+-----UNIFY-----+'.center(linelen)) print(indent+'|'.center(linelen)) print(indent+'V'.center(linelen)) bindings = {} result = fs1.unify(fs2, bindings) if result is None: print(indent+'(FAILED)'.center(linelen)) else: print('\n'.join(indent+l.center(linelen) for l in ("%s" % result).split('\n'))) if bindings and len(bindings.bound_variables()) > 0: print(repr(bindings).center(linelen)) return result def interactive_demo(trace=False): import random, sys HELP = ''' 1-%d: Select the corresponding feature structure q: Quit t: Turn tracing on or off l: List all feature structures ?: Help ''' print(''' This demo will repeatedly present you with a list of feature structures, and ask you to choose two for unification. Whenever a new feature structure is generated, it is added to the list of choices that you can pick from. However, since this can be a large number of feature structures, the demo will only print out a random subset for you to choose between at a given time. If you want to see the complete lists, type "l". For a list of valid commands, type "?". ''') print('Press "Enter" to continue...') sys.stdin.readline() fstruct_strings = [ '[agr=[number=sing, gender=masc]]', '[agr=[gender=masc, person=3]]', '[agr=[gender=fem, person=3]]', '[subj=[agr=(1)[]], agr->(1)]', '[obj=?x]', '[subj=?x]', '[/=None]', '[/=NP]', '[cat=NP]', '[cat=VP]', '[cat=PP]', '[subj=[agr=[gender=?y]], obj=[agr=[gender=?y]]]', '[gender=masc, agr=?C]', '[gender=?S, agr=[gender=?S,person=3]]' ] all_fstructs = [(i, FeatStruct(fstruct_strings[i])) for i in range(len(fstruct_strings))] def list_fstructs(fstructs): for i, fstruct in fstructs: print() lines = ("%s" % fstruct).split('\n') print('%3d: %s' % (i+1, lines[0])) for line in lines[1:]: print(' '+line) print() while True: # Pick 5 feature structures at random from the master list. MAX_CHOICES = 5 if len(all_fstructs) > MAX_CHOICES: fstructs = sorted(random.sample(all_fstructs, MAX_CHOICES)) else: fstructs = all_fstructs print('_'*75) print('Choose two feature structures to unify:') list_fstructs(fstructs) selected = [None,None] for (nth,i) in (('First',0), ('Second',1)): while selected[i] is None: print(('%s feature structure (1-%d,q,t,l,?): ' % (nth, len(all_fstructs))), end=' ') try: input = sys.stdin.readline().strip() if input in ('q', 'Q', 'x', 'X'): return if input in ('t', 'T'): trace = not trace print(' Trace = %s' % trace) continue if input in ('h', 'H', '?'): print(HELP % len(fstructs)); continue if input in ('l', 'L'): list_fstructs(all_fstructs); continue num = int(input)-1 selected[i] = all_fstructs[num][1] print() except: print('Bad sentence number') continue if trace: result = selected[0].unify(selected[1], trace=1) else: result = display_unification(selected[0], selected[1]) if result is not None: for i, fstruct in all_fstructs: if repr(result) == repr(fstruct): break else: all_fstructs.append((len(all_fstructs), result)) print('\nType "Enter" to continue unifying; or "q" to quit.') input = sys.stdin.readline().strip() if input in ('q', 'Q', 'x', 'X'): return def demo(trace=False): """ Just for testing """ #import random # parser breaks with values like '3rd' fstruct_strings = [ '[agr=[number=sing, gender=masc]]', '[agr=[gender=masc, person=3]]', '[agr=[gender=fem, person=3]]', '[subj=[agr=(1)[]], agr->(1)]', '[obj=?x]', '[subj=?x]', '[/=None]', '[/=NP]', '[cat=NP]', '[cat=VP]', '[cat=PP]', '[subj=[agr=[gender=?y]], obj=[agr=[gender=?y]]]', '[gender=masc, agr=?C]', '[gender=?S, agr=[gender=?S,person=3]]' ] all_fstructs = [FeatStruct(fss) for fss in fstruct_strings] #MAX_CHOICES = 5 #if len(all_fstructs) > MAX_CHOICES: #fstructs = random.sample(all_fstructs, MAX_CHOICES) #fstructs.sort() #else: #fstructs = all_fstructs for fs1 in all_fstructs: for fs2 in all_fstructs: print("\n*******************\nfs1 is:\n%s\n\nfs2 is:\n%s\n\nresult is:\n%s" % (fs1, fs2, unify(fs1, fs2))) if __name__ == '__main__': demo() __all__ = ['FeatStruct', 'FeatDict', 'FeatList', 'unify', 'subsumes', 'conflicts', 'Feature', 'SlashFeature', 'RangeFeature', 'SLASH', 'TYPE', 'FeatStructParser']
bbengfort/TextBlob
textblob/nltk/featstruct.py
Python
mit
102,193
[ "VisIt" ]
522a3501b60955271e0d1d13937aa3f1d834f15d4f8425c27a7f97334b5c0c0d
import json from pathlib import Path from ._schemata import ( TomvizSchema, ) from ._models import ( # noqa Pipeline, DataSource, init_operators, init_modules, ) from ._jsonpatch import ( sync_state_to_app, sync_state_to_python ) from ._pipeline import PipelineStateManager from ._views import ( View ) from paraview.simple import ( GetViews, GetActiveView, ) t = None pipelines = None views = [] active_view = None _state = None def _init(): global pipelines global _state _state = PipelineStateManager().serialize() _state = json.loads(_state) schema = TomvizSchema() global t t = schema.load(_state) pipelines = t.pipelines def _sync_to_python(pipeline_state): global _state schema = TomvizSchema() _state = schema.dump(t) sync_state_to_python(_state, json.loads(pipeline_state)) _state = schema.dump(t) def _current_state(): global t schema = TomvizSchema() return schema.dump(t) def _pipeline_index(ds): for (i, p) in enumerate(pipelines): if p.dataSource == ds: return i break return -1 def _active_view(): return View(GetActiveView()) def _views(): return [View(v) for v in GetViews()] views = _views() active_view = _active_view() def _sync_views(): global views global active_view views = _views() active_view = _active_view() def sync(): global _state schema = TomvizSchema() new_state = schema.dump(t) sync_state_to_app(_state, new_state) _state = schema.dump(t)#new_state def reset(): _init() def load(state, state_dir=None): def _load_from_path(path): nonlocal state_dir state_dir = str(path.parent) with path.open('r') as fp: state = fp.read() return state if isinstance(state, str): path = Path(state) state = _load_from_path(path) elif isinstance(state, Path): state = _load_from_path(state) elif isinstance(state, dict): state = json.dumps(state) elif hasattr(state, 'read'): state = state.read() if state_dir is None: raise Exception("'state_dir' must be provided inorder to locate data " "associated with state file.") PipelineStateManager().load(state, state_dir) init_modules() init_operators() _init()
OpenChemistry/tomviz
tomviz/python/tomviz/state/__init__.py
Python
bsd-3-clause
2,402
[ "ParaView" ]
437b2f1e74e0d94648f25aa3893878d66f73fefffbc64d18bf95634db1401717
"""Options manager for :class:`Poly` and public API functions. """ from sympy.core import S, Basic, sympify from sympy.utilities import any, all, numbered_symbols, topological_sort from sympy.polys.polyerrors import ( GeneratorsError, OptionError, FlagError, ) import sympy.polys import re class Option(object): """Base class for all kinds of options. """ option = None is_Flag = False requires = [] excludes = [] after = [] before = [] @classmethod def default(cls): return None @classmethod def preprocess(cls, option): return None @classmethod def postprocess(cls, options): pass class Flag(Option): """Base class for all kinds of flags. """ is_Flag = True class BooleanOption(Option): """An option that must have a boolean value or equivalent assigned. """ @classmethod def preprocess(cls, value): if value is True or value is False or value is 1 or value is 0: return bool(value) else: raise OptionError("'%s' must have a boolean value assigned, got %s" % (cls.option, value)) class OptionType(type): """Base type for all options that does registers options. """ def __init__(cls, *args, **kwargs): @property def getter(self): try: return self[cls.option] except KeyError: return cls.default() setattr(Options, cls.option, getter) Options.__options__[cls.option] = cls class Options(dict): """ Options manager for polynomial manipulation module. **Examples** >>> from sympy.polys.polyoptions import Options >>> from sympy.polys.polyoptions import build_options >>> from sympy.abc import x, y, z >>> Options((x, y, z), {'domain': 'ZZ'}) {'auto': False, 'domain': ZZ, 'gens': (x, y, z)} >>> build_options((x, y, z), {'domain': 'ZZ'}) {'auto': False, 'domain': ZZ, 'gens': (x, y, z)} **Options** * Expand --- boolean option * Gens --- option * Wrt --- option * Sort --- option * Order --- option * Field --- boolean option * Greedy --- boolean option * Domain --- option * Split --- boolean option * Gaussian --- boolean option * Extension --- option * Modulus --- option * Symmetric --- boolean option * Strict --- boolean option * Repr --- option **Flags** * Auto --- boolean flag * Frac --- boolean flag * Formal --- boolean flag * Polys --- boolean flag * Include --- boolean flag * All --- boolean flag * Gen --- flag """ __order__ = None __options__ = {} def __init__(self, gens, args, flags=None, strict=False): dict.__init__(self) if gens and args.get('gens', ()): raise OptionError("both '*gens' and keyword argument 'gens' supplied") elif gens: args = dict(args) args['gens'] = gens for option, value in args.iteritems(): try: cls = self.__options__[option] except KeyError: raise OptionError("'%s' is not a valid option" % option) if issubclass(cls, Flag): if flags is None or option not in flags: if strict: raise OptionError("'%s' flag is not allowed in this context" % option) if value is not None: self[option] = cls.preprocess(value) for option in self.keys(): cls = self.__options__[option] for require_option in cls.requires: if self.get(require_option) is None: raise OptionError("'%s' option is only allowed together with '%s'" % (option, require_option)) for exclude_option in cls.excludes: if self.get(exclude_option) is not None: raise OptionError("'%s' option is not allowed together with '%s'" % (option, exclude_option)) for option in self.__order__: self.__options__[option].postprocess(self) @classmethod def _init_dependencies_order(cls): """Resolve the order of options' processing. """ if cls.__order__ is None: vertices, edges = [], set([]) for name, option in cls.__options__.iteritems(): vertices.append(name) for _name in option.after: edges.add((_name, name)) for _name in option.before: edges.add((name, _name)) try: cls.__order__ = topological_sort((vertices, list(edges))) except ValueError: raise RuntimeError("cycle detected in sympy.polys options framework") def clone(self, updates={}): """Clone ``self`` and update specified options. """ obj = dict.__new__(self.__class__) for option, value in self.iteritems(): obj[option] = value for option, value in updates.iteritems(): obj[option] = value return obj def __setattr__(self, attr, value): if attr in self.__options__: self[attr] = value else: super(Options, self).__setattr__(attr, value) @property def args(self): args = {} for option, value in self.iteritems(): if value is not None and option != 'gens': cls = self.__options__[option] if not issubclass(cls, Flag): args[option] = value return args @property def options(self): options = {} for option, cls in self.__options__.iteritems(): if not issubclass(cls, Flag): options[option] = getattr(self, option) return options @property def flags(self): flags = {} for option, cls in self.__options__.iteritems(): if issubclass(cls, Flag): flags[option] = getattr(self, option) return flags class Expand(BooleanOption): """``expand`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'expand' requires = [] excludes = [] @classmethod def default(cls): return True class Gens(Option): """``gens`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'gens' requires = [] excludes = [] @classmethod def default(cls): return () @classmethod def preprocess(cls, gens): if isinstance(gens, Basic): gens = (gens,) elif len(gens) == 1 and hasattr(gens[0], '__iter__'): gens = gens[0] if gens == (None,): gens = () elif len(set(gens)) != len(gens): raise GeneratorsError("duplicated generators: %s" % str(gens)) elif any(gen.is_commutative is False for gen in gens): raise GeneratorsError("non-commutative generators: %s" % str(gens)) return tuple(gens) class Wrt(Option): """``wrt`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'wrt' requires = [] excludes = [] _re_split = re.compile(r"\s*,\s*|\s+") @classmethod def preprocess(cls, wrt): if isinstance(wrt, Basic): return [str(wrt)] elif isinstance(wrt, str): wrt = wrt.strip() if wrt.endswith(','): raise OptionError('Bad input: missing parameter.') if not wrt: return [] return [ gen for gen in cls._re_split.split(wrt) ] elif hasattr(wrt, '__getitem__'): return list(map(str, wrt)) else: raise OptionError("invalid argument for 'wrt' option") class Sort(Option): """``sort`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'sort' requires = [] excludes = [] @classmethod def default(cls): return [] @classmethod def preprocess(cls, sort): if isinstance(sort, str): return [ gen.strip() for gen in sort.split('>') ] elif hasattr(sort, '__getitem__'): return list(map(str, sort)) else: raise OptionError("invalid argument for 'sort' option") class Order(Option): """``order`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'order' requires = [] excludes = [] @classmethod def default(cls): return sympy.polys.monomialtools.monomial_key('lex') @classmethod def preprocess(cls, order): return sympy.polys.monomialtools.monomial_key(order) class Field(BooleanOption): """``field`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'field' requires = [] excludes = ['domain', 'split', 'gaussian'] class Greedy(BooleanOption): """``greedy`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'greedy' requires = [] excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric'] class Composite(BooleanOption): """ """ __metaclass__ = OptionType option = 'composite' @classmethod def default(cls): return True requires = [] excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric'] class Domain(Option): """``domain`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'domain' requires = [] excludes = ['field', 'greedy', 'split', 'gaussian', 'extension'] _re_finitefield = re.compile("^(FF|GF)\((\d+)\)$") _re_polynomial = re.compile("^(Z|ZZ|Q|QQ)\[(.+)\]$") _re_fraction = re.compile("^(Z|ZZ|Q|QQ)\((.+)\)$") _re_algebraic = re.compile("^(Q|QQ)\<(.+)\>$") @classmethod def preprocess(cls, domain): if not isinstance(domain, str): return domain else: if domain in ['Z', 'ZZ']: return sympy.polys.domains.ZZ if domain in ['Q', 'QQ']: return sympy.polys.domains.QQ if domain in ['R', 'RR']: return sympy.polys.domains.RR if domain == 'EX': return sympy.polys.domains.EX r = cls._re_finitefield.match(domain) if r is not None: return sympy.polys.domains.FF(int(r.groups()[1])) r = cls._re_polynomial.match(domain) if r is not None: ground, gens = r.groups() gens = map(sympify, gens.split(',')) if ground in ['Z', 'ZZ']: return sympy.polys.domains.ZZ.poly_ring(*gens) else: return sympy.polys.domains.QQ.poly_ring(*gens) r = cls._re_fraction.match(domain) if r is not None: ground, gens = r.groups() gens = map(sympify, gens.split(',')) if ground in ['Z', 'ZZ']: return sympy.polys.domains.ZZ.frac_field(*gens) else: return sympy.polys.domains.QQ.frac_field(*gens) r = cls._re_algebraic.match(domain) if r is not None: gens = map(sympify, r.groups()[1].split(',')) return sympy.polys.domains.QQ.algebraic_field(*gens) raise OptionError('expected a valid domain specification, got %s' % domain) @classmethod def postprocess(cls, options): if 'gens' in options and 'domain' in options and options['domain'].is_Composite and \ (set(options['domain'].gens) & set(options['gens'])): raise GeneratorsError("ground domain and generators interferes together") class Split(BooleanOption): """``split`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'split' requires = [] excludes = ['field', 'greedy', 'domain', 'gaussian', 'extension', 'modulus', 'symmetric'] @classmethod def postprocess(cls, options): if 'split' in options: raise NotImplementedError("'split' option is not implemented yet") class Gaussian(BooleanOption): """``gaussian`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'gaussian' requires = [] excludes = ['field', 'greedy', 'domain', 'split', 'extension', 'modulus', 'symmetric'] @classmethod def postprocess(cls, options): if 'gaussian' in options and options['gaussian'] is True: options['extension'] = set([S.ImaginaryUnit]) Extension.postprocess(options) class Extension(Option): """``extension`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'extension' requires = [] excludes = ['greedy', 'domain', 'split', 'gaussian', 'modulus', 'symmetric'] @classmethod def preprocess(cls, extension): if extension is True or extension is 1: return bool(extension) elif extension is False or extension is 0: raise OptionError("'False' is an invalid argument for 'extension'") else: if not hasattr(extension, '__iter__'): extension = set([extension]) else: if not extension: extension = None else: extension = set(extension) return extension @classmethod def postprocess(cls, options): if 'extension' in options and options['extension'] is not True: options['domain'] = sympy.polys.domains.QQ.algebraic_field(*options['extension']) class Modulus(Option): """``modulus`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'modulus' requires = [] excludes = ['greedy', 'split', 'domain', 'gaussian', 'extension'] @classmethod def preprocess(cls, modulus): modulus = sympify(modulus) if modulus.is_Integer and modulus > 0: return int(modulus) else: raise OptionError("'modulus' must a positive integer, got %s" % modulus) @classmethod def postprocess(cls, options): if 'modulus' in options: modulus = options['modulus'] symmetric = options.get('symmetric', True) options['domain'] = sympy.polys.domains.FF(modulus, symmetric) class Symmetric(BooleanOption): """``symmetric`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'symmetric' requires = ['modulus'] excludes = ['greedy', 'domain', 'split', 'gaussian', 'extension'] class Strict(BooleanOption): """``strict`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'strict' @classmethod def default(cls): return True class Repr(Option): """``repr`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'repr' @classmethod def default(cls): return sympy.polys.densepolys.DensePoly @classmethod def preprocess(cls, repr): if isinstance(repr, str): if repr == 'sparse': return sympy.polys.sparsepolys.SparsePoly elif repr == 'dense': return sympy.polys.densepolys.DensePoly else: raise OptionError("'%s' is not a valid value 'repr' option" % repr) elif isinstance(repr, sympy.polys.polyclasses.GenericPoly): return repr else: raise OptionError("'repr' must a string or a class, got %s" % repr) class Auto(BooleanOption, Flag): """``auto`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'auto' after = ['field', 'domain', 'extension', 'gaussian'] @classmethod def default(cls): return True @classmethod def postprocess(cls, options): if ('domain' in options or 'field' in options) and 'auto' not in options: options['auto'] = False class Frac(BooleanOption, Flag): """``auto`` option to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'frac' @classmethod def default(cls): return False class Formal(BooleanOption, Flag): """``formal`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'formal' @classmethod def default(cls): return False class Polys(BooleanOption, Flag): """``polys`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'polys' class Include(BooleanOption, Flag): """``include`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'include' @classmethod def default(cls): return False class All(BooleanOption, Flag): """``all`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'all' @classmethod def default(cls): return False class Gen(Flag): """``gen`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'gen' @classmethod def default(cls): return 0 @classmethod def preprocess(cls, gen): if isinstance(gen, (Basic, int)): return gen else: raise OptionError("invalid argument for 'gen' option") class Symbols(Flag): """``symbols`` flag to polynomial manipulation functions. """ __metaclass__ = OptionType option = 'symbols' @classmethod def default(cls): return numbered_symbols('s', start=1) @classmethod def preprocess(cls, symbols): if hasattr(symbols, '__iter__'): return iter(symbols) else: raise OptionError("expected an iterator or iterable container, got %s" % symbols) def build_options(gens, args=None): """Construct options from keyword arguments or ... options. """ if args is None: gens, args = (), gens if len(args) != 1 or 'opt' not in args or gens: return Options(gens, args) else: return args['opt'] def allowed_flags(args, flags): """ Allow specified flags to be used in the given context. **Examples** >>> from sympy.polys.polyoptions import allowed_flags >>> from sympy.polys.domains import ZZ >>> allowed_flags({'domain': ZZ}, []) >>> allowed_flags({'domain': ZZ, 'frac': True}, []) Traceback (most recent call last): ... FlagError: 'frac' flag is not allowed in this context >>> allowed_flags({'domain': ZZ, 'frac': True}, ['frac']) """ flags = set(flags) for arg in args.iterkeys(): try: if Options.__options__[arg].is_Flag and not arg in flags: raise FlagError("'%s' flag is not allowed in this context" % arg) except KeyError: raise OptionError("'%s' is not a valid option" % arg) Options._init_dependencies_order()
minrk/sympy
sympy/polys/polyoptions.py
Python
bsd-3-clause
19,349
[ "Gaussian" ]
04c88bd901e56dd7315b1bb6977e37d2d18ecd4dad26f9db7602874e5329d7ad
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import copy import numpy from functools import reduce from pyscf import lib from pyscf import gto from pyscf import scf from pyscf import cc from pyscf import ao2mo from pyscf.cc import ccsd, rccsd, eom_rccsd, rintermediates, gintermediates mol = gto.Mole() mol.atom = [ [8 , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)]] mol.basis = 'cc-pvdz' mol.verbose = 0 mol.spin = 0 mol.build() mf = scf.RHF(mol).run() mycc = rccsd.RCCSD(mf).run() def make_mycc1(): mf1 = copy.copy(mf) no = mol.nelectron // 2 n = mol.nao_nr() nv = n - no mf1.mo_occ = numpy.zeros(mol.nao_nr()) mf1.mo_occ[:no] = 2 numpy.random.seed(12) mf1.mo_coeff = numpy.random.random((n,n)) dm = mf1.make_rdm1(mf1.mo_coeff, mf1.mo_occ) fockao = mf1.get_hcore() + mf1.get_veff(mol, dm) mf1.mo_energy = numpy.einsum('pi,pq,qi->i', mf1.mo_coeff, fockao, mf1.mo_coeff) idx = numpy.hstack([mf1.mo_energy[:no].argsort(), no+mf1.mo_energy[no:].argsort()]) mf1.mo_coeff = mf1.mo_coeff[:,idx] mycc1 = rccsd.RCCSD(mf1) eris1 = mycc1.ao2mo() numpy.random.seed(12) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((no,no,nv,nv)) - .9 r2 = r2 + r2.transpose(1,0,3,2) mycc1.t1 = r1*1e-5 mycc1.t2 = r2*1e-5 return mf1, mycc1, eris1 mf1, mycc1, eris1 = make_mycc1() no, nv = mycc1.t1.shape mycci = copy.copy(mycc1) erisi = copy.copy(eris1) erisi.oooo = eris1.oooo + numpy.sin(eris1.oooo)*1j erisi.oooo = erisi.oooo + erisi.oooo.conj().transpose(1,0,3,2) erisi.ovoo = eris1.ovoo + numpy.sin(eris1.ovoo)*1j erisi.ovvo = eris1.ovvo + numpy.sin(eris1.ovvo)*1j erisi.oovv = eris1.oovv + numpy.sin(eris1.oovv)*1j erisi.oovv = erisi.oovv + erisi.oovv.conj().transpose(1,0,3,2) erisi.ovov = eris1.ovov + numpy.sin(eris1.ovov)*1j erisi.ovvv = eris1.ovvv + numpy.sin(eris1.ovvv)*1j erisi.vvvv = eris1.vvvv + numpy.sin(eris1.vvvv)*1j erisi.vvvv = erisi.vvvv + erisi.vvvv.conj().transpose(1,0,3,2) mycc2 = ccsd.CCSD(mf) mycc21 = ccsd.CCSD(mf1) mycc2.__dict__.update(mycc.__dict__) mycc21.__dict__.update(mycc1.__dict__) eris21 = mycc21.ao2mo() mycc3 = ccsd.CCSD(mf) mycc31 = ccsd.CCSD(mf1) mycc3.__dict__.update(mycc.__dict__) mycc31.__dict__.update(mycc1.__dict__) mycc3 = mycc3.set(max_memory=0, direct=True) mycc31 = mycc31.set(max_memory=0, direct=True) eris31 = mycc31.ao2mo() def tearDownModule(): global mol, mf, mycc, mf1, eris1, mycc1, mycci, erisi, mycc2, mycc21, eris21, mycc3, mycc31, eris31 del mol, mf, mycc, mf1, eris1, mycc1, mycci, erisi, mycc2, mycc21, eris21, mycc3, mycc31, eris31 class KnownValues(unittest.TestCase): def test_ipccsd(self): eom = mycc.eomip_method() e,v = eom.kernel(nroots=1, left=False, koopmans=False) e = eom.eip self.assertAlmostEqual(e, 0.4335604332073799, 6) e,v = mycc.ipccsd(nroots=3) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) myeom = eom_rccsd.EOMIP(mycc) lv = myeom.ipccsd(nroots=3, left=True)[1] e = myeom.ipccsd_star_contract(e, v, lv) self.assertAlmostEqual(e[0], 0.43793202122290747, 6) self.assertAlmostEqual(e[1], 0.52287073076243218, 6) self.assertAlmostEqual(e[2], 0.67994597799835099, 6) def test_ipccsd_koopmans(self): e,v = mycc.ipccsd(nroots=3, koopmans=True) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) e,v = mycc.ipccsd(nroots=3, guess=v[:3]) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) def test_ipccsd_partition(self): e,v = mycc.ipccsd(nroots=3, partition='mp') self.assertAlmostEqual(e[0], 0.42728862799879663, 6) self.assertAlmostEqual(e[1], 0.51359478811505332, 6) self.assertAlmostEqual(e[2], 0.67382901297144682, 6) e,v = mycc.ipccsd(nroots=3, partition='full') self.assertAlmostEqual(e[0], 0.42291981842588938, 6) self.assertAlmostEqual(e[1], 0.50992428154417802, 6) self.assertAlmostEqual(e[2], 0.67006510349161119, 6) e,v = mycc.ipccsd(nroots=3, partition='mp', left=True) self.assertAlmostEqual(e[0], 0.42728862799879663, 6) self.assertAlmostEqual(e[1], 0.51359478811505332, 6) self.assertAlmostEqual(e[2], 0.67382901297144682, 6) e,v = mycc.ipccsd(nroots=3, partition='full', left=True) self.assertAlmostEqual(e[0], 0.42291981842588938, 6) self.assertAlmostEqual(e[1], 0.50992428154417802, 6) self.assertAlmostEqual(e[2], 0.67006510349161119, 6) def test_eaccsd(self): eom = mycc.eomea_method() e,v = eom.kernel(nroots=1, left=False, koopmans=False) e = eom.eea self.assertAlmostEqual(e, 0.16737886338859731, 6) e,v = mycc.eaccsd(nroots=3) self.assertAlmostEqual(e[0], 0.16737886338859731, 6) self.assertAlmostEqual(e[1], 0.24027613852009164, 6) self.assertAlmostEqual(e[2], 0.51006797826488071, 6) myeom = eom_rccsd.EOMEA(mycc) lv = myeom.eaccsd(nroots=3, left=True)[1] e = myeom.eaccsd_star_contract(e, v, lv) self.assertAlmostEqual(e[0], 0.16656250872624662, 6) self.assertAlmostEqual(e[1], 0.2394414445283693, 6) self.assertAlmostEqual(e[2], 0.41399434356202935, 6) def test_eaccsd_koopmans(self): e,v = mycc.eaccsd(nroots=3, koopmans=True) self.assertAlmostEqual(e[0], 0.16737886338859731, 6) self.assertAlmostEqual(e[1], 0.24027613852009164, 6) self.assertAlmostEqual(e[2], 0.73443352557582653, 6) e,v = mycc.eaccsd(nroots=3, guess=v[:3]) self.assertAlmostEqual(e[0], 0.16737886338859731, 6) self.assertAlmostEqual(e[1], 0.24027613852009164, 6) self.assertAlmostEqual(e[2], 0.73443352557582653, 6) def test_eaccsd_partition(self): e,v = mycc.eaccsd(nroots=3, partition='mp') self.assertAlmostEqual(e[0], 0.16947311575051136, 6) self.assertAlmostEqual(e[1], 0.24234326468848749, 6) self.assertAlmostEqual(e[2], 0.7434661346653969 , 6) e,v = mycc.eaccsd(nroots=3, partition='full') self.assertAlmostEqual(e[0], 0.16418276148493574, 6) self.assertAlmostEqual(e[1], 0.23683978491376495, 6) self.assertAlmostEqual(e[2], 0.55640091560545624, 6) e,v = mycc.eaccsd(nroots=3, partition='mp', left=True) self.assertAlmostEqual(e[0], 0.16947311575051136, 6) self.assertAlmostEqual(e[1], 0.24234326468848749, 6) self.assertAlmostEqual(e[2], 0.7434661346653969 , 6) e,v = mycc.eaccsd(nroots=3, partition='full', left=True) self.assertAlmostEqual(e[0], 0.16418276148493574, 6) self.assertAlmostEqual(e[1], 0.23683978491376495, 6) self.assertAlmostEqual(e[2], 0.55640091560545624, 6) def test_eeccsd(self): eom = mycc.eomee_method() e,v = eom.kernel(nroots=1, koopmans=False) e = eom.eee self.assertAlmostEqual(e, 0.2757159395886167, 6) e,v = mycc.eeccsd(nroots=4) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) def test_eeccsd_koopmans(self): e,v = mycc.eeccsd(nroots=4, koopmans=True) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) e,v = mycc.eeccsd(nroots=4, guess=v[:4]) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) def test_eomee_ccsd_singlet(self): e, v = mycc.eomee_ccsd_singlet(nroots=1) self.assertAlmostEqual(e, 0.3005716731825082, 6) def test_eomee_ccsd_triplet(self): e, v = mycc.eomee_ccsd_triplet(nroots=1) self.assertAlmostEqual(e, 0.2757159395886167, 6) def test_eomsf_ccsd(self): e, v = mycc.eomsf_ccsd(nroots=1) self.assertAlmostEqual(e, 0.2757159395886167, 6) def test_vector_to_amplitudes(self): t1, t2 = mycc1.vector_to_amplitudes(mycc1.amplitudes_to_vector(mycc1.t1, mycc1.t2)) self.assertAlmostEqual(abs(mycc1.t1-t1).sum(), 0, 9) self.assertAlmostEqual(abs(mycc1.t2-t2).sum(), 0, 9) def test_eomee_ccsd_matvec_singlet(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((no,no,nv,nv)) - .9 r2 = r2 + r2.transpose(1,0,3,2) myeom = eom_rccsd.EOMEESinglet(mycc1) vec = myeom.amplitudes_to_vector(r1,r2) imds = myeom.make_imds(eris1) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1), -112883.3791497977, 8) self.assertAlmostEqual(lib.finger(r2), -268199.3475813322, 8) def test_eomee_ccsd_matvec_triplet(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((2,no,no,nv,nv)) - .9 r2[0] = r2[0] - r2[0].transpose(0,1,3,2) r2[0] = r2[0] - r2[0].transpose(1,0,2,3) r2[1] = r2[1] - r2[1].transpose(1,0,3,2) myeom = eom_rccsd.EOMEETriplet(mycc1) vec = myeom.amplitudes_to_vector(r1, r2) imds = myeom.make_imds(eris1) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1 ), 3550.5250670914056, 9) self.assertAlmostEqual(lib.finger(r2[0]), -237433.03756895234,8) self.assertAlmostEqual(lib.finger(r2[1]), 127680.0182437716 , 8) def test_eomsf_ccsd_matvec(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((2,no,no,nv,nv)) - .9 myeom = eom_rccsd.EOMEESpinFlip(mycc1) vec = myeom.amplitudes_to_vector(r1,r2) imds = myeom.make_imds(eris1) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1 ), -19368.729268465482, 8) self.assertAlmostEqual(lib.finger(r2[0]), 84325.863680611626 , 8) self.assertAlmostEqual(lib.finger(r2[1]), 6715.9574457836134 , 8) def test_eomee_diag(self): vec1S, vec1T, vec2 = eom_rccsd.EOMEE(mycc1).get_diag() self.assertAlmostEqual(lib.finger(vec1S),-4714.9854130015719, 9) self.assertAlmostEqual(lib.finger(vec1T), 2221.3155272953709, 9) self.assertAlmostEqual(lib.finger(vec2) ,-5486.1611871545592, 9) def test_ip_matvec(self): numpy.random.seed(12) r1 = numpy.random.random((no)) - .9 r2 = numpy.random.random((no,no,nv)) - .9 myeom = eom_rccsd.EOMIP(mycc1) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) myeom.partition = 'mp' self.assertAlmostEqual(lib.finger(r1), 0.37404344676857076, 12) self.assertAlmostEqual(lib.finger(r2), -1.1568913404570922, 12) imds = myeom.make_imds(eris1) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), -14894.669606811192, 9) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 1182.3095479451745, 9) myeom.partition = 'full' imds = myeom.make_imds(eris1) diag = myeom.get_diag(imds) vec1 = myeom.matvec(vec, imds, diag=diag) self.assertAlmostEqual(lib.finger(vec1), -3795.9122245246967, 9) self.assertAlmostEqual(lib.finger(diag), 1106.260154202434, 9) def test_ea_matvec(self): numpy.random.seed(12) r1 = numpy.random.random((nv)) - .9 r2 = numpy.random.random((no,nv,nv)) - .9 myeom = eom_rccsd.EOMEA(mycc1) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) myeom.partition = 'mp' self.assertAlmostEqual(lib.finger(r1), 1.4488291275539353, 12) self.assertAlmostEqual(lib.finger(r2), 0.97080165032287469, 12) imds = myeom.make_imds(eris1) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), -34426.363943760276, 9) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 2724.8239646679217, 9) myeom.partition = 'full' imds = myeom.make_imds(eris1) diag = myeom.get_diag(imds) vec1 = myeom.matvec(vec, imds, diag=diag) self.assertAlmostEqual(lib.finger(vec1), -17030.363405297598, 9) self.assertAlmostEqual(lib.finger(diag), 4688.9122122011922, 9) ######################################## # Complex integrals def test_ip_matvec1(self): numpy.random.seed(12) r1 = numpy.random.random((no))-.9 + numpy.random.random((no))*.2j r2 = (numpy.random.random((no,no,nv))-.9 + numpy.random.random((no,no,nv))*.2j) myeom = eom_rccsd.EOMIP(mycci) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) eris1 imds = myeom.make_imds(erisi) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), 25176.428829164193-4955.5351324520125j, 9) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 1106.2601542024306, 9) def test_ea_matvec1(self): numpy.random.seed(12) r1 = numpy.random.random((nv))-.9 + numpy.random.random((nv))*.2j r2 = (numpy.random.random((no,nv,nv))-.9 + numpy.random.random((no,nv,nv))*.2j) myeom = eom_rccsd.EOMEA(mycci) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) imds = myeom.make_imds(erisi) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), -105083.60825558871+25155.909195554908j, 8) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 4688.9122122011895, 9) ######################################## # With 4-fold symmetry in integrals def test_ipccsd2(self): e,v = mycc2.ipccsd(nroots=1) self.assertAlmostEqual(e, 0.4335604332073799, 6) e,v = mycc2.ipccsd(nroots=3) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) myeom = eom_rccsd.EOMIP(mycc2) lv = myeom.ipccsd(nroots=3, left=True)[1] e = myeom.ipccsd_star_contract(e, v, lv) self.assertAlmostEqual(e[0], 0.43793202122290747, 6) self.assertAlmostEqual(e[1], 0.52287073076243218, 6) self.assertAlmostEqual(e[2], 0.67994597799835099, 6) def test_ipccsd_koopmans2(self): e,v = mycc2.ipccsd(nroots=3, koopmans=True) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) e,v = mycc2.ipccsd(nroots=3, guess=v[:3]) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) def test_ipccsd_partition2(self): e,v = mycc2.ipccsd(nroots=3, partition='mp') self.assertAlmostEqual(e[0], 0.42728862799879663, 6) self.assertAlmostEqual(e[1], 0.51359478811505332, 6) self.assertAlmostEqual(e[2], 0.67382901297144682, 6) e,v = mycc2.ipccsd(nroots=3, partition='full') self.assertAlmostEqual(e[0], 0.42291981842588938, 6) self.assertAlmostEqual(e[1], 0.50992428154417802, 6) self.assertAlmostEqual(e[2], 0.67006510349161119, 6) def test_eaccsd2(self): e,v = mycc2.eaccsd(nroots=1) self.assertAlmostEqual(e, 0.16737886338859731, 6) e,v = mycc2.eaccsd(nroots=3) self.assertAlmostEqual(e[0], 0.16737886338859731, 6) self.assertAlmostEqual(e[1], 0.24027613852009164, 6) self.assertAlmostEqual(e[2], 0.51006797826488071, 6) myeom = eom_rccsd.EOMEA(mycc2) lv = myeom.eaccsd(nroots=3, left=True)[1] e = myeom.eaccsd_star_contract(e, v, lv) self.assertAlmostEqual(e[0], 0.16656250872624662, 6) self.assertAlmostEqual(e[1], 0.2394414445283693, 6) self.assertAlmostEqual(e[2], 0.41399434356202935, 6) def test_eaccsd_koopmans2(self): e,v = mycc2.eaccsd(nroots=3, koopmans=True) self.assertAlmostEqual(e[0], 0.16737886338859731, 6) self.assertAlmostEqual(e[1], 0.24027613852009164, 6) self.assertAlmostEqual(e[2], 0.73443352557582653, 6) e,v = mycc2.eaccsd(nroots=3, guess=v[:3]) self.assertAlmostEqual(e[0], 0.16737886338859731, 6) self.assertAlmostEqual(e[1], 0.24027613852009164, 6) self.assertAlmostEqual(e[2], 0.73443352557582653, 6) def test_eaccsd_partition2(self): e,v = mycc2.eaccsd(nroots=3, partition='mp') self.assertAlmostEqual(e[0], 0.16947311575051136, 6) self.assertAlmostEqual(e[1], 0.24234326468848749, 6) self.assertAlmostEqual(e[2], 0.7434661346653969 , 6) e,v = mycc2.eaccsd(nroots=3, partition='full') self.assertAlmostEqual(e[0], 0.16418276148493574, 6) self.assertAlmostEqual(e[1], 0.23683978491376495, 6) self.assertAlmostEqual(e[2], 0.55640091560545624, 6) def test_eeccsd2(self): e,v = mycc2.eeccsd(nroots=1) self.assertAlmostEqual(e, 0.2757159395886167, 6) e,v = mycc2.eeccsd(nroots=4) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) def test_eeccsd_koopmans2(self): e,v = mycc2.eeccsd(nroots=4, koopmans=True) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) e,v = mycc2.eeccsd(nroots=4, guess=v[:4]) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) def test_eomee_ccsd_matvec_singlet2(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((no,no,nv,nv)) - .9 r2 = r2 + r2.transpose(1,0,3,2) myeom = eom_rccsd.EOMEESinglet(mycc21) vec = myeom.amplitudes_to_vector(r1,r2) imds = myeom.make_imds(eris21) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1), -112883.3791497977, 8) self.assertAlmostEqual(lib.finger(r2), -268199.3475813322, 8) def test_eomee_ccsd_matvec_triplet2(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((2,no,no,nv,nv)) - .9 r2[0] = r2[0] - r2[0].transpose(0,1,3,2) r2[0] = r2[0] - r2[0].transpose(1,0,2,3) r2[1] = r2[1] - r2[1].transpose(1,0,3,2) myeom = eom_rccsd.EOMEETriplet(mycc21) vec = myeom.amplitudes_to_vector(r1, r2) imds = myeom.make_imds(eris21) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1 ), 3550.5250670914056, 9) self.assertAlmostEqual(lib.finger(r2[0]), -237433.03756895234,8) self.assertAlmostEqual(lib.finger(r2[1]), 127680.0182437716 , 8) def test_eomsf_ccsd_matvec2(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((2,no,no,nv,nv)) - .9 myeom = eom_rccsd.EOMEESpinFlip(mycc21) vec = myeom.amplitudes_to_vector(r1,r2) imds = myeom.make_imds(eris21) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1 ), -19368.729268465482, 8) self.assertAlmostEqual(lib.finger(r2[0]), 84325.863680611626 , 8) self.assertAlmostEqual(lib.finger(r2[1]), 6715.9574457836134 , 8) def test_eomee_diag2(self): vec1S, vec1T, vec2 = eom_rccsd.EOMEE(mycc21).get_diag() self.assertAlmostEqual(lib.finger(vec1S),-4714.9854130015719, 9) self.assertAlmostEqual(lib.finger(vec1T), 2221.3155272953709, 9) self.assertAlmostEqual(lib.finger(vec2) ,-5486.1611871545592, 9) def test_ip_matvec2(self): numpy.random.seed(12) r1 = numpy.random.random((no)) - .9 r2 = numpy.random.random((no,no,nv)) - .9 myeom = eom_rccsd.EOMIP(mycc21) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) myeom.partition = 'mp' self.assertAlmostEqual(lib.finger(r1), 0.37404344676857076, 12) self.assertAlmostEqual(lib.finger(r2), -1.1568913404570922, 12) imds = myeom.make_imds(eris21) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), -14894.669606811192, 9) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 1182.3095479451745, 9) myeom.partition = 'full' imds = myeom.make_imds(eris21) diag = myeom.get_diag(imds) vec1 = myeom.matvec(vec, imds, diag=diag) self.assertAlmostEqual(lib.finger(vec1), -3795.9122245246967, 9) self.assertAlmostEqual(lib.finger(diag), 1106.260154202434, 9) def test_ea_matvec2(self): numpy.random.seed(12) r1 = numpy.random.random((nv)) - .9 r2 = numpy.random.random((no,nv,nv)) - .9 myeom = eom_rccsd.EOMEA(mycc21) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) myeom.partition = 'mp' self.assertAlmostEqual(lib.finger(r1), 1.4488291275539353, 12) self.assertAlmostEqual(lib.finger(r2), 0.97080165032287469, 12) imds = myeom.make_imds(eris21) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), -34426.363943760276, 9) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 2724.8239646679217, 9) myeom.partition = 'full' imds = myeom.make_imds(eris21) diag = myeom.get_diag(imds) vec1 = myeom.matvec(vec, imds, diag=diag) self.assertAlmostEqual(lib.finger(vec1), -17030.363405297598, 9) self.assertAlmostEqual(lib.finger(diag), 4688.9122122011922, 9) ######################################## # With 4-fold symmetry in integrals # max_memory = 0 # direct = True def test_ipccsd3(self): e,v = mycc3.ipccsd(nroots=1) self.assertAlmostEqual(e, 0.4335604332073799, 6) e,v = mycc3.ipccsd(nroots=3) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) myeom = eom_rccsd.EOMIP(mycc3) lv = myeom.ipccsd(nroots=3, left=True)[1] e = myeom.ipccsd_star_contract(e, v, lv) self.assertAlmostEqual(e[0], 0.43793202122290747, 6) self.assertAlmostEqual(e[1], 0.52287073076243218, 6) self.assertAlmostEqual(e[2], 0.67994597799835099, 6) def test_ipccsd_koopmans3(self): e,v = mycc3.ipccsd(nroots=3, koopmans=True) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) e,v = mycc3.ipccsd(nroots=3, guess=v[:3]) self.assertAlmostEqual(e[0], 0.4335604332073799, 6) self.assertAlmostEqual(e[1], 0.5187659896045407, 6) self.assertAlmostEqual(e[2], 0.6782876002229172, 6) def test_ipccsd_partition3(self): e,v = mycc3.ipccsd(nroots=3, partition='mp') self.assertAlmostEqual(e[0], 0.42728862799879663, 6) self.assertAlmostEqual(e[1], 0.51359478811505332, 6) self.assertAlmostEqual(e[2], 0.67382901297144682, 6) e,v = mycc3.ipccsd(nroots=3, partition='full') self.assertAlmostEqual(e[0], 0.42291981842588938, 6) self.assertAlmostEqual(e[1], 0.50992428154417802, 6) self.assertAlmostEqual(e[2], 0.67006510349161119, 6) # def test_eaccsd3(self): # e,v = mycc3.eaccsd(nroots=1) # self.assertAlmostEqual(e, 0.16737886338859731, 6) # # e,v = mycc3.eaccsd(nroots=3) # self.assertAlmostEqual(e[0], 0.16737886338859731, 6) # self.assertAlmostEqual(e[1], 0.24027613852009164, 6) # self.assertAlmostEqual(e[2], 0.51006797826488071, 6) # # myeom = eom_rccsd.EOMEA(mycc3) # lv = myeom.eaccsd(nroots=3, left=True)[1] # e = myeom.eaccsd_star_contract(e, v, lv) # self.assertAlmostEqual(e[0], 0.16656250872624662, 6) # self.assertAlmostEqual(e[1], 0.2394414445283693, 6) # self.assertAlmostEqual(e[2], 0.41399434356202935, 6) # # def test_eaccsd_koopmans3(self): # e,v = mycc3.eaccsd(nroots=3, koopmans=True) # self.assertAlmostEqual(e[0], 0.16737886338859731, 6) # self.assertAlmostEqual(e[1], 0.24027613852009164, 6) # self.assertAlmostEqual(e[2], 0.73443352557582653, 6) # # e,v = mycc3.eaccsd(nroots=3, guess=v[:3]) # self.assertAlmostEqual(e[0], 0.16737886338859731, 6) # self.assertAlmostEqual(e[1], 0.24027613852009164, 6) # self.assertAlmostEqual(e[2], 0.73443352557582653, 6) # # def test_eaccsd_partition3(self): # e,v = mycc3.eaccsd(nroots=3, partition='mp') # self.assertAlmostEqual(e[0], 0.16947311575051136, 6) # self.assertAlmostEqual(e[1], 0.24234326468848749, 6) # self.assertAlmostEqual(e[2], 0.7434661346653969 , 6) # # e,v = mycc3.eaccsd(nroots=3, partition='full') # self.assertAlmostEqual(e[0], 0.16418276148493574, 6) # self.assertAlmostEqual(e[1], 0.23683978491376495, 6) # self.assertAlmostEqual(e[2], 0.55640091560545624, 6) def test_eeccsd3(self): e,v = mycc3.eeccsd(nroots=1) self.assertAlmostEqual(e, 0.2757159395886167, 6) e,v = mycc3.eeccsd(nroots=4) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) def test_eeccsd_koopmans3(self): e,v = mycc3.eeccsd(nroots=4, koopmans=True) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) e,v = mycc3.eeccsd(nroots=4, guess=v[:4]) self.assertAlmostEqual(e[0], 0.2757159395886167, 6) self.assertAlmostEqual(e[1], 0.2757159395886167, 6) self.assertAlmostEqual(e[2], 0.2757159395886167, 6) self.assertAlmostEqual(e[3], 0.3005716731825082, 6) def test_eomee_ccsd_matvec_singlet3(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((no,no,nv,nv)) - .9 r2 = r2 + r2.transpose(1,0,3,2) myeom = eom_rccsd.EOMEESinglet(mycc31) vec = myeom.amplitudes_to_vector(r1,r2) imds = myeom.make_imds(eris31) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1), -112883.3791497977, 8) self.assertAlmostEqual(lib.finger(r2), -268199.3475813322, 8) def test_eomee_ccsd_matvec_triplet3(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((2,no,no,nv,nv)) - .9 r2[0] = r2[0] - r2[0].transpose(0,1,3,2) r2[0] = r2[0] - r2[0].transpose(1,0,2,3) r2[1] = r2[1] - r2[1].transpose(1,0,3,2) myeom = eom_rccsd.EOMEETriplet(mycc31) vec = myeom.amplitudes_to_vector(r1, r2) imds = myeom.make_imds(eris31) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1 ), 3550.5250670914056, 9) self.assertAlmostEqual(lib.finger(r2[0]), -237433.03756895234,8) self.assertAlmostEqual(lib.finger(r2[1]), 127680.0182437716 , 8) def test_eomsf_ccsd_matvec3(self): numpy.random.seed(10) r1 = numpy.random.random((no,nv)) - .9 r2 = numpy.random.random((2,no,no,nv,nv)) - .9 myeom = eom_rccsd.EOMEESpinFlip(mycc31) vec = myeom.amplitudes_to_vector(r1,r2) imds = myeom.make_imds(eris31) vec1 = myeom.matvec(vec, imds) r1, r2 = myeom.vector_to_amplitudes(vec1) self.assertAlmostEqual(lib.finger(r1 ), -19368.729268465482, 8) self.assertAlmostEqual(lib.finger(r2[0]), 84325.863680611626 , 8) self.assertAlmostEqual(lib.finger(r2[1]), 6715.9574457836134 , 8) def test_eomee_diag3(self): vec1S, vec1T, vec2 = eom_rccsd.EOMEE(mycc31).get_diag() self.assertAlmostEqual(lib.finger(vec1S),-2881.6804563818432, 9) self.assertAlmostEqual(lib.finger(vec1T), 2039.7385969969259, 9) self.assertAlmostEqual(lib.finger(vec2) ,-4271.6230465236358, 9) def test_ip_matvec3(self): numpy.random.seed(12) r1 = numpy.random.random((no)) - .9 r2 = numpy.random.random((no,no,nv)) - .9 myeom = eom_rccsd.EOMIP(mycc31) vec = myeom.amplitudes_to_vector(r1,r2) r1,r2 = myeom.vector_to_amplitudes(vec) myeom.partition = 'mp' self.assertAlmostEqual(lib.finger(r1), 0.37404344676857076, 12) self.assertAlmostEqual(lib.finger(r2), -1.1568913404570922, 12) imds = myeom.make_imds(eris31) vec1 = myeom.matvec(vec, imds) self.assertAlmostEqual(lib.finger(vec1), -14894.669606811192, 9) self.assertAlmostEqual(lib.finger(myeom.get_diag()), 1182.3095479451745, 9) myeom.partition = 'full' imds = myeom.make_imds(eris31) diag = myeom.get_diag(imds) vec1 = myeom.matvec(vec, imds, diag=diag) self.assertAlmostEqual(lib.finger(vec1), -3795.9122245246967, 9) self.assertAlmostEqual(lib.finger(diag), 1106.260154202434, 9) def test_sort_left_right_eigensystem(self): myeom = eom_rccsd.EOMIP(mycc) right_evecs = [numpy.ones(10)] * 4 left_evecs = [numpy.ones(10)] * 5 right_evecs = [x*i for i, x in enumerate(right_evecs)] left_evecs = [x*i for i, x in enumerate(left_evecs)] revals, revecs, levecs = eom_rccsd._sort_left_right_eigensystem( myeom, [True, False, True, True], [-1.1, 0, 1.1, 2.2], right_evecs, [True, True, True, False, True], [-2.2, -1.1, 0, 1.1, 2.2], left_evecs) self.assertEqual(revals[0], -1.1) self.assertEqual(revals[1], 2.2) self.assertEqual(revecs[0][0], 0) self.assertEqual(revecs[1][0], 3) self.assertEqual(levecs[0][0], 1) self.assertEqual(levecs[1][0], 4) revals, revecs, levecs = eom_rccsd._sort_left_right_eigensystem( myeom, [True, False, True, True], [-1.1, 0, 1.1, 2.2], right_evecs, [True, True, False, True, True], [-2.2, -1.1, 0, 1.1, 2.2], left_evecs) self.assertEqual(revals[0], -1.1) self.assertEqual(revals[1], 1.1) self.assertEqual(revals[2], 2.2) self.assertEqual(revecs[0][0], 0) self.assertEqual(revecs[1][0], 2) self.assertEqual(revecs[2][0], 3) self.assertEqual(levecs[0][0], 1) self.assertEqual(levecs[1][0], 3) self.assertEqual(levecs[2][0], 4) # def test_ea_matvec3(self): # numpy.random.seed(12) # r1 = numpy.random.random((nv)) - .9 # r2 = numpy.random.random((no,nv,nv)) - .9 # myeom = eom_rccsd.EOMEA(mycc31) # vec = myeom.amplitudes_to_vector(r1,r2) # r1,r2 = myeom.vector_to_amplitudes(vec) # myeom.partition = 'mp' # self.assertAlmostEqual(lib.finger(r1), 1.4488291275539353, 12) # self.assertAlmostEqual(lib.finger(r2), 0.97080165032287469, 12) # imds = myeom.make_imds(eris31) # vec1 = myeom.matvec(vec, imds) # self.assertAlmostEqual(lib.finger(vec1), -34426.363943760276, 9) # self.assertAlmostEqual(lib.finger(myeom.get_diag()), 2724.8239646679217, 9) # # myeom.partition = 'full' # imds = myeom.make_imds(eris31) # diag = myeom.get_diag(imds) # vec1 = myeom.matvec(vec, imds, diag=diag) # self.assertAlmostEqual(lib.finger(vec1), -17030.363405297598, 9) # self.assertAlmostEqual(lib.finger(diag), 4688.9122122011922, 9) def test_t3p2_intermediates_complex(self): '''Although this has not been tested strictly for complex values, it was written to be correct for complex values and differences in the complex values between versions should be taken into account and corrected.''' myt1 = mycc1.t1 + 1j * numpy.sin(mycc1.t1) * mycc1.t1 myt2 = mycc1.t2 + 1j * numpy.sin(mycc1.t2) * mycc1.t2 myt2 = myt2 + myt2.transpose(1,0,3,2) e, pt1, pt2, Wmcik, Wacek = rintermediates.get_t3p2_imds_slow(mycc1, myt1, myt2, eris=erisi) self.assertAlmostEqual(lib.finger(e), 23223.465490572264, 6) self.assertAlmostEqual(lib.finger(pt1), (-5.2202836452466705-0.09570164571057749j), 6) self.assertAlmostEqual(lib.finger(pt2), (46.188012063609506-1.303867687778909j), 6) self.assertAlmostEqual(lib.finger(Wmcik), (-18.438930654297778+1.5734161307568773j), 6) self.assertAlmostEqual(lib.finger(Wacek), (-7.187576764072701+0.7399185332889747j), 6) def test_t3p2_intermediates_real(self): myt1 = mycc1.t1.copy() myt2 = mycc1.t2.copy() myt2 = myt2 + myt2.transpose(1,0,3,2) e, pt1, pt2, Wmcik, Wacek = rintermediates.get_t3p2_imds_slow(mycc1, myt1, myt2) self.assertAlmostEqual(lib.finger(e), 23230.479350851536, 6) self.assertAlmostEqual(lib.finger(pt1), -5.218888542335442, 6) self.assertAlmostEqual(lib.finger(pt2), 46.19512409958347, 6) self.assertAlmostEqual(lib.finger(Wmcik), -18.47928005593598, 6) self.assertAlmostEqual(lib.finger(Wacek), -7.101360230151883, 6) def test_t3p2_intermediates_against_so(self): from pyscf.cc.addons import convert_to_gccsd myt1 = mycc1.t1.copy() myt2 = mycc1.t2.copy() e, pt1, pt2, Wmcik, Wacek = rintermediates.get_t3p2_imds_slow(mycc1, myt1, myt2) mygcc = convert_to_gccsd(mycc1) mygt1 = mygcc.t1.copy() mygt2 = mygcc.t2.copy() ge, gpt1, gpt2, gWmcik, gWacek = gintermediates.get_t3p2_imds_slow(mygcc, mygt1, mygt2) self.assertAlmostEqual(lib.finger(pt1), -2.6094405706617727, 6) self.assertAlmostEqual(lib.finger(pt2), 23.097562049844235, 6) self.assertAlmostEqual(lib.finger(pt1), lib.finger(gpt1[::2,::2]), 6) self.assertAlmostEqual(lib.finger(pt2), lib.finger(gpt2[::2,1::2,::2,1::2]), 6) def test_h2o_star(self): mol_h2o = gto.Mole() mol_h2o.atom = [ [8, [0.000000000000000, -0.000000000000000, -0.124143731294022]], [1, [0.000000000000000, -1.430522735894536, 0.985125550040314]], [1, [0.000000000000000, 1.430522735894536, 0.985125550040314]]] mol_h2o.unit = 'B' mol_h2o.basis = {'H' : [[0, [5.4471780, 0.156285], [0.8245472, 0.904691]], [0, [0.1831916, 1.0]]], 'O' : '3-21G'} mol_h2o.verbose = 7 mol_h2o.output = '/dev/null' mol_h2o.build() mol.conv_tol = 1e-12 mf_h2o = scf.RHF(mol_h2o) mf_h2o.conv_tol_grad = 1e-12 mf_h2o.kernel() mycc_h2o = cc.RCCSD(mf_h2o).run() mycc_h2o.conv_tol_normt = 1e-12 mycc_h2o.conv_tol = 1e-12 mycc_h2o.kernel() myeom = eom_rccsd.EOMIP(mycc_h2o) e = myeom.ipccsd_star(nroots=3) self.assertAlmostEqual(e[0], 0.410661965883, 6) myeom = eom_rccsd.EOMIP_Ta(mycc_h2o) e = myeom.ipccsd_star(nroots=3) self.assertAlmostEqual(e[0], 0.411695647736, 6) myeom = eom_rccsd.EOMEA(mycc_h2o) e = myeom.eaccsd_star(nroots=3) self.assertAlmostEqual(e[0], 0.250589854185, 6) myeom = eom_rccsd.EOMEA_Ta(mycc_h2o) e = myeom.eaccsd_star(nroots=3) self.assertAlmostEqual(e[0], 0.250720295150, 6) if __name__ == "__main__": print("Tests for EOM RCCSD") unittest.main()
gkc1000/pyscf
pyscf/cc/test/test_eom_rccsd.py
Python
apache-2.0
38,148
[ "PySCF" ]
c1ee19a3a21f58ca391c26487d9185c294c08539af37e908388c12276c4a940e
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- http://www.mdanalysis.org # Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under the GNU Public Licence, v2 or any higher version # # Please cite your use of MDAnalysis in published work: # # R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler, # D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein. # MDAnalysis: A Python package for the rapid analysis of molecular dynamics # simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th # Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy. # # N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein. # MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # """\ ========================================================================= Reading trajectories from memory --- :mod:`MDAnalysis.coordinates.memory` ========================================================================= :Author: Wouter Boomsma :Year: 2016 :Copyright: GNU Public License v2 :Maintainer: Wouter Boomsma <wb@di.ku.dk>, wouterboomsma on github .. versionadded:: 0.16.0 The module contains a trajectory reader that operates on an array in memory, rather than reading from file. This makes it possible to use operate on raw coordinate using existing MDAnalysis tools. In addition, it allows the user to make changes to the coordinates in a trajectory (e.g. through :attr:`MDAnalysis.core.groups.AtomGroup.positions`) without having to write the entire state to file. How to use the :class:`MemoryReader` ==================================== The :class:`MemoryReader` can be used to either directly generate a trajectory as a numpy array or by transferring an existing trajectory to memory. In-memory representation of arbitrary trajectories ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If sufficient memory is available to hold a whole trajectory in memory then analysis can be sped up substantially by transferring the trajectory to memory. The most straightforward use of the :class:`MemoryReader` is to simply use the ``in_memory=True`` flag for the :class:`~MDAnalysis.core.universe.Universe` class, which automatically transfers a trajectory to memory:: import MDAnalysis as mda from MDAnalysisTests.datafiles import TPR, XTC universe = mda.Universe(TPR, XTC, in_memory=True) Of course, sufficient memory has to be available to hold the whole trajectory. Switching a trajectory to an in-memory representation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The decision to transfer the trajectory to memory can be made at any time with the :meth:`~MDAnalysis.core.universe.Universe.transfer_to_memory` method of a :class:`~MDAnalysis.core.universe.Universe`:: universe = mda.Universe(TPR, XTC) universe.transfer_to_memory() This operation may take a while (with `verbose=True` a progress bar is displayed) but then subsequent operations on the trajectory directly operate on the in-memory array and will be very fast. Constructing a Reader from a numpy array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The :class:`MemoryReader` provides great flexibility because it becomes possible to create a :class:`~MDAnalysis.core.universe.Universe` directly from a numpy array. A simple example consists of a new universe created from the array extracted from a DCD :meth:`~MDAnalysis.coordinates.DCD.DCDReader.timeseries`:: import MDAnalysis as mda from MDAnalysisTests.datafiles import DCD, PSF from MDAnalysis.coordinates.memory import MemoryReader universe = mda.Universe(PSF, DCD) coordinates = universe.trajectory.timeseries(universe.atoms) universe2 = mda.Universe(PSF, coordinates, format=MemoryReader, order='afc') .. rubric:: Creating an in-memory trajectory with :func:`~MDAnalysis.analysis.base.AnalysisFromFunction` The :meth:`~MDAnalysis.coordinates.DCD.DCDReader.timeseries` is currently only implemented for the :class:`~MDAnalysis.coordinates.DCD.DCDReader`. However, the :func:`MDAnalysis.analysis.base.AnalysisFromFunction` can provide the same functionality for any supported trajectory format:: import MDAnalysis as mda from MDAnalysis.tests.datafiles import PDB, XTC from MDAnalysis.coordinates.memory import MemoryReader from MDAnalysis.analysis.base import AnalysisFromFunction u = mda.Universe(PDB, XTC) coordinates = AnalysisFromFunction(lambda ag: ag.positions.copy(), u.atoms).run().results u2 = mda.Universe(PDB, coordinates, format=MemoryReader) .. _creating-in-memory-trajectory-label: Creating an in-memory trajectory of a sub-system ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Creating a trajectory for just a selection of an existing trajectory requires the transfer of the appropriate coordinates as well as creation of a topology of the sub-system. For the latter one can use the :func:`~MDAnalysis.core.universe.Merge` function, for the former the :meth:`~MDAnalysis.core.universe.Universe.load_new` method of a :class:`~MDAnalysis.core.universe.Universe` together with the :class:`MemoryReader`. In the following, an in-memory trajectory of only the protein is created:: import MDAnalysis as mda from MDAnalysis.tests.datafiles import PDB, XTC from MDAnalysis.coordinates.memory import MemoryReader from MDAnalysis.analysis.base import AnalysisFromFunction u = mda.Universe(PDB, XTC) protein = u.select_atoms("protein") coordinates = AnalysisFromFunction(lambda ag: ag.positions.copy(), protein).run().results u2 = mda.Merge(protein) # create the protein-only Universe u2.load_new(coordinates, format=MemoryReader) The protein coordinates are extracted into ``coordinates`` and then the in-memory trajectory is loaded from these coordinates. In principle, this could have all be done in one line:: u2 = mda.Merge(protein).load_new( AnalysisFromFunction(lambda ag: ag.positions.copy(), protein).run().results, format=MemoryReader) The new :class:`~MDAnalysis.core.universe.Universe` ``u2`` can be used to, for instance, write out a new trajectory or perform fast analysis on the sub-system. Classes ======= .. autoclass:: Timestep :members: :inherited-members: .. autoclass:: MemoryReader :members: :inherited-members: """ import logging import errno import numpy as np from . import base class Timestep(base.Timestep): """ Timestep for the :class:`MemoryReader` Overrides the positions property in :class:`MDAnalysis.coordinates.base.Timestep` to use avoid duplication of the array. """ @property def positions(self): return base.Timestep.positions.fget(self) @positions.setter def positions(self, new): self.has_positions = True # Use reference to original rather than a copy self._pos = new class MemoryReader(base.ProtoReader): """ MemoryReader works with trajectories represented as numpy arrays. A trajectory reader interface to a numpy array of the coordinates. For compatibility with the timeseries interface, support is provided for specifying the order of columns through the format option. """ format = 'MEMORY' _Timestep = Timestep def __init__(self, coordinate_array, order='fac', dimensions=None, dt=1, filename=None, **kwargs): """ Parameters ---------- coordinate_array : :class:`~numpy.ndarray` object The underlying array of coordinates order : str, optional the order/shape of the return data array, corresponding to (a)tom, (f)rame, (c)oordinates all six combinations of 'a', 'f', 'c' are allowed ie "fac" - return array where the shape is (frame, number of atoms, coordinates) dimensions: (*A*, *B*, *C*, *alpha*, *beta*, *gamma*), optional unitcell dimensions (*A*, *B*, *C*, *alpha*, *beta*, *gamma*) lengths *A*, *B*, *C* are in the MDAnalysis length unit (Å), and angles are in degrees. dt: float, optional The time difference between frames (ps). If :attr:`time` is set, then `dt` will be ignored. filename: string, optional The name of the file from which this instance is created. Set to None when created from an array """ super(MemoryReader, self).__init__() self.filename = filename self.stored_order = order self.set_array(np.asarray(coordinate_array), order) self.n_frames = \ self.coordinate_array.shape[self.stored_order.find('f')] self.n_atoms = \ self.coordinate_array.shape[self.stored_order.find('a')] provided_n_atoms = kwargs.pop("n_atoms", None) if (provided_n_atoms is not None and provided_n_atoms != self.n_atoms): raise ValueError("The provided value for n_atoms ({}) " "does not match the shape of the coordinate " "array ({})" .format(provided_n_atoms, self.n_atoms)) self.ts = self._Timestep(self.n_atoms, **kwargs) self.ts.dt = dt if dimensions is not None: self.ts.dimensions = dimensions self.ts.frame = -1 self.ts.time = -1 self._read_next_timestep() def set_array(self, coordinate_array, order='fac'): """ Set underlying array in desired column order. Parameters ---------- coordinate_array : :class:`~numpy.ndarray` object The underlying array of coordinates order The order/shape of the return data array, corresponding to (a)tom, (f)rame, (c)oordinates all six combinations of 'a', 'f', 'c' are allowed ie "fac" - return array where the shape is (frame, number of atoms, coordinates) """ # Only make copy if not already in float32 format self.coordinate_array = coordinate_array.astype('float32', copy=False) self.stored_format = order def get_array(self): """ Return underlying array. """ return self.coordinate_array def _reopen(self): """Reset iteration to first frame""" self.ts.frame = -1 self.ts.time = -1 def timeseries(self, asel=None, start=0, stop=-1, step=1, format='afc'): """Return a subset of coordinate data for an AtomGroup in desired column order/format. If no selection is given, it will return a view of the underlying array, while a copy is returned otherwise. Parameters --------- asel : :class:`~MDAnalysis.core.groups.AtomGroup` object Atom selection. Defaults to None, in which case the full set of coordinate data is returned. Note that in this case, a view of the underlying numpy array is returned, while a copy of the data is returned whenever asel is different from None. start, stop, skip : int range of trajectory to access, start and stop are inclusive format : str the order/shape of the return data array, corresponding to (a)tom, (f)rame, (c)oordinates all six combinations of 'a', 'f', 'c' are allowed ie "fac" - return array where the shape is (frame, number of atoms, coordinates). """ # The "format" name is used for compliance with DCD.timeseries # Renaming it to order here for internal consistency in this class order = format array = self.get_array() if order == self.stored_order: pass elif order[0] == self.stored_order[0]: array = np.swapaxes(array, 1, 2) elif order[1] == self.stored_order[1]: array = np.swapaxes(array, 0, 2) elif order[2] == self.stored_order[2]: array = np.swapaxes(array, 0, 1) elif order[0] == self.stored_order[1]: array = np.swapaxes(array, 1, 0) array = np.swapaxes(array, 1, 2) elif order[0] == self.stored_order[2]: array = np.swapaxes(array, 2, 0) array = np.swapaxes(array, 1, 2) a_index = order.find('a') f_index = order.find('f') stop_index = stop+1 if stop_index == 0: stop_index = None basic_slice = ([slice(None)] * f_index + [slice(start, stop_index, step)] + [slice(None)] * (2-f_index)) # Return a view if either: # 1) asel is None # 2) asel corresponds to the selection of all atoms. array = array[basic_slice] if (asel is None or asel is asel.universe.atoms): return array else: # If selection is specified, return a copy return array.take(asel.indices, a_index) def _read_next_timestep(self, ts=None): """copy next frame into timestep""" if self.ts.frame >= self.n_frames-1: raise IOError(errno.EIO, 'trying to go over trajectory limit') if ts is None: ts = self.ts ts.frame += 1 f_index = self.stored_order.find('f') basic_slice = ([slice(None)]*(f_index) + [self.ts.frame] + [slice(None)]*(2-f_index)) ts.positions = self.coordinate_array[basic_slice] ts.time = self.ts.frame*self.dt return ts def _read_frame(self, i): """read frame i""" # Frame number is incremented to zero by _read_next_timestep() self.ts.frame = i - 1 return self._read_next_timestep() def __repr__(self): """String representation""" return ("<{cls} with {nframes} frames of {natoms} atoms>" "".format( cls=self.__class__.__name__, nframes=self.n_frames, natoms=self.n_atoms ))
alejob/mdanalysis
package/MDAnalysis/coordinates/memory.py
Python
gpl-2.0
14,502
[ "MDAnalysis" ]
2e1d6406e0f47fe9fe525a07aa7b0e004a931f125a06764b9d13c63812957838
""" This OVITO script exports the dislocation lines extracted by the DXA analysis modifier to a file. You should run this script from within the graphical user interface using the Scripting->Run Script File menu option. """ from ovito import * from ovito.data import * def export_dislocations(disloc_network): print("%i dislocation segments" % len(network.segments)) for segment in network.segments: print("Segment %i: length=%f, Burgers vector=%s" % (segment.id, segment.length, segment.true_burgers_vector)) print(segment.points) # Loop over all objects in the scene and # find one that contains dislocation data. # Then call export_dislocations(). for i in range(len(dataset.scene_nodes)): node = dataset.scene_nodes[i] data = node.compute() if hasattr(data, 'dislocations'): export_dislocations(data.dislocations) break
srinath-chakravarthy/ovito
examples/scripts/export_dislocations.py
Python
gpl-3.0
914
[ "OVITO" ]
9ec00e28cccc53cb14ec8a6e3acf14952a8e20fa5e7df217c2c6f8759c32c30a
#!/usr/bin/python2.7 # encoding: utf-8 #Libs import from __future__ import division import numpy as np import sys from utide import solve, reconstruct #TR comment: 2 alternatives #import netCDF4 as nc from scipy.io import netcdf from scipy.io import savemat from scipy.io import loadmat from pydap.client import open_url import cPickle as pkl import copy #Add local path to utilities sys.path.append('../utilities/') #Utility import from shortest_element_path import shortest_element_path from object_from_dict import ObjectFromDict #Local import from variablesFvcom import _load_var, _load_grid from functionsFvcom import * from functionsFvcomThreeD import * from plotsFvcom import * class FVCOM: ''' Description: ---------- A class/structure for FVCOM data. Functionality structured as follows: _Data. = raw netcdf file data |_Variables. = fvcom variables and quantities |_Grid. = fvcom grid data |_History = Quality Control metadata FVCOM._|_Utils2D. = set of useful functions and methods for 2D and 3D runs |_Utils3D. = set of useful functions and methods for 3D runs |_Plots. = plotting functions |_Save_as = "save as" methods Inputs: ------ - filename = path to file, string, ex: testFvcom=FVCOM('./path_to_FVOM_output_file/filename'). Note that the file can be a pickle file (i.e. *.p) or a netcdf file (i.e. *.nc). Additionally, either a file path or a OpenDap url could be used. Options: ------- - ax = defines for a specific spatial region to work with, as such: ax = [minimun longitude, maximun longitude, minimun latitude, maximum latitude] or use one of the following pre-defined region: ax = 'GP', 'PP', 'DG' or 'MP' Note that this option permits to extract partial data from the overall file and therefore reduce memory and cpu use. - tx = defines for a specific temporal period to work with, as such: tx = ['2012-11-07T12:00:00','2012.11.09T12:00:00'], string of 'yyyy-mm-ddThh:mm:ss'. Note that this option permits to extract partial data from the overall file and therefore reduce memory and cpu use. Notes: ----- Throughout the package, the following conventions apply: - Date = string of 'yyyy-mm-ddThh:mm:ss' - Coordinates = decimal degrees East and North - Directions = in degrees, between -180 and 180 deg., i.e. 0=East, 90=North, +/-180=West, -90=South - Depth = 0m is the free surface and depth is negative ''' def __init__(self, filename, ax=[], tx=[], debug=False): ''' Initialize FVCOM class.''' self._debug = debug if debug: print '-Debug mode on-' #Loading pickle file if filename.endswith('.p'): f = open(filename, "rb") data = pkl.load(f) self._origin_file = data['Origin'] self.History = data['History'] if debug: print "Turn keys into attributs" self.Grid = ObjectFromDict(data['Grid']) self.Variables = ObjectFromDict(data['Variables']) try: if self._origin_file.startswith('http'): #Look for file through OpenDAP server print "Retrieving data through OpenDap server..." self.Data = open_url(data['Origin']) #Create fake attribut to be consistent with the rest of the code self.Data.variables = self.Data else: #WB_Alternative: self.Data = sio.netcdf.netcdf_file(filename, 'r') #WB_comments: scipy has causes some errors, and even though can be # faster, can be unreliable #self.Data = nc.Dataset(data['Origin'], 'r') self.Data = netcdf.netcdf_file(data['Origin'], 'r',mmap=True) except: #TR: need to precise the type of error here print "the original *.nc file has not been found" pass #Loading netcdf file elif filename.endswith('.nc'): if filename.startswith('http'): #Look for file through OpenDAP server print "Retrieving data through OpenDap server..." self.Data = open_url(filename) #Create fake attribut to be consistent with the rest of the code self.Data.variables = self.Data else: #Look for file locally print "Retrieving data from " + filename + " ..." #WB_Alternative: self.Data = sio.netcdf.netcdf_file(filename, 'r') #WB_comments: scipy has causes some errors, and even though can be # faster, can be unreliable #self.Data = nc.Dataset(filename, 'r') self.Data = netcdf.netcdf_file(filename, 'r',mmap=True) text = 'Created from ' + filename self._origin_file = filename #Metadata self.History = [text] # Calling sub-class print "Initialisation..." #print "This might take some time..." try: self.Grid = _load_grid(self.Data, ax, self.History, debug=self._debug) self.Variables = _load_var(self.Data, self.Grid, tx, self.History, debug=self._debug) except MemoryError: print '---Data too large for machine memory---' print 'Tip: use ax or tx during class initialisation' print '--- to use partial data' raise elif filename.endswith('.mat'): print "---Functionality not yet implemented---" sys.exit() else: print "---Wrong file format---" sys.exit() self.Plots = PlotsFvcom(self.Variables, self.Grid, self._debug) self.Util2D = FunctionsFvcom(self.Variables, self.Grid, self.Plots, self.History, self._debug) if self.Variables._3D: self.Util3D = FunctionsFvcomThreeD(self.Variables, self.Grid, self.Plots, self.Util2D, self.History, self._debug) self.Plots.vertical_slice = self.Util3D._vertical_slice #Special methods def __add__(self, FvcomClass, debug=False): """ This special method permits to stack variables of 2 FVCOM objects through a simple addition: fvcom1 += fvcom2 Notes: ----- - fvcom1 and fvcom2 have to cover the exact same spatial domain - last time step of fvcom1 must be <= to the first time step of fvcom2 """ debug = debug or self._debug #Define bounding box if debug: print "Computing bounding box..." if self.Grid._ax == []: lon = self.Grid.lon[:] lat = self.Grid.lat[:] self.Grid._ax = [lon.min(), lon.max(), lat.min(), lat.max()] if FvcomClass.Grid._ax == []: lon = FvcomClass.Grid.lon[:] lat = FvcomClass.Grid.lat[:] FvcomClass.Grid._ax = [lon.min(), lon.max(), lat.min(), lat.max()] #series of test before stacking if not (self.Grid._ax == FvcomClass.Grid._ax): print "---Spatial regions do not match---" sys.exit() elif not ((self.Grid.nele == FvcomClass.Grid.nele) and (self.Grid.nnode == FvcomClass.Grid.nnode) and (self.Variables._3D == FvcomClass.Variables._3D)): print "---Data dimensions do not match---" sys.exit() else: if not (self.Variables.julianTime[-1]<= FvcomClass.Variables.julianTime[0]): print "---Data not consecutive in time---" sys.exit() #Copy self to newself newself = copy.copy(self) #TR comment: it still points toward self and modifies it # so cannot do fvcom3 = fvcom1 + fvcom2 if debug: print 'Stacking variables...' #keyword list for hstack kwl=['matlabTime', 'julianTime'] for key in kwl: tmpN = getattr(newself.Variables, key) tmpO = getattr(FvcomClass.Variables, key) setattr(newself.Variables, key, np.hstack((tmpN[:], tmpO[:]))) #keyword list for vstack kwl=['u', 'v', 'w', 'ua', 'va', 'el', 'tke', 'gls'] for key in kwl: try: tmpN = getattr(newself.Variables, key) tmpO = getattr(FvcomClass.Variables, key) setattr(newself.Variables, key, np.vstack((tmpN[:], tmpO[:]))) except AttributeError: continue #New time dimension newself.Grid.ntime = newself.Grid.ntime + FvcomClass.Grid.ntime #Append to new object history text = 'Data from ' + FvcomClass.History[0].split('/')[-1] \ + ' has been stacked' newself.History.append(text) return newself #Methods def Save_as(self, filename, fileformat='pickle', debug=False): """ This method saves the current FVCOM structure as: - *.p, i.e. python file - *.mat, i.e. Matlab file Inputs: ------ - filename = path + name of the file to be saved, string Keywords: -------- - fileformat = format of the file to be saved, i.e. 'pickle' or 'matlab' """ debug = debug or self._debug if debug: print 'Saving file...' #Define bounding box if debug: print "Computing bounding box..." if self.Grid._ax == []: lon = self.Grid.lon[:] lat = self.Grid.lat[:] self.Grid._ax = [lon.min(), lon.max(), lat.min(), lat.max()] #Save as different formats if fileformat=='pickle': filename = filename + ".p" f = open(filename, "wb") data = {} data['Origin'] = self._origin_file data['History'] = self.History data['Grid'] = self.Grid.__dict__ data['Variables'] = self.Variables.__dict__ #TR: Force caching Variables otherwise error during loading # with 'netcdf4.Variable' type (see above) for key in data['Variables']: listkeys=['Variable', 'ArrayProxy', 'BaseType'] if any([type(data['Variables'][key]).__name__==x for x in listkeys]): if debug: print "Force caching for " + key data['Variables'][key] = data['Variables'][key][:] #Unpickleable objects data['Grid'].pop("triangle", None) #TR: Force caching Variables otherwise error during loading # with 'netcdf4.Variable' type (see above) for key in data['Grid']: listkeys=['Variable', 'ArrayProxy', 'BaseType'] if any([type(data['Grid'][key]).__name__==x for x in listkeys]): if debug: print "Force caching for " + key data['Grid'][key] = data['Grid'][key][:] #Save in pickle file if debug: print 'Dumping in pickle file...' try: pkl.dump(data, f, protocol=pkl.HIGHEST_PROTOCOL) except SystemError: try: print "---Very large data, this may take a while---" pkl.dump(data, f) except SystemError: print "---Data too large for machine memory---" print "Tip: use ax or tx during class initialisation" print "--- to use partial data" sys.exit() f.close() elif fileformat=='matlab': filename = filename + ".mat" #TR comment: based on MitchellO'Flaherty-Sproul's code dtype = float data = {} Grd = {} Var = {} data['Origin'] = self._origin_file data['History'] = self.History Grd = self.Grid.__dict__ Var = self.Variables.__dict__ #TR: Force caching Variables otherwise error during loading # with 'netcdf4.Variable' type (see above) for key in Var: listkeys=['Variable', 'ArrayProxy', 'BaseType'] if any([type(Var[key]).__name__==x for x in listkeys]): if debug: print "Force caching for " + key Var[key] = Var[key][:] #keyV = key + '-var' #data[keyV] = Var[key] data[key] = Var[key] #Unpickleable objects Grd.pop("triangle", None) for key in Grd: listkeys=['Variable', 'ArrayProxy', 'BaseType'] if any([type(Grd[key]).__name__==x for x in listkeys]): if debug: print "Force caching for " + key Grd[key] = Grd[key][:] #keyG = key + '-grd' #data[keyG] = Grd[key] data[key] = Grd[key] #Save in mat file file if debug: print 'Dumping in matlab file...' savemat(filename, data, oned_as='column') else: print "---Wrong file format---" #Test section when running in shell >> python fvcomClass.py #if __name__ == '__main__': #filename = './test_file/dn_coarse_0001.nc' #test = FVCOM(filename) #test.harmonics(0, cnstit='auto', notrend=True, nodiagn=True) #WB_COMMENTS: fixed matlabttime to matlabtime #test.reconstr(test.Variables.matlabTime)
rsignell-usgs/PySeidon
pyseidon/fvcomClass/fvcomClass.py
Python
agpl-3.0
15,044
[ "NetCDF" ]
7737a189d7956a9005037fe6ba155879612ddab4154e2348a7cf9e34b2c5c266
""" Copyright (c) 2015 Andreea Georgescu Created on Wed Nov 19 00:18:55 2014 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. 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/>. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from interp import interp1d from globalfnc import ConfidenceLevel, chi_squared1 pi = np.pi name = "PICO_500" modulated = False energy_resolution_type = "Dirac" # actually Bubble Nucleation, but similar enough to implement like Dirac def EnergyResolution(e): return 0.5 * np.ones_like(e) FFSD = 'GaussianFFSD' FFSI = 'HelmFF' FF = {'SI': FFSI, 'SDPS': FFSD, 'SDAV': FFSD, } target_nuclide_AZC_list = np.array([[19, 9, 0.80]]) target_nuclide_JSpSn_list = \ np.array([[1./2, 0.4751 * np.sqrt(3./2 / pi), -0.0087 * np.sqrt(3./2 / pi)]]) target_nuclide_mass_list = np.array([17.6969]) num_target_nuclides = target_nuclide_mass_list.size def QuenchingFactor(e): return np.ones_like(e) Ethreshold = 6. Emaximum = 100 ERmaximum = np.inf def Efficiency_ER(er): return np.ones_like(er) alpha = 5. def Efficiency(e, er): if er > Ethreshold: return 1. else: return 0. Exposure = 250. * 2.0 * 365.24 ERecoilList = np.array([])
SamWitte/Codds_DarkMatter
src/Data/PICO_500.py
Python
gpl-2.0
1,807
[ "DIRAC" ]
98fa228e9cbc3ec296540cc4c1243fbc931aa0dc8a26b45c6f0ab36b0571b66d
# Author: Samuel Genheden samuel.genheden@gmail.com """ Routines to parse files and streams """ import fileinput import re import numpy as np from units import * def stdin2ndarray() : """ Parse columns and rows of data from standard input into a numpy.ndarray """ data = [] for line in fileinput.input() : if line[0] not in ["#","@"] : data.append(line.strip().split()) return np.array(data,dtype=float) def parse2ndarray(filename): """ Parse columns and rows of data from a file into a numpy.ndarray Treats lines starting with # and @ as comments """ data = [] with open(filename,"r") as f : data = [line.strip().split() for line in f.readlines() if line[0] not in ["#","@"] ] # Check for missing data at the end due to error cols0 = len(data[0]) data = [line for line in data if len(line) == cols0] return np.array(data,dtype=float) def parse_densityfile(filename) : """ Parse densities from g_density """ lines = [] with open(filename, 'r') as f: lines = f.readlines() i = 0 while lines[i].startswith("#") : i = i + 1 legends = [] while lines[i].startswith('@'): if lines[i].find("yaxis label") > 0 : cols = lines[i].split('"') ylabel = cols[-2] elif re.search(" s\d+ legend",lines[i]): cols = lines[i].split('"') legends.append(cols[-2]) i = i + 1 data = [] while i < len(lines): data.append(lines[i].strip().split()) i = i + 1 data = np.array(data, dtype=float) densities = {l : col for l, col in zip(legends, data[:,1:].T)} return data[:,0], densities, ylabel ## ## Routines to read output from Umbrella Sampling ### class UmbrellaResults(object) : """ Parent class to encapsulate a results file from an umbrella/zconst sampling simulation Internally, irrespectively of MD code, the units should be Angstroms for lengths and kcal/mol for energy Attributes ---------- center : float the center of the umbrella potential samples : numpy array the samples from the simulation weight : float the weight of the umbrella potential """ def __init__(self,center,weight=None,filename=None,**kwargs) : self.samples = None self.center = center self.weight = weight if filename is not None : self.read(filename,**kwargs) def __add__(self,other) : """ Adds the samples of another simulation onto this one """ both = UmbrellaResults(self.center,self.weight) both.samples = np.zeros(self.samples.shape[0]+other.samples.shape[0]) both.samples[:self.samples.shape[0]] = self.samples both.samples[self.samples.shape[0]:] = other.samples return both def __radd__(self,other) : both = UmbrellaResults(other.center,other.weight) both.samples = np.zeros(self.samples.shape[0]+other.samples.shape[0]) both.samples[:self.other.shape[0]] = other.samples both.samples[self.other.shape[0]:] = self.samples return both def read(self,filename,**kwargs) : """ Should be implemented by sub-classes """ pass def skip(self,nskip,ispart=True) : """ Removes/skip samples at the start of the simulation Parameters ---------- nskip : int the number or the proportion of samples to skip ispart : bool, optional if the nskip argument should be interpreted as the proportion of the total number of samples """ if self.samples is None or (ispart and nskip < 2): return if ispart : nskip = int(np.floor(float(self.samples.shape[0])/float(nskip))) self.samples = self.samples[nskip+1:] def shorten(self,n,ispart=True) : """ Removes samples at the end of the simulation Parameters ---------- n : int the number or the proportion of samples to discard ispart : bool, optional if the n argument should be interpreted as the proportion of the total number of samples """ if self.samples is None or (ispart and n < 2): return if ispart : n = int(np.floor(float(self.samples.shape[0])/float(n))) self.samples = self.samples[:n+1] def block_it(self,nblocks) : """ Sub-sample/block the samples Parameters ---------- nblocks : int the number of blocks Returns ------- list of _ResultsFile objects the sub-samples/blocks of the original samples """ if nblocks == 1 : return [self] blocks = [] nitems = self.samples.shape[0] blocklen = int(np.floor(float(nitems)/float(nblocks))) for i in range(nblocks) : blocks.append(UmbrellaResults(self.center,self.weight)) blocks[-1].samples = self.samples[blocklen*i:min(blocklen*(i+1),nitems)] return blocks def synthesize(self) : """ Replaces the samples with normal distributed data according to the mean and standard deviation of the orignal data """ self._samples_orig = self.samples mean = self.samples.mean() std = self.samples.std() self.samples = random.randn(self.samples.shape[0])*std + mean def lower(self) : """ Returns the lower part of the 99% confidence interval """ return self.samples.mean()-2.58*self.samples.std() def upper(self) : """ Returns the upper part of the 99% confidence interval """ return self.samples.mean()+2.58*self.samples.std() class GromacsUmbrellaResults(UmbrellaResults) : """ Read umbrella samples from a Gromacs pullx-files """ def read(self,filename,**kwargs) : """ Read a pullx-file Parameters ---------- filename : string the name of the file **kwargs : colidx : the column index to parse isforces : if it is a pullf file rather than a pullx file """ data = [] if "colidx" in kwargs : colidx = kwargs["colidx"] else : colidx = 2 # The pullf files do not have column 1 if "isforces" in kwargs and kwargs["isforces"] : colidx = colidx - 1 for line in open(filename,'r').readlines() : if not line[0] == "#" and not line[0] == "@" and len(line) > 4 : try : data.append(line.strip().split()[colidx]) except : pass if "isforces" in kwargs and kwargs["isforces"] : self.samples = np.array(data,dtype=float) / 10.0 * ECONV[KJMOL][KCALMOL] # Convert to kcal/mol/A else : self.samples = np.array(data,dtype=float)*10 # Convert to A if colidx != 2 : self.samples = -self.samples if self.center > 0 : self.samples = np.abs(self.samples) class PlumedUmbrellaResults(UmbrellaResults) : """ Read umbrella samples from a plumed colvars-file """ def read(self,filename,**kwargs) : """ Read a colvars-file Parameters ---------- filename : string the name of the file **kwargs : colidx : the column index to parse """ data = [] if "colidx" in kwargs : colidx = kwargs["colidx"]-1 # To make it compatible with Gromacs umbrella output else : colidx = 1 nread = 0 with open(filename,"r") as f : line = f.readline() while line : if line[0] != "#" : data.append(line.strip().split()[colidx]) line = f.readline() self.samples = np.array(data,dtype=float)*10 # Convert to A if colidx != 1 : self.samples = -self.samples if self.center > 0 and "expansion" not in kwargs : self.samples = np.abs(self.samples) class LammpsUmbrellaResults(UmbrellaResults) : """ Read umbrella samples from a Lammps colvars-file """ def read(self,filename,**kwargs) : """ Read a colvars-file Parameters ---------- filename : string the name of the file **kwargs : stride : the stride to parse """ if "stride" in kwargs : stride = kwargs["stride"] else : stride = -1 data = [] nread = 0 with open(filename,"r") as f : line = f.readline() while line : if line[0] != "#" : nread = nread + 1 if stride <= 0 or (stride > 0 and (nread == 1 or (nread-1) % stride == 0)) : if len(line.strip().split()) > 1 : data.append(line.strip().split()[1]) line = f.readline() self.samples = np.array(data,dtype=float) class SimpleEnergyFile(UmbrellaResults) : """ Read a simple energy file with total energies """ def read(self,filename,**kwargs) : """ Read a two-columned energy file, where the second column is parsed as total energies Parameters ---------- filename : string the name of the file **kwargs : ignored at the moment """ data = [] with open(filename,"r") as f : line = f.readline() while line : if line[0] != "#" : data.append(line.strip().split()[1]) line = f.readline() self.samples = np.array(data,dtype=float)
SGenheden/Scripts
sgenlib/parsing.py
Python
mit
9,364
[ "Gromacs", "LAMMPS" ]
c19761bf204cc07348f6b77b78fec95284fc53f2877f3df315dd95c78eb9b314
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple from Cheetah.Template import Template from Cheetah.DummyTransaction import * from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList from Cheetah.CacheRegion import CacheRegion import Cheetah.Filters as Filters import Cheetah.ErrorCatchers as ErrorCatchers ################################################## ## MODULE CONSTANTS VFFSL=valueFromFrameOrSearchList VFSL=valueFromSearchList VFN=valueForName currentTime=time.time __CHEETAH_version__ = '2.4.4' __CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0) __CHEETAH_genTime__ = 1453357629.274994 __CHEETAH_genTimestamp__ = 'Thu Jan 21 15:27:09 2016' __CHEETAH_src__ = '/home/babel/Build/Test/OpenPLi5/openpli5.0/build/tmp/work/tmnanoseplus-oe-linux/enigma2-plugin-extensions-openwebif/1+gitAUTOINC+186ea358f6-r0/git/plugin/controllers/views/web/epgsearch.tmpl' __CHEETAH_srcLastModified__ = 'Thu Jan 21 15:27:08 2016' __CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine' if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple: raise AssertionError( 'This template was compiled with Cheetah version' ' %s. Templates compiled before version %s must be recompiled.'%( __CHEETAH_version__, RequiredCheetahVersion)) ################################################## ## CLASSES class epgsearch(Template): ################################################## ## CHEETAH GENERATED METHODS def __init__(self, *args, **KWs): super(epgsearch, self).__init__(*args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split() for k,v in KWs.items(): if k in allowedKWs: cheetahKWArgs[k] = v self._initCheetahInstance(**cheetahKWArgs) def respond(self, trans=None): ## CHEETAH: main method generated for this template if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)): trans = self.transaction # is None unless self.awake() was called if not trans: trans = DummyTransaction() _dummyTrans = True else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body _orig_filter_53550734 = _filter filterName = u'WebSafe' if self._CHEETAH__filters.has_key("WebSafe"): _filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName] else: _filter = self._CHEETAH__currentFilter = \ self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter write(u'''<?xml version="1.0" encoding="UTF-8"?> <e2eventlist> ''') for event in VFFSL(SL,"events",True): # generated from line 4, col 2 write(u'''\t<e2event> \t\t<e2eventid>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.id",True)) # u'$str($event.id)' on line 6, col 14 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.id)')) # from line 6, col 14. write(u'''</e2eventid> \t\t<e2eventstart>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.begin_timestamp",True)) # u'$str($event.begin_timestamp)' on line 7, col 17 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.begin_timestamp)')) # from line 7, col 17. write(u'''</e2eventstart> \t\t<e2eventduration>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.duration_sec",True)) # u'$str($event.duration_sec)' on line 8, col 20 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.duration_sec)')) # from line 8, col 20. write(u'''</e2eventduration> \t\t<e2eventcurrenttime>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.now_timestamp",True)) # u'$str($event.now_timestamp)' on line 9, col 23 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.now_timestamp)')) # from line 9, col 23. write(u'''</e2eventcurrenttime> \t\t<e2eventtitle>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.title",True)) # u'$str($event.title)' on line 10, col 17 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.title)')) # from line 10, col 17. write(u'''</e2eventtitle> \t\t<e2eventdescription>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.shortdesc",True)) # u'$str($event.shortdesc)' on line 11, col 23 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.shortdesc)')) # from line 11, col 23. write(u'''</e2eventdescription> \t\t<e2eventdescriptionextended>''') _v = VFFSL(SL,"str",False)(VFFSL(SL,"event.longdesc",True)) # u'$str($event.longdesc)' on line 12, col 31 if _v is not None: write(_filter(_v, rawExpr=u'$str($event.longdesc)')) # from line 12, col 31. write(u'''</e2eventdescriptionextended> \t\t<e2eventservicereference>''') _v = VFFSL(SL,"event.sref",True) # u'$event.sref' on line 13, col 28 if _v is not None: write(_filter(_v, rawExpr=u'$event.sref')) # from line 13, col 28. write(u'''</e2eventservicereference> \t\t<e2eventservicename>''') _v = VFFSL(SL,"event.sname",True) # u'$event.sname' on line 14, col 23 if _v is not None: write(_filter(_v, rawExpr=u'$event.sname')) # from line 14, col 23. write(u'''</e2eventservicename> \t</e2event> ''') write(u'''</e2eventlist> ''') _filter = self._CHEETAH__currentFilter = _orig_filter_53550734 ######################################## ## END - generated method body return _dummyTrans and trans.response().getvalue() or "" ################################################## ## CHEETAH GENERATED ATTRIBUTES _CHEETAH__instanceInitialized = False _CHEETAH_version = __CHEETAH_version__ _CHEETAH_versionTuple = __CHEETAH_versionTuple__ _CHEETAH_genTime = __CHEETAH_genTime__ _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__ _CHEETAH_src = __CHEETAH_src__ _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__ _mainCheetahMethod_for_epgsearch= 'respond' ## END CLASS DEFINITION if not hasattr(epgsearch, '_initCheetahAttributes'): templateAPIClass = getattr(epgsearch, '_CHEETAH_templateClass', Template) templateAPIClass._addCheetahPlumbingCodeToClass(epgsearch) # CHEETAH was developed by Tavis Rudd and Mike Orr # with code, advice and input from many other volunteers. # For more information visit http://www.CheetahTemplate.org/ ################################################## ## if run from command line: if __name__ == '__main__': from Cheetah.TemplateCmdLineIface import CmdLineIface CmdLineIface(templateObj=epgsearch()).run()
MOA-2011/e2openplugin-OpenWebif
plugin/controllers/views/web/epgsearch.py
Python
gpl-2.0
7,504
[ "VisIt" ]
573655f60423e4735b540d976e055a34d95efdd0074be5ad20242d2ff6a2b916
""" User policy settings """ from askbot.conf.settings_wrapper import settings from askbot.conf.super_groups import LOGIN_USERS_COMMUNICATION from askbot.deps import livesettings from django.conf import settings as django_settings from askbot.skins import utils as skin_utils from django.utils.translation import ugettext as _ from askbot import const USER_SETTINGS = livesettings.ConfigurationGroup( 'USER_SETTINGS', _('User settings'), super_group = LOGIN_USERS_COMMUNICATION ) settings.register( livesettings.BooleanValue( USER_SETTINGS, 'EDITABLE_SCREEN_NAME', default = True, description = _('Allow editing user screen name') ) ) settings.register( livesettings.BooleanValue( USER_SETTINGS, 'ALLOW_ACCOUNT_RECOVERY_BY_EMAIL', default = True, description = _('Allow account recovery by email') ) ) settings.register( livesettings.BooleanValue( USER_SETTINGS, 'ALLOW_ADD_REMOVE_LOGIN_METHODS', default = True, description = _('Allow adding and removing login methods') ) ) settings.register( livesettings.IntegerValue( USER_SETTINGS, 'MIN_USERNAME_LENGTH', hidden=True, default=1, description=_('Minimum allowed length for screen name') ) ) settings.register( livesettings.BooleanValue( USER_SETTINGS, 'DISABLE_GRAVATAR', default = False, description = _('Disable use of gravatar.com'), help_text=_( 'Check this option if you want to disallow the use of gravatar.com for avatars. You will have to enable uploaded avatars. For more information, please visit <a href="http://askbot.org/doc/optional-modules.html#uploaded-avatars">this page</a>.' ) ) ) settings.register( livesettings.ImageValue( USER_SETTINGS, 'DEFAULT_AVATAR_URL', description = _('Default avatar for users'), help_text = _( 'To change the avatar image, select new file, ' 'then submit this whole form.' ), upload_directory = django_settings.ASKBOT_FILE_UPLOAD_DIR, upload_url = '/' + django_settings.ASKBOT_UPLOADED_FILES_URL, default = '/images/nophoto.png', url_resolver = skin_utils.get_media_url ) ) settings.register( livesettings.StringValue( USER_SETTINGS, 'GRAVATAR_TYPE', default='identicon', choices=const.GRAVATAR_TYPE_CHOICES, description=_('Default Gravatar icon type'), help_text=_( 'This option allows you to set the default avatar type for email addresses without associated gravatar images. For more information, please visit <a href="http://en.gravatar.com/site/implement/images/">this page</a>.' ) ) ) settings.register( livesettings.StringValue( USER_SETTINGS, 'NAME_OF_ANONYMOUS_USER', default = '', description = _('Name for the Anonymous user') ) )
rosihorrorshow/askbot-devel
askbot/conf/user_settings.py
Python
gpl-3.0
3,162
[ "VisIt" ]
1ae8266009056c37d570b88e7b3e8f2ba5411baae618f30a200f1c3a088dd448
#!/usr/bin/python2.4 # # Copyright 2007 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A library for manipulating points and polylines. This is a library for creating and manipulating points on the unit sphere, as an approximate model of Earth. The primary use of this library is to make manipulation and matching of polylines easy in the transitfeed library. NOTE: in this library, Earth is modelled as a sphere, whereas GTFS specifies that latitudes and longitudes are in WGS84. For the purpose of comparing and matching latitudes and longitudes that are relatively close together on the surface of the earth, this is adequate; for other purposes, this library may not be accurate enough. """ __author__ = 'chris.harrelson.code@gmail.com (Chris Harrelson)' import copy import decimal import heapq import math class ShapeError(Exception): """Thrown whenever there is a shape parsing error.""" pass EARTH_RADIUS_METERS = 6371010.0 class Point(object): """ A class representing a point on the unit sphere in three dimensions. """ def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __hash__(self): return hash((self.x, self.y, self.z)) def __cmp__(self, other): if not isinstance(other, Point): raise TypeError('Point.__cmp__(x,y) requires y to be a "Point", ' 'not a "%s"' % type(other).__name__) return cmp((self.x, self.y, self.z), (other.x, other.y, other.z)) def __str__(self): return "(%.15f, %.15f, %.15f) " % (self.x, self.y, self.z) def Norm2(self): """ Returns the L_2 (Euclidean) norm of self. """ sum = self.x * self.x + self.y * self.y + self.z * self.z return math.sqrt(float(sum)) def IsUnitLength(self): return abs(self.Norm2() - 1.0) < 1e-14 def Plus(self, other): """ Returns a new point which is the pointwise sum of self and other. """ return Point(self.x + other.x, self.y + other.y, self.z + other.z) def Minus(self, other): """ Returns a new point which is the pointwise subtraction of other from self. """ return Point(self.x - other.x, self.y - other.y, self.z - other.z) def DotProd(self, other): """ Returns the (scalar) dot product of self with other. """ return self.x * other.x + self.y * other.y + self.z * other.z def Times(self, val): """ Returns a new point which is pointwise multiplied by val. """ return Point(self.x * val, self.y * val, self.z * val) def Normalize(self): """ Returns a unit point in the same direction as self. """ return self.Times(1 / self.Norm2()) def RobustCrossProd(self, other): """ A robust version of cross product. If self and other are not nearly the same point, returns the same value as CrossProd() modulo normalization. Otherwise returns an arbitrary unit point orthogonal to self. """ assert(self.IsUnitLength() and other.IsUnitLength()) x = self.Plus(other).CrossProd(other.Minus(self)) if abs(x.x) > 1e-15 or abs(x.y) > 1e-15 or abs(x.z) > 1e-15: return x.Normalize() else: return self.Ortho() def LargestComponent(self): """ Returns (i, val) where i is the component index (0 - 2) which has largest absolute value and val is the value of the component. """ if abs(self.x) > abs(self.y): if abs(self.x) > abs(self.z): return (0, self.x) else: return (2, self.z) else: if abs(self.y) > abs(self.z): return (1, self.y) else: return (2, self.z) def Ortho(self): """Returns a unit-length point orthogonal to this point""" (index, val) = self.LargestComponent() index = index - 1 if index < 0: index = 2 temp = Point(0.012, 0.053, 0.00457) if index == 0: temp.x = 1 elif index == 1: temp.y = 1 elif index == 2: temp.z = 1 return self.CrossProd(temp).Normalize() def CrossProd(self, other): """ Returns the cross product of self and other. """ return Point( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x) @staticmethod def _approxEq(a, b): return abs(a - b) < 1e-11 def Equals(self, other): """ Returns true of self and other are approximately equal. """ return (self._approxEq(self.x, other.x) and self._approxEq(self.y, other.y) and self._approxEq(self.z, other.z)) def Angle(self, other): """ Returns the angle in radians between self and other. """ return math.atan2(self.CrossProd(other).Norm2(), self.DotProd(other)) def ToLatLng(self): """ Returns that latitude and longitude that this point represents under a spherical Earth model. """ rad_lat = math.atan2(self.z, math.sqrt(self.x * self.x + self.y * self.y)) rad_lng = math.atan2(self.y, self.x) return (rad_lat * 180.0 / math.pi, rad_lng * 180.0 / math.pi) @staticmethod def FromLatLng(lat, lng): """ Returns a new point representing this latitude and longitude under a spherical Earth model. """ phi = lat * (math.pi / 180.0) theta = lng * (math.pi / 180.0) cosphi = math.cos(phi) return Point(math.cos(theta) * cosphi, math.sin(theta) * cosphi, math.sin(phi)) def GetDistanceMeters(self, other): assert(self.IsUnitLength() and other.IsUnitLength()) return self.Angle(other) * EARTH_RADIUS_METERS def SimpleCCW(a, b, c): """ Returns true if the triangle abc is oriented counterclockwise. """ return c.CrossProd(a).DotProd(b) > 0 def GetClosestPoint(x, a, b): """ Returns the point on the great circle segment ab closest to x. """ assert(x.IsUnitLength()) assert(a.IsUnitLength()) assert(b.IsUnitLength()) a_cross_b = a.RobustCrossProd(b) # project to the great circle going through a and b p = x.Minus( a_cross_b.Times( x.DotProd(a_cross_b) / a_cross_b.Norm2())) # if p lies between a and b, return it if SimpleCCW(a_cross_b, a, p) and SimpleCCW(p, b, a_cross_b): return p.Normalize() # otherwise return the closer of a or b if x.Minus(a).Norm2() <= x.Minus(b).Norm2(): return a else: return b class Poly(object): """ A class representing a polyline. """ def __init__(self, points = [], name=None): self._points = list(points) self._name = name def AddPoint(self, p): """ Adds a new point to the end of the polyline. """ assert(p.IsUnitLength()) self._points.append(p) def GetName(self): return self._name def GetPoint(self, i): return self._points[i] def GetPoints(self): return self._points def GetNumPoints(self): return len(self._points) def _GetPointSafe(self, i): try: return self.GetPoint(i) except IndexError: return None def GetClosestPoint(self, p): """ Returns (closest_p, closest_i), where closest_p is the closest point to p on the piecewise linear curve represented by the polyline, and closest_i is the index of the point on the polyline just before the polyline segment that contains closest_p. """ assert(len(self._points) > 0) closest_point = self._points[0] closest_i = 0 for i in range(0, len(self._points) - 1): (a, b) = (self._points[i], self._points[i+1]) cur_closest_point = GetClosestPoint(p, a, b) if p.Angle(cur_closest_point) < p.Angle(closest_point): closest_point = cur_closest_point.Normalize() closest_i = i return (closest_point, closest_i) def LengthMeters(self): """Return length of this polyline in meters.""" assert(len(self._points) > 0) length = 0 for i in range(0, len(self._points) - 1): length += self._points[i].GetDistanceMeters(self._points[i+1]) return length def Reversed(self): """Return a polyline that is the reverse of this polyline.""" return Poly(reversed(self.GetPoints()), self.GetName()) def CutAtClosestPoint(self, p): """ Let x be the point on the polyline closest to p. Then CutAtClosestPoint returns two new polylines, one representing the polyline from the beginning up to x, and one representing x onwards to the end of the polyline. x is the first point returned in the second polyline. """ (closest, i) = self.GetClosestPoint(p) tmp = [closest] tmp.extend(self._points[i+1:]) return (Poly(self._points[0:i+1]), Poly(tmp)) def GreedyPolyMatchDist(self, shape): """ Tries a greedy matching algorithm to match self to the given shape. Returns the maximum distance in meters of any point in self to its matched point in shape under the algorithm. Args: shape, a Poly object. """ tmp_shape = Poly(shape.GetPoints()) max_radius = 0 for (i, point) in enumerate(self._points): tmp_shape = tmp_shape.CutAtClosestPoint(point)[1] dist = tmp_shape.GetPoint(0).GetDistanceMeters(point) max_radius = max(max_radius, dist) return max_radius @staticmethod def MergePolys(polys, merge_point_threshold=10): """ Merge multiple polylines, in the order that they were passed in. Merged polyline will have the names of their component parts joined by ';'. Example: merging [a,b], [c,d] and [e,f] will result in [a,b,c,d,e,f]. However if the endpoints of two adjacent polylines are less than merge_point_threshold meters apart, we will only use the first endpoint in the merged polyline. """ name = ";".join((p.GetName(), '')[p.GetName() is None] for p in polys) merged = Poly([], name) if polys: first_poly = polys[0] for p in first_poly.GetPoints(): merged.AddPoint(p) last_point = merged._GetPointSafe(-1) for poly in polys[1:]: first_point = poly._GetPointSafe(0) if (last_point and first_point and last_point.GetDistanceMeters(first_point) <= merge_point_threshold): points = poly.GetPoints()[1:] else: points = poly.GetPoints() for p in points: merged.AddPoint(p) last_point = merged._GetPointSafe(-1) return merged def __str__(self): return self._ToString(str) def ToLatLngString(self): return self._ToString(lambda p: str(p.ToLatLng())) def _ToString(self, pointToStringFn): return "%s: %s" % (self.GetName() or "", ", ".join([pointToStringFn(p) for p in self._points])) class PolyCollection(object): """ A class representing a collection of polylines. """ def __init__(self): self._name_to_shape = {} pass def AddPoly(self, poly, smart_duplicate_handling=True): """ Adds a new polyline to the collection. """ inserted_name = poly.GetName() if poly.GetName() in self._name_to_shape: if not smart_duplicate_handling: raise ShapeError("Duplicate shape found: " + poly.GetName()) print ("Warning: duplicate shape id being added to collection: " + poly.GetName()) if poly.GreedyPolyMatchDist(self._name_to_shape[poly.GetName()]) < 10: print " (Skipping as it apears to be an exact duplicate)" else: print " (Adding new shape variant with uniquified name)" inserted_name = "%s-%d" % (inserted_name, len(self._name_to_shape)) self._name_to_shape[inserted_name] = poly def NumPolys(self): return len(self._name_to_shape) def FindMatchingPolys(self, start_point, end_point, max_radius=150): """ Returns a list of polylines in the collection that have endpoints within max_radius of the given start and end points. """ matches = [] for shape in self._name_to_shape.itervalues(): if start_point.GetDistanceMeters(shape.GetPoint(0)) < max_radius and \ end_point.GetDistanceMeters(shape.GetPoint(-1)) < max_radius: matches.append(shape) return matches class PolyGraph(PolyCollection): """ A class representing a graph where the edges are polylines. """ def __init__(self): PolyCollection.__init__(self) self._nodes = {} def AddPoly(self, poly, smart_duplicate_handling=True): PolyCollection.AddPoly(self, poly, smart_duplicate_handling) start_point = poly.GetPoint(0) end_point = poly.GetPoint(-1) self._AddNodeWithEdge(start_point, poly) self._AddNodeWithEdge(end_point, poly) def _AddNodeWithEdge(self, point, edge): if point in self._nodes: self._nodes[point].add(edge) else: self._nodes[point] = set([edge]) def ShortestPath(self, start, goal): """Uses the A* algorithm to find a shortest path between start and goal. For more background see http://en.wikipedia.org/wiki/A-star_algorithm Some definitions: g(x): The actual shortest distance traveled from initial node to current node. h(x): The estimated (or "heuristic") distance from current node to goal. We use the distance on Earth from node to goal as the heuristic. This heuristic is both admissible and monotonic (see wikipedia for more details). f(x): The sum of g(x) and h(x), used to prioritize elements to look at. Arguments: start: Point that is in the graph, start point of the search. goal: Point that is in the graph, end point for the search. Returns: A Poly object representing the shortest polyline through the graph from start to goal, or None if no path found. """ assert start in self._nodes assert goal in self._nodes closed_set = set() # Set of nodes already evaluated. open_heap = [(0, start)] # Nodes to visit, heapified by f(x). open_set = set([start]) # Same as open_heap, but a set instead of a heap. g_scores = { start: 0 } # Distance from start along optimal path came_from = {} # Map to reconstruct optimal path once we're done. while open_set: (f_x, x) = heapq.heappop(open_heap) open_set.remove(x) if x == goal: return self._ReconstructPath(came_from, goal) closed_set.add(x) edges = self._nodes[x] for edge in edges: if edge.GetPoint(0) == x: y = edge.GetPoint(-1) else: y = edge.GetPoint(0) if y in closed_set: continue tentative_g_score = g_scores[x] + edge.LengthMeters() tentative_is_better = False if y not in open_set: h_y = y.GetDistanceMeters(goal) f_y = tentative_g_score + h_y open_set.add(y) heapq.heappush(open_heap, (f_y, y)) tentative_is_better = True elif tentative_g_score < g_scores[y]: tentative_is_better = True if tentative_is_better: came_from[y] = (x, edge) g_scores[y] = tentative_g_score return None def _ReconstructPath(self, came_from, current_node): """ Helper method for ShortestPath, to reconstruct path. Arguments: came_from: a dictionary mapping Point to (Point, Poly) tuples. This dictionary keeps track of the previous neighbor to a node, and the edge used to get from the previous neighbor to the node. current_node: the current Point in the path. Returns: A Poly that represents the path through the graph from the start of the search to current_node. """ if current_node in came_from: (previous_node, previous_edge) = came_from[current_node] if previous_edge.GetPoint(0) == current_node: previous_edge = previous_edge.Reversed() p = self._ReconstructPath(came_from, previous_node) return Poly.MergePolys([p, previous_edge], merge_point_threshold=0) else: return Poly([], '') def FindShortestMultiPointPath(self, points, max_radius=150, keep_best_n=10, verbosity=0): """ Return a polyline, representing the shortest path through this graph that has edge endpoints on each of a given list of points in sequence. We allow fuzziness in matching of input points to points in this graph. We limit ourselves to a view of the best keep_best_n paths at any time, as a greedy optimization. """ assert len(points) > 1 nearby_points = [] paths_found = [] # A heap sorted by inverse path length. for i, point in enumerate(points): nearby = [p for p in self._nodes.iterkeys() if p.GetDistanceMeters(point) < max_radius] if verbosity >= 2: print ("Nearby points for point %d %s: %s" % (i + 1, str(point.ToLatLng()), ", ".join([str(n.ToLatLng()) for n in nearby]))) if nearby: nearby_points.append(nearby) else: print "No nearby points found for point %s" % str(point.ToLatLng()) return None pathToStr = lambda start, end, path: (" Best path %s -> %s: %s" % (str(start.ToLatLng()), str(end.ToLatLng()), path and path.GetName() or "None")) if verbosity >= 3: print "Step 1" step = 2 start_points = nearby_points[0] end_points = nearby_points[1] for start in start_points: for end in end_points: path = self.ShortestPath(start, end) if verbosity >= 3: print pathToStr(start, end, path) PolyGraph._AddPathToHeap(paths_found, path, keep_best_n) for possible_points in nearby_points[2:]: if verbosity >= 3: print "\nStep %d" % step step += 1 new_paths_found = [] start_end_paths = {} # cache of shortest paths between (start, end) pairs for score, path in paths_found: start = path.GetPoint(-1) for end in possible_points: if (start, end) in start_end_paths: new_segment = start_end_paths[(start, end)] else: new_segment = self.ShortestPath(start, end) if verbosity >= 3: print pathToStr(start, end, new_segment) start_end_paths[(start, end)] = new_segment if new_segment: new_path = Poly.MergePolys([path, new_segment], merge_point_threshold=0) PolyGraph._AddPathToHeap(new_paths_found, new_path, keep_best_n) paths_found = new_paths_found if paths_found: best_score, best_path = max(paths_found) return best_path else: return None @staticmethod def _AddPathToHeap(heap, path, keep_best_n): if path and path.GetNumPoints(): new_item = (-path.LengthMeters(), path) if new_item not in heap: if len(heap) < keep_best_n: heapq.heappush(heap, new_item) else: heapq.heapreplace(heap, new_item)
digideskio/transitfeed
transitfeed/shapelib.py
Python
apache-2.0
19,617
[ "VisIt" ]
d945eb9a8c231eacdc04ed5e6a7c0b912d87a419ae7333bb5c8946011d4cb68d
# Copyright (c) 2012 - 2014, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy.special import gammaln, digamma from ...util.linalg import pdinv from domains import _REAL, _POSITIVE import warnings import weakref class Prior(object): domain = None _instance = None def __new__(cls, *args, **kwargs): if not cls._instance or cls._instance.__class__ is not cls: cls._instance = super(Prior, cls).__new__(cls, *args, **kwargs) return cls._instance def pdf(self, x): return np.exp(self.lnpdf(x)) def plot(self): import sys assert "matplotlib" in sys.modules, "matplotlib package has not been imported." from ...plotting.matplot_dep import priors_plots priors_plots.univariate_plot(self) def __repr__(self, *args, **kwargs): return self.__str__() class Gaussian(Prior): """ Implementation of the univariate Gaussian probability function, coupled with random variables. :param mu: mean :param sigma: standard deviation .. Note:: Bishop 2006 notation is used throughout the code """ domain = _REAL _instances = [] def __new__(cls, mu=0, sigma=1): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if instance().mu == mu and instance().sigma == sigma: return instance() o = super(Prior, cls).__new__(cls, mu, sigma) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, mu, sigma): self.mu = float(mu) self.sigma = float(sigma) self.sigma2 = np.square(self.sigma) self.constant = -0.5 * np.log(2 * np.pi * self.sigma2) def __str__(self): return "N({:.2g}, {:.2g})".format(self.mu, self.sigma) def lnpdf(self, x): return self.constant - 0.5 * np.square(x - self.mu) / self.sigma2 def lnpdf_grad(self, x): return -(x - self.mu) / self.sigma2 def rvs(self, n): return np.random.randn(n) * self.sigma + self.mu # def __getstate__(self): # return self.mu, self.sigma # # def __setstate__(self, state): # self.mu = state[0] # self.sigma = state[1] # self.sigma2 = np.square(self.sigma) # self.constant = -0.5 * np.log(2 * np.pi * self.sigma2) class Uniform(Prior): domain = _REAL _instances = [] def __new__(cls, lower=0, upper=1): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if instance().lower == lower and instance().upper == upper: return instance() o = super(Prior, cls).__new__(cls, lower, upper) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, lower, upper): self.lower = float(lower) self.upper = float(upper) def __str__(self): return "[{:.2g}, {:.2g}]".format(self.lower, self.upper) def lnpdf(self, x): region = (x >= self.lower) * (x <= self.upper) return region def lnpdf_grad(self, x): return np.zeros(x.shape) def rvs(self, n): return np.random.uniform(self.lower, self.upper, size=n) # def __getstate__(self): # return self.lower, self.upper # # def __setstate__(self, state): # self.lower = state[0] # self.upper = state[1] class LogGaussian(Gaussian): """ Implementation of the univariate *log*-Gaussian probability function, coupled with random variables. :param mu: mean :param sigma: standard deviation .. Note:: Bishop 2006 notation is used throughout the code """ domain = _POSITIVE _instances = [] def __new__(cls, mu=0, sigma=1): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if instance().mu == mu and instance().sigma == sigma: return instance() o = super(Prior, cls).__new__(cls, mu, sigma) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, mu, sigma): self.mu = float(mu) self.sigma = float(sigma) self.sigma2 = np.square(self.sigma) self.constant = -0.5 * np.log(2 * np.pi * self.sigma2) def __str__(self): return "lnN({:.2g}, {:.2g})".format(self.mu, self.sigma) def lnpdf(self, x): return self.constant - 0.5 * np.square(np.log(x) - self.mu) / self.sigma2 - np.log(x) def lnpdf_grad(self, x): return -((np.log(x) - self.mu) / self.sigma2 + 1.) / x def rvs(self, n): return np.exp(np.random.randn(n) * self.sigma + self.mu) class MultivariateGaussian(Prior): """ Implementation of the multivariate Gaussian probability function, coupled with random variables. :param mu: mean (N-dimensional array) :param var: covariance matrix (NxN) .. Note:: Bishop 2006 notation is used throughout the code """ domain = _REAL _instances = [] def __new__(cls, mu=0, var=1): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if np.all(instance().mu == mu) and np.all(instance().var == var): return instance() o = super(Prior, cls).__new__(cls, mu, var) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, mu, var): self.mu = np.array(mu).flatten() self.var = np.array(var) assert len(self.var.shape) == 2 assert self.var.shape[0] == self.var.shape[1] assert self.var.shape[0] == self.mu.size self.input_dim = self.mu.size self.inv, self.hld = pdinv(self.var) self.constant = -0.5 * self.input_dim * np.log(2 * np.pi) - self.hld def summary(self): raise NotImplementedError def pdf(self, x): return np.exp(self.lnpdf(x)) def lnpdf(self, x): d = x - self.mu return self.constant - 0.5 * np.sum(d * np.dot(d, self.inv), 1) def lnpdf_grad(self, x): d = x - self.mu return -np.dot(self.inv, d) def rvs(self, n): return np.random.multivariate_normal(self.mu, self.var, n) def plot(self): import sys assert "matplotlib" in sys.modules, "matplotlib package has not been imported." from ..plotting.matplot_dep import priors_plots priors_plots.multivariate_plot(self) def __getstate__(self): return self.mu, self.var def __setstate__(self, state): self.mu = state[0] self.var = state[1] assert len(self.var.shape) == 2 assert self.var.shape[0] == self.var.shape[1] assert self.var.shape[0] == self.mu.size self.input_dim = self.mu.size self.inv, self.hld = pdinv(self.var) self.constant = -0.5 * self.input_dim * np.log(2 * np.pi) - self.hld def gamma_from_EV(E, V): warnings.warn("use Gamma.from_EV to create Gamma Prior", FutureWarning) return Gamma.from_EV(E, V) class Gamma(Prior): """ Implementation of the Gamma probability function, coupled with random variables. :param a: shape parameter :param b: rate parameter (warning: it's the *inverse* of the scale) .. Note:: Bishop 2006 notation is used throughout the code """ domain = _POSITIVE _instances = [] def __new__(cls, a=1, b=.5): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if instance().a == a and instance().b == b: return instance() o = super(Prior, cls).__new__(cls, a, b) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, a, b): self.a = float(a) self.b = float(b) self.constant = -gammaln(self.a) + a * np.log(b) def __str__(self): return "Ga({:.2g}, {:.2g})".format(self.a, self.b) def summary(self): ret = {"E[x]": self.a / self.b, \ "E[ln x]": digamma(self.a) - np.log(self.b), \ "var[x]": self.a / self.b / self.b, \ "Entropy": gammaln(self.a) - (self.a - 1.) * digamma(self.a) - np.log(self.b) + self.a} if self.a > 1: ret['Mode'] = (self.a - 1.) / self.b else: ret['mode'] = np.nan return ret def lnpdf(self, x): return self.constant + (self.a - 1) * np.log(x) - self.b * x def lnpdf_grad(self, x): return (self.a - 1.) / x - self.b def rvs(self, n): return np.random.gamma(scale=1. / self.b, shape=self.a, size=n) @staticmethod def from_EV(E, V): """ Creates an instance of a Gamma Prior by specifying the Expected value(s) and Variance(s) of the distribution. :param E: expected value :param V: variance """ a = np.square(E) / V b = E / V return Gamma(a, b) def __getstate__(self): return self.a, self.b def __setstate__(self, state): self.a = state[0] self.b = state[1] self.constant = -gammaln(self.a) + self.a * np.log(self.b) class InverseGamma(Gamma): """ Implementation of the inverse-Gamma probability function, coupled with random variables. :param a: shape parameter :param b: rate parameter (warning: it's the *inverse* of the scale) .. Note:: Bishop 2006 notation is used throughout the code """ domain = _POSITIVE _instances = [] def __new__(cls, a=1, b=.5): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if instance().a == a and instance().b == b: return instance() o = super(Prior, cls).__new__(cls, a, b) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, a, b): self.a = float(a) self.b = float(b) self.constant = -gammaln(self.a) + a * np.log(b) def __str__(self): return "iGa({:.2g}, {:.2g})".format(self.a, self.b) def lnpdf(self, x): return self.constant - (self.a + 1) * np.log(x) - self.b / x def lnpdf_grad(self, x): return -(self.a + 1.) / x + self.b / x ** 2 def rvs(self, n): return 1. / np.random.gamma(scale=1. / self.b, shape=self.a, size=n) class DGPLVM_KFDA(Prior): """ Implementation of the Discriminative Gaussian Process Latent Variable function using Kernel Fisher Discriminant Analysis by Seung-Jean Kim for implementing Face paper by Chaochao Lu. :param lambdaa: constant :param sigma2: constant .. Note:: Surpassing Human-Level Face paper dgplvm implementation """ domain = _REAL # _instances = [] # def __new__(cls, lambdaa, sigma2): # Singleton: # if cls._instances: # cls._instances[:] = [instance for instance in cls._instances if instance()] # for instance in cls._instances: # if instance().mu == mu and instance().sigma == sigma: # return instance() # o = super(Prior, cls).__new__(cls, mu, sigma) # cls._instances.append(weakref.ref(o)) # return cls._instances[-1]() def __init__(self, lambdaa, sigma2, lbl, kern, x_shape): """A description for init""" self.datanum = lbl.shape[0] self.classnum = lbl.shape[1] self.lambdaa = lambdaa self.sigma2 = sigma2 self.lbl = lbl self.kern = kern lst_ni = self.compute_lst_ni() self.a = self.compute_a(lst_ni) self.A = self.compute_A(lst_ni) self.x_shape = x_shape def get_class_label(self, y): for idx, v in enumerate(y): if v == 1: return idx return -1 # This function assigns each data point to its own class # and returns the dictionary which contains the class name and parameters. def compute_cls(self, x): cls = {} # Appending each data point to its proper class for j in xrange(self.datanum): class_label = self.get_class_label(self.lbl[j]) if class_label not in cls: cls[class_label] = [] cls[class_label].append(x[j]) if len(cls) > 2: for i in range(2, self.classnum): del cls[i] return cls def x_reduced(self, cls): x1 = cls[0] x2 = cls[1] x = np.concatenate((x1, x2), axis=0) return x def compute_lst_ni(self): lst_ni = [] lst_ni1 = [] lst_ni2 = [] f1 = (np.where(self.lbl[:, 0] == 1)[0]) f2 = (np.where(self.lbl[:, 1] == 1)[0]) for idx in f1: lst_ni1.append(idx) for idx in f2: lst_ni2.append(idx) lst_ni.append(len(lst_ni1)) lst_ni.append(len(lst_ni2)) return lst_ni def compute_a(self, lst_ni): a = np.ones((self.datanum, 1)) count = 0 for N_i in lst_ni: if N_i == lst_ni[0]: a[count:count + N_i] = (float(1) / N_i) * a[count] count += N_i else: if N_i == lst_ni[1]: a[count: count + N_i] = -(float(1) / N_i) * a[count] count += N_i return a def compute_A(self, lst_ni): A = np.zeros((self.datanum, self.datanum)) idx = 0 for N_i in lst_ni: B = float(1) / np.sqrt(N_i) * (np.eye(N_i) - ((float(1) / N_i) * np.ones((N_i, N_i)))) A[idx:idx + N_i, idx:idx + N_i] = B idx += N_i return A # Here log function def lnpdf(self, x): x = x.reshape(self.x_shape) K = self.kern.K(x) a_trans = np.transpose(self.a) paran = self.lambdaa * np.eye(x.shape[0]) + self.A.dot(K).dot(self.A) inv_part = pdinv(paran)[0] J = a_trans.dot(K).dot(self.a) - a_trans.dot(K).dot(self.A).dot(inv_part).dot(self.A).dot(K).dot(self.a) J_star = (1. / self.lambdaa) * J return (-1. / self.sigma2) * J_star # Here gradient function def lnpdf_grad(self, x): x = x.reshape(self.x_shape) K = self.kern.K(x) paran = self.lambdaa * np.eye(x.shape[0]) + self.A.dot(K).dot(self.A) inv_part = pdinv(paran)[0] b = self.A.dot(inv_part).dot(self.A).dot(K).dot(self.a) a_Minus_b = self.a - b a_b_trans = np.transpose(a_Minus_b) DJ_star_DK = (1. / self.lambdaa) * (a_Minus_b.dot(a_b_trans)) DJ_star_DX = self.kern.gradients_X(DJ_star_DK, x) return (-1. / self.sigma2) * DJ_star_DX def rvs(self, n): return np.random.rand(n) # A WRONG implementation def __str__(self): return 'DGPLVM_prior' def __getstate___(self): return self.lbl, self.lambdaa, self.sigma2, self.kern, self.x_shape def __setstate__(self, state): lbl, lambdaa, sigma2, kern, a, A, x_shape = state self.datanum = lbl.shape[0] self.classnum = lbl.shape[1] self.lambdaa = lambdaa self.sigma2 = sigma2 self.lbl = lbl self.kern = kern lst_ni = self.compute_lst_ni() self.a = self.compute_a(lst_ni) self.A = self.compute_A(lst_ni) self.x_shape = x_shape class DGPLVM(Prior): """ Implementation of the Discriminative Gaussian Process Latent Variable model paper, by Raquel. :param sigma2: constant .. Note:: DGPLVM for Classification paper implementation """ domain = _REAL # _instances = [] # def __new__(cls, mu, sigma): # Singleton: # if cls._instances: # cls._instances[:] = [instance for instance in cls._instances if instance()] # for instance in cls._instances: # if instance().mu == mu and instance().sigma == sigma: # return instance() # o = super(Prior, cls).__new__(cls, mu, sigma) # cls._instances.append(weakref.ref(o)) # return cls._instances[-1]() def __init__(self, sigma2, lbl, x_shape): self.sigma2 = sigma2 # self.x = x self.lbl = lbl self.classnum = lbl.shape[1] self.datanum = lbl.shape[0] self.x_shape = x_shape self.dim = x_shape[1] def get_class_label(self, y): for idx, v in enumerate(y): if v == 1: return idx return -1 # This function assigns each data point to its own class # and returns the dictionary which contains the class name and parameters. def compute_cls(self, x): cls = {} # Appending each data point to its proper class for j in xrange(self.datanum): class_label = self.get_class_label(self.lbl[j]) if class_label not in cls: cls[class_label] = [] cls[class_label].append(x[j]) return cls # This function computes mean of each class. The mean is calculated through each dimension def compute_Mi(self, cls): M_i = np.zeros((self.classnum, self.dim)) for i in cls: # Mean of each class M_i[i] = np.mean(cls[i], axis=0) return M_i # Adding data points as tuple to the dictionary so that we can access indices def compute_indices(self, x): data_idx = {} for j in xrange(self.datanum): class_label = self.get_class_label(self.lbl[j]) if class_label not in data_idx: data_idx[class_label] = [] t = (j, x[j]) data_idx[class_label].append(t) return data_idx # Adding indices to the list so we can access whole the indices def compute_listIndices(self, data_idx): lst_idx = [] lst_idx_all = [] for i in data_idx: if len(lst_idx) == 0: pass #Do nothing, because it is the first time list is created so is empty else: lst_idx = [] # Here we put indices of each class in to the list called lst_idx_all for m in xrange(len(data_idx[i])): lst_idx.append(data_idx[i][m][0]) lst_idx_all.append(lst_idx) return lst_idx_all # This function calculates between classes variances def compute_Sb(self, cls, M_i, M_0): Sb = np.zeros((self.dim, self.dim)) for i in cls: B = (M_i[i] - M_0).reshape(self.dim, 1) B_trans = B.transpose() Sb += (float(len(cls[i])) / self.datanum) * B.dot(B_trans) return Sb # This function calculates within classes variances def compute_Sw(self, cls, M_i): Sw = np.zeros((self.dim, self.dim)) for i in cls: N_i = float(len(cls[i])) W_WT = np.zeros((self.dim, self.dim)) for xk in cls[i]: W = (xk - M_i[i]) W_WT += np.outer(W, W) Sw += (N_i / self.datanum) * ((1. / N_i) * W_WT) return Sw # Calculating beta and Bi for Sb def compute_sig_beta_Bi(self, data_idx, M_i, M_0, lst_idx_all): # import pdb # pdb.set_trace() B_i = np.zeros((self.classnum, self.dim)) Sig_beta_B_i_all = np.zeros((self.datanum, self.dim)) for i in data_idx: # pdb.set_trace() # Calculating Bi B_i[i] = (M_i[i] - M_0).reshape(1, self.dim) for k in xrange(self.datanum): for i in data_idx: N_i = float(len(data_idx[i])) if k in lst_idx_all[i]: beta = (float(1) / N_i) - (float(1) / self.datanum) Sig_beta_B_i_all[k] += float(N_i) / self.datanum * (beta * B_i[i]) else: beta = -(float(1) / self.datanum) Sig_beta_B_i_all[k] += float(N_i) / self.datanum * (beta * B_i[i]) Sig_beta_B_i_all = Sig_beta_B_i_all.transpose() return Sig_beta_B_i_all # Calculating W_j s separately so we can access all the W_j s anytime def compute_wj(self, data_idx, M_i): W_i = np.zeros((self.datanum, self.dim)) for i in data_idx: N_i = float(len(data_idx[i])) for tpl in data_idx[i]: xj = tpl[1] j = tpl[0] W_i[j] = (xj - M_i[i]) return W_i # Calculating alpha and Wj for Sw def compute_sig_alpha_W(self, data_idx, lst_idx_all, W_i): Sig_alpha_W_i = np.zeros((self.datanum, self.dim)) for i in data_idx: N_i = float(len(data_idx[i])) for tpl in data_idx[i]: k = tpl[0] for j in lst_idx_all[i]: if k == j: alpha = 1 - (float(1) / N_i) Sig_alpha_W_i[k] += (alpha * W_i[j]) else: alpha = 0 - (float(1) / N_i) Sig_alpha_W_i[k] += (alpha * W_i[j]) Sig_alpha_W_i = (1. / self.datanum) * np.transpose(Sig_alpha_W_i) return Sig_alpha_W_i # This function calculates log of our prior def lnpdf(self, x): x = x.reshape(self.x_shape) cls = self.compute_cls(x) M_0 = np.mean(x, axis=0) M_i = self.compute_Mi(cls) Sb = self.compute_Sb(cls, M_i, M_0) Sw = self.compute_Sw(cls, M_i) # Sb_inv_N = np.linalg.inv(Sb + np.eye(Sb.shape[0]) * (np.diag(Sb).min() * 0.1)) #Sb_inv_N = np.linalg.inv(Sb+np.eye(Sb.shape[0])*0.1) Sb_inv_N = pdinv(Sb+ np.eye(Sb.shape[0]) * (np.diag(Sb).min() * 0.1))[0] return (-1 / self.sigma2) * np.trace(Sb_inv_N.dot(Sw)) # This function calculates derivative of the log of prior function def lnpdf_grad(self, x): x = x.reshape(self.x_shape) cls = self.compute_cls(x) M_0 = np.mean(x, axis=0) M_i = self.compute_Mi(cls) Sb = self.compute_Sb(cls, M_i, M_0) Sw = self.compute_Sw(cls, M_i) data_idx = self.compute_indices(x) lst_idx_all = self.compute_listIndices(data_idx) Sig_beta_B_i_all = self.compute_sig_beta_Bi(data_idx, M_i, M_0, lst_idx_all) W_i = self.compute_wj(data_idx, M_i) Sig_alpha_W_i = self.compute_sig_alpha_W(data_idx, lst_idx_all, W_i) # Calculating inverse of Sb and its transpose and minus # Sb_inv_N = np.linalg.inv(Sb + np.eye(Sb.shape[0]) * (np.diag(Sb).min() * 0.1)) # Sb_inv_N = np.linalg.inv(Sb+np.eye(Sb.shape[0])*0.1) Sb_inv_N = pdinv(Sb+ np.eye(Sb.shape[0]) * (np.diag(Sb).min() * 0.1))[0] Sb_inv_N_trans = np.transpose(Sb_inv_N) Sb_inv_N_trans_minus = -1 * Sb_inv_N_trans Sw_trans = np.transpose(Sw) # Calculating DJ/DXk DJ_Dxk = 2 * ( Sb_inv_N_trans_minus.dot(Sw_trans).dot(Sb_inv_N_trans).dot(Sig_beta_B_i_all) + Sb_inv_N_trans.dot( Sig_alpha_W_i)) # Calculating derivative of the log of the prior DPx_Dx = ((-1 / self.sigma2) * DJ_Dxk) return DPx_Dx.T # def frb(self, x): # from functools import partial # from GPy.models import GradientChecker # f = partial(self.lnpdf) # df = partial(self.lnpdf_grad) # grad = GradientChecker(f, df, x, 'X') # grad.checkgrad(verbose=1) def rvs(self, n): return np.random.rand(n) # A WRONG implementation def __str__(self): return 'DGPLVM_prior' class HalfT(Prior): """ Implementation of the half student t probability function, coupled with random variables. :param A: scale parameter :param nu: degrees of freedom """ domain = _POSITIVE _instances = [] def __new__(cls, A, nu): # Singleton: if cls._instances: cls._instances[:] = [instance for instance in cls._instances if instance()] for instance in cls._instances: if instance().A == A and instance().nu == nu: return instance() o = super(Prior, cls).__new__(cls, A, nu) cls._instances.append(weakref.ref(o)) return cls._instances[-1]() def __init__(self, A, nu): self.A = float(A) self.nu = float(nu) self.constant = gammaln(.5*(self.nu+1.)) - gammaln(.5*self.nu) - .5*np.log(np.pi*self.A*self.nu) def __str__(self): return "hT({:.2g}, {:.2g})".format(self.A, self.nu) def lnpdf(self,theta): return (theta>0) * ( self.constant -.5*(self.nu+1) * np.log( 1.+ (1./self.nu) * (theta/self.A)**2 ) ) #theta = theta if isinstance(theta,np.ndarray) else np.array([theta]) #lnpdfs = np.zeros_like(theta) #theta = np.array([theta]) #above_zero = theta.flatten()>1e-6 #v = self.nu #sigma2=self.A #stop #lnpdfs[above_zero] = (+ gammaln((v + 1) * 0.5) # - gammaln(v * 0.5) # - 0.5*np.log(sigma2 * v * np.pi) # - 0.5*(v + 1)*np.log(1 + (1/np.float(v))*((theta[above_zero][0]**2)/sigma2)) #) #return lnpdfs def lnpdf_grad(self,theta): theta = theta if isinstance(theta,np.ndarray) else np.array([theta]) grad = np.zeros_like(theta) above_zero = theta>1e-6 v = self.nu sigma2=self.A grad[above_zero] = -0.5*(v+1)*(2*theta[above_zero])/(v*sigma2 + theta[above_zero][0]**2) return grad def rvs(self, n): #return np.random.randn(n) * self.sigma + self.mu from scipy.stats import t #[np.abs(x) for x in t.rvs(df=4,loc=0,scale=50, size=10000)]) ret = t.rvs(self.nu,loc=0,scale=self.A, size=n) ret[ret<0] = 0 return ret
gusmaogabriels/GPy
GPy/core/parameterization/priors.py
Python
bsd-3-clause
26,352
[ "Gaussian" ]
a1efb10279a74bf604f9a43127e676cb0bb784d8ba626a674e58b4974487ba85
from __future__ import print_function import os, shutil, fileinput import numpy import yaml import read_config import file_io # get default timestep def get_default_timestep(configs): this_file = 'Scene.main.mdl' this_path = os.path.join(configs['model_dir'],this_file) with open(this_path) as f: for line in f: if line.startswith('TIME_STEP =') or line.startswith('TIME_STEP='): deflt_timestep = float(line.split('=')[-1]) return deflt_timestep # intialize new westpa sim with template def initialize_template(template_dir,output_dir): # delete previous copy of output_simulation try: shutil.rmtree(output_dir) except OSError: if not os.path.isdir(output_dir): pass # make new copy of output_simulation try: shutil.copytree(template_dir,output_dir) except OSError: if os.path.isdir(output_dir): pass # copy mcell model into template def copy_mcell_model(mod_dir,out_dir): shutil.copytree(os.path.join(mod_dir),os.path.join(out_dir,'bstates',os.path.basename(mod_dir))) # move Scene.WE.mdl template into model folder def mv_sceWEmdl(mod_name,out_dir): this_file = 'Scene.WE.mdl' shutil.move(os.path.join(out_dir,'bstates',this_file),os.path.join(out_dir,'bstates',mod_name,this_file)) # generic function to replace placeholder term in template file name with real term def replace_all(file,searchExp,replaceExp): for line in fileinput.input(file, inplace=True): print(line.replace(searchExp, replaceExp), end='') # hard-coded into westpa_template template_names = {} template_names['model_name'] = 'template_model_dir_name' template_names['west_python'] = 'template_west_python' template_names['west_root'] = 'template_west_root' template_names['observable_name'] = 'template_observable_name' template_names['record_frequency'] = 'template_record_frequency' template_names['bin_bounds'] = 'template_bin_bounds' template_names['we_iters'] = 'template_we_iters' template_names['we_stride'] = 'template_we_stride' template_names['timestep'] = 'template_timestep' template_names['bin_bounds'] = 'template_bin_bounds' template_names['bin_target_count'] = 'template_bin_target_count' # write new cleanup.sh def write_new_cleanup(out_dir,configs): this_file = 'cleanup.sh' this_path = os.path.join(out_dir,this_file) replace_all(this_path,template_names['model_name'],configs['model_name']) # write new env.sh def write_new_env(out_dir,configs): this_file = 'env.sh' this_path = os.path.join(out_dir,this_file) replace_all(this_path,template_names['west_python'],configs['env']['python']) replace_all(this_path,template_names['west_root'],configs['env']['westpa']) # write new runseg.sh def write_new_runseg(out_dir,configs): this_file = 'runseg.sh' this_path = os.path.join(out_dir,this_file) replace_all(this_path,template_names['model_name'],configs['model_name']) replace_all(this_path,template_names['observable_name'],configs['model']['observable_1']) # write new system.py def write_new_system(out_dir,configs): this_file = 'system.py' this_path = os.path.join(out_dir,this_file) replace_all(this_path,template_names['record_frequency'],str(configs['data']['rec_freq'])) replace_all(this_path,template_names['bin_target_count'],str(configs['WE']['bins']['target_count'])) bin_min = configs['WE']['bins']['min_pcoord'] bin_max = configs['WE']['bins']['max_pcoord'] bin_step = configs['WE']['bins']['bin_size'] new_bins = 'list(numpy.linspace({0} + {2}/2.0,{1} - {2}/2.0, ({1} - {0})/{2}))'.format(bin_min,bin_max,bin_step) replace_all(this_path,template_names['bin_bounds'],new_bins) # write new west.cfg def write_new_westcfg(out_dir,configs): this_file = 'west.cfg' this_path = os.path.join(out_dir,this_file) replace_all(this_path,template_names['we_iters'],str(configs['WE']['iters'])) # write new Scene.WE.mdl def write_new_sceneWEmdl(out_dir,configs): this_file = 'Scene.WE.mdl' this_path = os.path.join(out_dir,'bstates',configs['model_name'],this_file) replace_all(this_path,template_names['we_iters'],str(configs['WE']['iters'])) replace_all(this_path,template_names['we_stride'],str(configs['WE']['stride'])) replace_all(this_path,template_names['record_frequency'],str(configs['data']['rec_freq'])) replace_all(this_path,template_names['timestep'],str(configs['default_timestep'])) # write new Scene.WE.mdl def write_new_scenemainmdl(out_dir,configs): this_file = 'Scene.main.mdl' this_path = os.path.join(out_dir,'bstates',configs['model_name'],this_file) for linenum,line in enumerate(fileinput.input(this_path, inplace=True)): if linenum==0: print('INCLUDE_FILE = "Scene.WE.mdl"') print(line, end='') elif line.startswith('ITERATIONS =') or line.startswith('ITERATIONS='): print('ITERATIONS = iterations') elif line.startswith('TIME_STEP =') or line.startswith('TIME_STEP='): print('TIME_STEP = timestep') else: print(line, end='') # write new Scene.rxn_output.mdl def write_new_scenerxn_outputmdl(out_dir,configs): this_file = 'Scene.rxn_output.mdl' this_path = os.path.join(out_dir,'bstates',configs['model_name'],this_file) for line in fileinput.input(this_path, inplace=True): if line.startswith(' STEP=') or line.startswith(' STEP=') or line.startswith('STEP=') or line.startswith(' STEP =') or line.startswith(' STEP =') or line.startswith('STEP ='): print(' STEP=record_freq') else: print(line.replace('/seed_" & seed & "',''), end='')
donovanr/weighted-ensemble-izer
weightedensemblizer/file_io.py
Python
gpl-2.0
5,710
[ "MCell" ]
5e408f2ed9a0ee98055bbf305fcda2b576c6b350a38612a61a4192c3b8d0e93d
#!/usr/bin/env python ''' Optimize the geometry of excited states using CASSCF or CASCI Note when optiming the excited states, states may flip and this may cause convergence issue in geometry optimizer. ''' from pyscf import gto from pyscf import scf, mcscf mol = gto.Mole() mol.atom="N; N 1, 1.1" mol.basis= "6-31g" mol.build() mf = scf.RHF(mol).run() # # 1. Geometry optimization over a specific state. # # Targeting at one excited state mc = mcscf.CASCI(mf, 4,4) mc.state_specific_(2) excited_grad = mc.nuc_grad_method().as_scanner() mol1 = excited_grad.optimizer().kernel() # Code above is equivalent to mc = mcscf.CASCI(mf, 4,4) mc.fcisolver.nstates = 3 excited_grad = mc.nuc_grad_method().as_scanner(state=2) mol1 = excited_grad.optimizer().kernel() # CASSCF for one excited state mc = mcscf.CASSCF(mf, 4,4) mc.state_specific_(2) excited_grad = mc.nuc_grad_method().as_scanner() mol1 = excited_grad.optimizer().kernel() # # 2. Geometry optimization over an averaged state. # Note the state-averaged gradients are optimized. # mc = mcscf.CASCI(mf, 4,4) mc.state_average_([0.25, 0.25, 0.25, 0.25]) excited_grad = mc.nuc_grad_method().as_scanner() mol1 = excited_grad.optimizer().kernel() mc = mcscf.CASSCF(mf, 4,4) mc.state_average_([0.25, 0.25, 0.25, 0.25]) excited_grad = mc.nuc_grad_method().as_scanner() mol1 = excited_grad.optimizer().kernel() # # 3. Geometry optimization for mixed FCI solvers. # Note the state-averaged gradients are optimized. # import copy mc = mcscf.CASSCF(mf, 4,4) solver1 = mc.fcisolver solver2 = copy.copy(mc.fcisolver) solver2.spin = 2 mc = mcscf.addons.state_average_mix_(mc, [solver1, solver2], (.5, .5)) excited_grad = mc.nuc_grad_method().as_scanner() mol1 = excited_grad.optimizer().kernel()
gkc1000/pyscf
examples/geomopt/12-mcscf_excited_states.py
Python
apache-2.0
1,744
[ "PySCF" ]
08726ba82b028169d1f964c9b4bee14ad6b500aa8d245023c18781b17433fdd8
from __future__ import print_function, division import os from pathlib import Path from datetime import datetime import inspect import warnings import platform import numpy as np import pandas as pd import pyemu from ..pyemu_warnings import PyemuWarning import copy import string # the tolerable percent difference (100 * (max - min)/mean) # used when checking that constant and zone type parameters are in fact constant (within # a given zone) DIRECT_PAR_PERCENT_DIFF_TOL = 1.0 def _get_datetime_from_str(sdt): # could be expanded if someone is feeling clever. if isinstance(sdt, str): PyemuWarning( "Assuming passed reference start date time is " "year first str {0}".format(sdt) ) sdt = pd.to_datetime(sdt, yearfirst=True) assert isinstance(sdt, pd.Timestamp), "Error interpreting start_datetime" return sdt def _check_var_len(var, n, fill=None): if not isinstance(var, list): var = [var] if fill is not None: if fill == "first": fill = var[0] elif fill == "last": fill = var[-1] nv = len(var) if nv < n: var.extend([fill for _ in range(n - nv)]) return var class PstFrom(object): """construct high-dimensional PEST(++) interfaces with all the bells and whistles Args: original_d (`str`): the path to a complete set of model input and output files new_d (`str`): the path to where the model files and PEST interface files will be copied/built longnames (`bool`): flag to use longer-than-PEST-likes parameter and observation names. Default is True remove_existing (`bool`): flag to destroy any existing files and folders in `new_d`. Default is False spatial_reference (varies): an object that faciliates geo-locating model cells based on index. Default is None zero_based (`bool`): flag if the model uses zero-based indices, Default is True start_datetime (`str`): a string that can be case to a datatime instance the represents the starting datetime of the model tpl_subfolder (`str`): option to write template files to a subfolder within ``new_d``. Default is False (write template files to ``new_d``). chunk_len (`int`): the size of each "chunk" of files to spawn a multiprocessing.Pool member to process. On windows, beware setting this much smaller than 50 because of the overhead associated with spawning the pool. This value is added to the call to `apply_list_and_array_pars`. Default is 50 echo (`bool`): flag to echo logger messages to the screen. Default is True Note: This is the way... Example:: pf = PstFrom("path_to_model_files","new_dir_with_pest_stuff",start_datetime="1-1-2020") pf.add_parameters("hk.dat") pf.add_observations("heads.csv") pf.build_pst("pest.pst") pe = pf.draw(100) pe.to_csv("prior.csv") """ def __init__( self, original_d, new_d, longnames=True, remove_existing=False, spatial_reference=None, zero_based=True, start_datetime=None, tpl_subfolder=None, chunk_len=50, echo=True, ): self.original_d = Path(original_d) self.new_d = Path(new_d) self.original_file_d = None self.mult_file_d = None self.tpl_d = self.new_d if tpl_subfolder is not None: self.tpl_d = Path(self.new_d, tpl_subfolder) self.remove_existing = bool(remove_existing) self.zero_based = bool(zero_based) self._spatial_reference = spatial_reference self._spatial_ref_xarray = None self._spatial_ref_yarray = None self.spatial_reference = None if start_datetime is not None: start_datetime = _get_datetime_from_str(start_datetime) self.start_datetime = start_datetime self.geostruct = None self.par_struct_dict = {} # self.par_struct_dict_l = {} self.mult_files = [] self.org_files = [] self.par_dfs = [] self.unique_parnmes = set() # set of unique parameters added so far through add_parameters method self.obs_dfs = [] self.py_run_file = "forward_run.py" self.mod_command = "python {0}".format(self.py_run_file) self.pre_py_cmds = [] self.pre_sys_cmds = [] # a list of preprocessing commands to add to # the forward_run.py script commands are executed with os.system() # within forward_run.py. self.mod_py_cmds = [] self.mod_sys_cmds = [] self.post_py_cmds = [] self.post_sys_cmds = [] # a list of post-processing commands to add to # the forward_run.py script. Commands are executed with os.system() # within forward_run.py. self.extra_py_imports = [] self.tmp_files = [] self.tpl_filenames, self.input_filenames = [], [] self.ins_filenames, self.output_filenames = [], [] self.longnames = bool(longnames) self.logger = pyemu.Logger("PstFrom.log", echo=echo) self.logger.statement("starting PstFrom process") self._prefix_count = {} self.get_xy = None self.add_pars_callcount = 0 self.ijwarned = {} self.initialize_spatial_reference() self._setup_dirs() self._parfile_relations = [] self._pp_facs = {} self.pst = None self._function_lines_list = [] # each function is itself a list of lines self.direct_org_files = [] self.ult_ubound_fill = 1.0e30 self.ult_lbound_fill = -1.0e30 self.chunk_len = int(chunk_len) @property def parfile_relations(self): """build up a container of parameter file information. Called programmatically...""" if isinstance(self._parfile_relations, list): pr = pd.concat(self._parfile_relations, ignore_index=True) else: pr = self._parfile_relations # quick checker for name, g in pr.groupby("model_file"): if g.sep.nunique() > 1: self.logger.warn( "separator mismatch for {0}, seps passed {1}" "".format(name, [s for s in g.sep.unique()]) ) if g.fmt.nunique() > 1: self.logger.warn( "format mismatch for {0}, fmt passed {1}" "".format(name, [f for f in g.fmt.unique()]) ) # if ultimate parameter bounds have been set for only one instance # of the model file we need to pass this through to all ubound = g.apply( lambda x: pd.Series( { k: v for n, c in enumerate(x.use_cols) for k, v in [["ubound{0}".format(c), x.upper_bound[n]]] } ) if x.use_cols is not None else pd.Series({k: v for k, v in [["ubound", x.upper_bound]]}), axis=1, ) if ubound.nunique(0, False).gt(1).any(): ub_min = ubound.min().fillna(self.ult_ubound_fill).to_dict() pr.loc[g.index, "upper_bound"] = g.use_cols.apply( lambda x: [ub_min["ubound{0}".format(c)] for c in x] if x is not None else ub_min["ubound"] ) # repeat for lower bounds lbound = g.apply( lambda x: pd.Series( { k: v for n, c in enumerate(x.use_cols) for k, v in [["lbound{0}".format(c), x.lower_bound[n]]] } ) if x.use_cols is not None else pd.Series({k: v for k, v in [["lbound", x.lower_bound]]}), axis=1, ) if lbound.nunique(0, False).gt(1).any(): lb_max = lbound.max().fillna(self.ult_lbound_fill).to_dict() pr.loc[g.index, "lower_bound"] = g.use_cols.apply( lambda x: [lb_max["lbound{0}".format(c)] for c in x] if x is not None else lb_max["lbound"] ) pr["zero_based"] = self.zero_based return pr def _generic_get_xy(self, args, **kwargs): i, j = self.parse_kij_args(args, kwargs) return i, j def _dict_get_xy(self, arg, **kwargs): if isinstance(arg, list): arg = tuple(arg) xy = self._spatial_reference.get(arg, None) if xy is None: arg_len = None try: arg_len = len(arg) except Exception as e: self.logger.lraise( "Pstfrom._dict_get_xy() error getting xy from arg:'{0}' - no len support".format( arg ) ) if arg_len == 1: xy = self._spatial_reference.get(arg[0], None) elif arg_len == 2 and arg[0] == 0: xy = self._spatial_reference.get(arg[1], None) elif arg_len == 2 and arg[1] == 0: xy = self._spatial_reference.get(arg[0], None) else: self.logger.lraise( "Pstfrom._dict_get_xy() error getting xy from arg:'{0}'".format(arg) ) if xy is None: self.logger.lraise( "Pstfrom._dict_get_xy() error getting xy from arg:'{0}' - still None".format( arg ) ) return xy[0], xy[1] def _flopy_sr_get_xy(self, args, **kwargs): i, j = self.parse_kij_args(args, kwargs) if all([ij is None for ij in [i, j]]): return i, j else: return ( self._spatial_reference.xcentergrid[i, j], self._spatial_reference.ycentergrid[i, j], ) def _flopy_mg_get_xy(self, args, **kwargs): i, j = self.parse_kij_args(args, kwargs) if all([ij is None for ij in [i, j]]): return i, j else: if self._spatial_ref_xarray is None: self._spatial_ref_xarray = self._spatial_reference.xcellcenters self._spatial_ref_yarray = self._spatial_reference.ycellcenters return (self._spatial_ref_xarray[i, j], self._spatial_ref_yarray[i, j]) def parse_kij_args(self, args, kwargs): """parse args into kij indices. Called programmatically""" if len(args) >= 2: ij_id = None if "ij_id" in kwargs: ij_id = kwargs["ij_id"] if ij_id is not None: i, j = [args[ij] for ij in ij_id] else: if not self.ijwarned[self.add_pars_callcount]: self.logger.warn( ( "get_xy() warning: position of i and j in index_cols " "not specified, assume (i,j) are final two entries in " "index_cols." ) ) self.ijwarned[self.add_pars_callcount] = True # assume i and j are the final two entries in index_cols i, j = args[-2], args[-1] else: if not self.ijwarned[self.add_pars_callcount]: self.logger.warn( ( "get_xy() warning: need locational information " "(e.g. i,j) to generate xy, " "insufficient index cols passed to interpret: {}" "" ).format(str(args)) ) self.ijwarned[self.add_pars_callcount] = True i, j = None, None return i, j def initialize_spatial_reference(self): """process the spatial reference argument. Called programmatically""" if self._spatial_reference is None: self.get_xy = self._generic_get_xy elif hasattr(self._spatial_reference, "xcentergrid") and hasattr( self._spatial_reference, "ycentergrid" ): self.get_xy = self._flopy_sr_get_xy elif hasattr(self._spatial_reference, "xcellcenters") and hasattr( self._spatial_reference, "ycellcenters" ): # support modelgrid style cell locs self._spatial_reference.xcentergrid = self._spatial_reference.xcellcenters self._spatial_reference.ycentergrid = self._spatial_reference.ycellcenters self.get_xy = self._flopy_mg_get_xy elif isinstance(self._spatial_reference, dict): self.logger.statement("dictionary-based spatial reference detected...") self.get_xy = self._dict_get_xy else: self.logger.lraise( "initialize_spatial_reference() error: " "unsupported spatial_reference" ) self.spatial_reference = self._spatial_reference def write_forward_run(self): """write the forward run script. Called by build_pst()""" # update python commands with system style commands for alist, ilist in zip( [self.pre_py_cmds, self.mod_py_cmds, self.post_py_cmds], [self.pre_sys_cmds, self.mod_sys_cmds, self.post_sys_cmds], ): if ilist is None: continue if not isinstance(ilist, list): ilist = [ilist] for cmd in ilist: new_sys_cmd = "pyemu.os_utils.run(r'{0}')\n".format(cmd) if new_sys_cmd in alist: self.logger.warn( "sys_cmd '{0}' already in sys cmds, skipping...".format( new_sys_cmd ) ) else: self.logger.statement("forward_run line:{0}".format(new_sys_cmd)) alist.append(new_sys_cmd) with open(self.new_d / self.py_run_file, "w") as f: f.write( "import os\nimport multiprocessing as mp\nimport numpy as np" + "\nimport pandas as pd\n" ) f.write("import pyemu\n") for ex_imp in self.extra_py_imports: f.write("import {0}\n".format(ex_imp)) for func_lines in self._function_lines_list: f.write("\n") f.write("# function added thru PstFrom.add_py_function()\n") for func_line in func_lines: f.write(func_line) f.write("\n") f.write("def main():\n") f.write("\n") s = " " for tmp_file in self.tmp_files: f.write(s + "try:\n") f.write(s + " os.remove(r'{0}')\n".format(tmp_file)) f.write(s + "except Exception as e:\n") f.write( s + " print(r'error removing tmp file:{0}')\n".format(tmp_file) ) for line in self.pre_py_cmds: f.write(s + line + "\n") for line in self.mod_py_cmds: f.write(s + line + "\n") for line in self.post_py_cmds: f.write(s + line + "\n") f.write("\n") f.write("if __name__ == '__main__':\n") f.write(" mp.freeze_support()\n main()\n\n") def _pivot_par_struct_dict(self): struct_dict = {} for gs, gps in self.par_struct_dict.items(): par_dfs = [] for _, l in gps.items(): df = pd.concat(l) if "timedelta" in df.columns: df.loc[:, "y"] = 0 # df.loc[:, "x"] = df.timedelta.apply(lambda x: x.days) par_dfs.append(df) struct_dict[gs] = par_dfs return struct_dict def _rename_par_struct_dict(self, mapdict): for gs, gps in self.par_struct_dict.items(): df_dict = {} for k, li in gps.items(): tdf = [] for df in li: df.parnme.update(mapdict) df = df.rename(index=mapdict) tdf.append(df) df_dict[k] = tdf self.par_struct_dict[gs] = df_dict def build_prior( self, fmt="ascii", filename=None, droptol=None, chunk=None, sigma_range=6 ): """Build the prior parameter covariance matrix Args: fmt (`str`): the file format to save to. Default is "ASCII", can be "binary", "coo", or "none" filename (`str`): the filename to save the cov to droptol (`float`): absolute value of prior cov entries that are smaller than `droptol` are treated as zero. chunk (`int`): number of entries to write to binary/coo at once. Default is None (write all elements at once sigma_range (`int`): number of standard deviations represented by parameter bounds. Default is 6 (99% confidence). 4 would be approximately 95% confidence bounds Returns: `pyemu.Cov`: the prior parameter covariance matrix Note: This method processes parameters by group names For really large numbers of parameters (>30K), this method will cause memory errors. Luckily, in most cases, users only want this matrix to generate a prior parameter ensemble and the `PstFrom.draw()` is a better choice... """ struct_dict = self._pivot_par_struct_dict() self.logger.log("building prior covariance matrix") if len(struct_dict) > 0: cov = pyemu.helpers.geostatistical_prior_builder( self.pst, struct_dict=struct_dict, sigma_range=sigma_range ) else: cov = pyemu.Cov.from_parameter_data(self.pst, sigma_range=sigma_range) if filename is None: filename = self.pst.filename.with_suffix(".prior.cov") if fmt != "none": self.logger.statement( "saving prior covariance matrix to file {0}".format(filename) ) if fmt == "ascii": cov.to_ascii(filename) elif fmt == "binary": cov.to_binary(filename, droptol=droptol, chunk=chunk) elif fmt == "uncfile": cov.to_uncfile(filename) elif fmt == "coo": cov.to_coo(filename, droptol=droptol, chunk=chunk) self.logger.log("building prior covariance matrix") return cov def draw(self, num_reals=100, sigma_range=6, use_specsim=False, scale_offset=True): """Draw a parameter ensemble from the distribution implied by the initial parameter values in the control file and the prior parameter covariance matrix. Args: num_reals (`int`): the number of realizations to draw sigma_range (`int`): number of standard deviations represented by parameter bounds. Default is 6 (99% confidence). 4 would be approximately 95% confidence bounds use_specsim (`bool`): flag to use spectral simulation for grid-scale pars (highly recommended). Default is False scale_offset (`bool`): flag to apply scale and offset to parameter bounds before calculating prior variance. Dfault is True. If you are using non-default scale and/or offset and you get an exception during draw, try changing this value to False. Returns: `pyemu.ParameterEnsemble`: a prior parameter ensemble Note: This method draws by parameter group If you are using grid-style parameters, please use spectral simulation (`use_specsim=True`) """ self.logger.log("drawing realizations") if self.pst.npar_adj == 0: self.logger.warn("no adjustable parameters, nothing to draw...") return # precondition {geostruct:{group:df}} dict to {geostruct:[par_dfs]} struct_dict = self._pivot_par_struct_dict() # list for holding grid style groups gr_pe_l = [] if use_specsim: if not pyemu.geostats.SpecSim2d.grid_is_regular( self.spatial_reference.delr, self.spatial_reference.delc ): self.logger.lraise( "draw() error: can't use spectral simulation with irregular grid" ) self.logger.log("spectral simulation for grid-scale pars") # loop over geostructures defined in PestFrom object # (setup through add_parameters) for geostruct, par_df_l in struct_dict.items(): par_df = pd.concat(par_df_l) # force to single df par_df = par_df.loc[par_df.partype == "grid", :] if "i" in par_df.columns: # need 'i' and 'j' for specsim grd_p = pd.notna(par_df.i) else: grd_p = np.array([0]) # if there are grid pars (also grid pars with i,j info) if grd_p.sum() > 0: # select pars to use specsim for gr_df = par_df.loc[grd_p] gr_df = gr_df.astype({"i": int, "j": int}) # make sure int # (won't be if there were nans in concatenated df) if len(gr_df) > 0: # get specsim object for this geostruct ss = pyemu.geostats.SpecSim2d( delx=self.spatial_reference.delr, dely=self.spatial_reference.delc, geostruct=geostruct, ) # specsim draw (returns df) gr_pe1 = ss.grid_par_ensemble_helper( pst=self.pst, gr_df=gr_df, num_reals=num_reals, sigma_range=sigma_range, logger=self.logger, ) # append to list of specsim drawn pars gr_pe_l.append(gr_pe1) # rebuild struct_dict entry for this geostruct # to not include specsim pars struct_dict[geostruct] = [] # loop over all in list associated with geostruct for p_df in par_df_l: # if pars are not in the specsim pars just created # assign them to this struct_dict entry # needed if none specsim pars are linked to same geostruct if not p_df.index.isin(gr_df.index).all(): struct_dict[geostruct].append(p_df) self.logger.log("spectral simulation for grid-scale pars") # draw remaining pars based on their geostruct self.logger.log("Drawing non-specsim pars") pe = pyemu.helpers.geostatistical_draws( self.pst, struct_dict=struct_dict, num_reals=num_reals, sigma_range=sigma_range, scale_offset=scale_offset, ) self.logger.log("Drawing non-specsim pars") if len(gr_pe_l) > 0: gr_par_pe = pd.concat(gr_pe_l, axis=1) pe.loc[:, gr_par_pe.columns] = gr_par_pe.values # par_ens = pyemu.ParameterEnsemble(pst=self.pst, df=pe) self.logger.log("drawing realizations") return pe def build_pst(self, filename=None, update=False, version=1): """Build control file from i/o files in PstFrom object. Warning: This builds a pest control file from scratch, overwriting anything already in self.pst object and anything already writen to `filename` Args: filename (`str`): the filename to save the control file to. If None, the name is formed from the `PstFrom.original_d` ,the orginal directory name from which the forward model was extracted. Default is None. The control file is saved in the `PstFrom.new_d` directory. update (`bool`) or (str): flag to add to existing Pst object and rewrite. If string {'pars', 'obs'} just update respective components of Pst. Default is False - build from PstFrom components. version (`int`): control file version to write, Default is 1 Note: This builds a pest control file from scratch, overwriting anything already in self.pst object and anything already writen to `filename` The new pest control file is assigned an NOPTMAX value of 0 """ # import cProfile # pd.set_option('display.max_rows', 500) # pd.set_option('display.max_columns', 500) # pd.set_option('display.width', 1000) par_data_cols = pyemu.pst_utils.pst_config["par_fieldnames"] obs_data_cols = pyemu.pst_utils.pst_config["obs_fieldnames"] if update: if self.pst is None: self.logger.warn( "Can't update Pst object not initialised. " "Setting update to False" ) update = False else: if filename is None: filename = get_filepath(self.new_d, self.pst.filename) else: if filename is None: filename = Path(self.new_d, self.original_d.name).with_suffix(".pst") filename = get_filepath(self.new_d, filename) # if os.path.dirname(filename) in ["", "."]: # filename = os.path.join(self.new_d, filename) if update: pst = self.pst if update is True: update = {"pars": False, "obs": False} elif isinstance(update, str): update = {update: True} elif isinstance(update, (set, list)): update = {s: True for s in update} uupdate = True else: update = {"pars": False, "obs": False} uupdate = False pst = pyemu.Pst(filename, load=False) # TODO should this be under an if:? incase updating and prior info has been set pst.prior_information = pst.null_prior.merge(pd.DataFrame( data=[], columns=pst.prior_fieldnames)) if "pars" in update.keys() or not uupdate: if len(self.par_dfs) > 0: # parameter data from object par_data = pd.concat(self.par_dfs).loc[:, par_data_cols] # info relating parameter multiplier files to model input files parfile_relations = self.parfile_relations parfile_relations.to_csv(self.new_d / "mult2model_info.csv") if not any( ["apply_list_and_array_pars" in s for s in self.pre_py_cmds] ): self.pre_py_cmds.insert( 0, "pyemu.helpers.apply_list_and_array_pars(" "arr_par_file='mult2model_info.csv',chunk_len={0})".format( self.chunk_len ), ) else: par_data = pyemu.pst_utils._populate_dataframe( [], pst.par_fieldnames, pst.par_defaults, pst.par_dtype ) # set parameter data # some pre conditioning to support rentry here is more add_par # calls are made with update/rebuild pst shtmx = 0 gshtmx = 0 if pst.parameter_data is not None: # copy existing par data (incase it has been edited) par_data_orig = pst.parameter_data.copy() if "longname" in par_data_orig.columns: # Support existing long names mapping par_data_orig = par_data_orig.set_index( "longname") # starting point for updated mapping shtmx = par_data_orig.parnme.str.strip('p').astype(int).max() + 1 gshtmx = par_data_orig.pargp.str.strip('pg').astype(int).max() + 1 # index of new pars (might need this later) new_par_data = par_data.index.difference(par_data_orig.index) else: new_par_data = slice(None) # build or update par data pst.parameter_data = pd.concat( [pst.parameter_data, par_data.loc[new_par_data]], axis=0) # pst.template_files = self.tpl_filenames # pst.input_files = self.input_filenames pst.model_input_data = pd.DataFrame( {"pest_file": self.tpl_filenames, "model_file": self.input_filenames}, index=self.tpl_filenames, ) # rename pars and obs in case short names are desired if not self.longnames: self.logger.log("Converting parameters to shortnames") # pull out again for shorthand access par_data = pst.parameter_data # new pars will not be mapped, start this mapping npd = par_data.loc[new_par_data] par_data.loc[npd.index, 'longname'] = npd.parnme # get short names (using existing names as index starting point) par_data.loc[npd.index, "shortname"] = [ 'p' + f"{i}" for i in range(shtmx, shtmx+len(npd)) ] # set to dict parmap = par_data.loc[npd.index, "shortname"].to_dict() # rename parnames and propagate to tpls etc. self.logger.log("Renaming parameters for shortnames") pst.rename_parameters(parmap, pst_path=self.new_d) self.logger.log("Renaming parameters for shortnames") # rename in struct dicts self._rename_par_struct_dict(parmap) # save whole shortname-longname mapping (will over write previous) par_data.set_index("shortname")["longname"].to_csv( filename.with_name('parlongname.map')) npd.index = npd.index.map(parmap) # build group mapping df pargpmap = pd.DataFrame(npd.pargp.unique(), columns=['longname']) # shortnames from using previous a starting point (if existing) pargpmap["shortname"] = "pg" + (pargpmap.index+gshtmx).astype(str) pargpmap_dict = pargpmap.set_index('longname').shortname.to_dict() par_data.loc[npd.index, "pglong"] = npd.pargp par_data.loc[npd.index, 'pargp'] = npd.pargp.map(pargpmap_dict) par_data.groupby('pargp').pglong.first().to_csv( filename.with_name('pglongname.map')) self.logger.log("Converting parameters to shortnames") if "obs" in update.keys() or not uupdate: if len(self.obs_dfs) > 0: obs_data = pd.concat(self.obs_dfs).loc[:, obs_data_cols] else: obs_data = pyemu.pst_utils._populate_dataframe( [], pst.obs_fieldnames, pst.obs_defaults, pst.obs_dtype ) obs_data.loc[:, "obsnme"] = [] obs_data.index = [] # set observation data # some pre conditioning to support rentry here is more add_obs # calls are made with update/rebuild pst shtmx = 0 gshtmx = 0 if pst.observation_data is not None: # copy existing obs data (incase it has been edited) obs_data_orig = pst.observation_data.copy() if "longname" in obs_data_orig.columns: # Support existing long names mapping obs_data_orig = obs_data_orig.set_index( "longname") # starting point for updated mapping shtmx = obs_data_orig.obsnme.str.strip('ob').astype(int).max() + 1 gshtmx = obs_data_orig.obgnme.str.strip('obg').astype(int).max() + 1 # index of new obs (might need this later) new_obs_data = obs_data.index.difference(obs_data_orig.index) else: new_obs_data = slice(None) # build or update obs data pst.observation_data = pd.concat( [pst.observation_data, obs_data.loc[new_obs_data]], axis=0) # pst.instruction_files = self.ins_filenames # pst.output_files = self.output_filenames pst.model_output_data = pd.DataFrame( {"pest_file": self.ins_filenames, "model_file": self.output_filenames}, index=self.ins_filenames, ) # rename pars and obs in case short names are desired if not self.longnames: # pr = cProfile.Profile() # pr.enable() self.logger.log("Converting observations to shortnames") # pull out again for shorthand access obs_data = pst.observation_data # new obs will not be mapped so start this mapping nod = obs_data.loc[new_obs_data] obs_data.loc[nod.index, "longname"] = nod.obsnme # get short names (using existing names as index starting point) obs_data.loc[nod.index, "shortname"] = [ 'ob' + f"{i}" for i in range(shtmx, shtmx+len(nod)) ] obsmap = obs_data.loc[nod.index, "shortname"].to_dict() # rename obsnames and propagate to ins files self.logger.log("Renaming observations for shortnames") pst.rename_observations(obsmap, pst_path=self.new_d) self.logger.log("Renaming observations for shortnames") obs_data.set_index("shortname")["longname"].to_csv( filename.with_name('obslongname.map')) nod.index = nod.index.map(obsmap) # build group mapping df obgpmap = pd.DataFrame(nod.obgnme.unique(), columns=['longname']) # shortnames from using previous a starting point (if existing) obgpmap["shortname"] = "obg" + (obgpmap.index+gshtmx).astype(str) obgpmap_dict = obgpmap.set_index('longname').shortname.to_dict() obs_data.loc[nod.index, "oglong"] = nod.obgnme obs_data.loc[nod.index, 'obgnme'] = nod.obgnme.map(obgpmap_dict) obs_data.groupby('obgnme').oglong.first().to_csv( filename.with_name('oglongname.map')) self.logger.log("Converting observations to shortnames") # pr.disable() # pr.print_stats(sort="cumtime") # obs_data.sort_index(inplace=True) #TODO if not uupdate: pst.model_command = self.mod_command pst.control_data.noptmax = 0 self.pst = pst self.pst.write(filename, version=version) self.write_forward_run() pst.try_parse_name_metadata() return pst def _setup_dirs(self): self.logger.log("setting up dirs") if not os.path.exists(self.original_d): self.logger.lraise(f"original_d '{self.original_d}' not found") if not os.path.isdir(self.original_d): self.logger.lraise(f"original_d '{self.original_d}' is not a directory") if self.new_d.exists(): if self.remove_existing: self.logger.log(f"removing existing new_d '{self.new_d}'") pyemu.os_utils._try_remove_existing(self.new_d) self.logger.log(f"removing existing new_d '{self.new_d}'") else: self.logger.lraise( f"new_d '{self.new_d}' already exists " "- use remove_existing=True" ) self.logger.log( f"copying original_d '{self.original_d}' to new_d '{self.new_d}'" ) pyemu.os_utils._try_copy_dir(self.original_d, self.new_d) self.logger.log( f"copying original_d '{self.original_d}' to new_d '{self.new_d}'" ) self.original_file_d = self.new_d / "org" if self.original_file_d.exists(): self.logger.lraise(f"'org' subdir already exists in new_d '{self.new_d}'") self.original_file_d.mkdir(exist_ok=True) self.mult_file_d = self.new_d / "mult" if self.mult_file_d.exists(): self.logger.lraise(f"'mult' subdir already exists in new_d '{self.new_d}'") self.mult_file_d.mkdir(exist_ok=True) self.tpl_d.mkdir(exist_ok=True) self.logger.log("setting up dirs") def _par_prep( self, filenames, index_cols, use_cols, fmts=None, seps=None, skip_rows=None, c_char=None, ): # todo: cast str column names, index_cols and use_cols to lower if str? # todo: check that all index_cols and use_cols are the same type file_dict = {} fmt_dict = {} sep_dict = {} skip_dict = {} ( filenames, fmts, seps, skip_rows, index_cols, use_cols, ) = self._prep_arg_list_lengths( filenames, fmts, seps, skip_rows, index_cols, use_cols ) storehead = None if index_cols is not None: for filename, sep, fmt, skip in zip(filenames, seps, fmts, skip_rows): # cast to pathlib.Path instance # input file path may or may not include original_d # input_filepath = get_filepath(self.original_d, filename) rel_filepath = get_relative_filepath(self.original_d, filename) dest_filepath = self.new_d / rel_filepath # data file in dest_ws/org/ folder org_file = self.original_file_d / rel_filepath.name self.logger.log(f"loading list-style {dest_filepath}") df, storehead, _ = self._load_listtype_file( rel_filepath, index_cols, use_cols, fmt, sep, skip, c_char ) # Currently just passing through comments in header (i.e. before the table data) stkeys = np.array( sorted(storehead.keys()) ) # comments line numbers as sorted array if ( stkeys.size > 0 and stkeys.min() == 0 ): # TODO pass comment_char through to par_file_rel so mid-table comments can be preserved skip = 1 + np.sum(np.diff(stkeys) == 1) # # looping over model input filenames if fmt.lower() == "free": if sep is None: sep = " " if rel_filepath.suffix.lower() == ".csv": sep = "," if df.columns.is_integer(): hheader = False else: hheader = df.columns self.logger.statement( f"loaded list-style '{dest_filepath}' of shape {df.shape}" ) # TODO BH: do we need to be careful of the format of the model # files? -- probs not necessary for the version in # original_file_d - but for the eventual product model file, # it might be format sensitive - yuck # Update, BH: I think the `original files` saved can always # be comma delim --they are never directly used # as model inputs-- as long as we pass the required model # input file format (and sep), right? # write orig version of input file to `org` (e.g.) dir # make any subfolders if they don't exist # org_path = Path(self.original_file_d, rel_file_path.parent) # org_path.mkdir(exist_ok=True) if len(storehead) != 0: kwargs = {} if "win" in platform.platform().lower(): kwargs = {"line_terminator": "\n"} with open(org_file, "w") as fp: lc = 0 fr = 0 for key in sorted(storehead.keys()): if key > lc: self.logger.warn( "Detected mid-table comment " f"on line {key + 1} tabular model file, " "comment will be lost" ) lc += 1 continue # TODO if we want to preserve mid-table comments, # these lines might help - will also need to # pass comment_char through so it can be # used by the apply methods # to = key - lc # df.iloc[fr:to].to_csv( # fp, sep=',', mode='a', header=hheader, # todo - presence of header may cause an issue with this # **kwargs) # lc += to - fr # fr = to fp.write(storehead[key]) fp.flush() lc += 1 if lc < len(df): df.iloc[fr:].to_csv( fp, sep=",", mode="a", header=hheader, index=False, **kwargs, ) else: df.to_csv( org_file, index=False, sep=",", header=hheader, ) file_dict[rel_filepath] = df fmt_dict[rel_filepath] = fmt sep_dict[rel_filepath] = sep skip_dict[rel_filepath] = skip self.logger.log(f"loading list-style {dest_filepath}") # check for compatibility fnames = list(file_dict.keys()) for i in range(len(fnames)): for j in range(i + 1, len(fnames)): if file_dict[fnames[i]].shape[1] != file_dict[fnames[j]].shape[1]: self.logger.lraise( f"shape mismatch for array style, '{fnames[i]}' " f"shape {file_dict[fnames[i]].shape[1]} != " f"'{fnames[j]}' " f"shape {file_dict[fnames[j]].shape[1]}" ) else: # load array type files # loop over model input files for input_filena, sep, fmt, skip in zip(filenames, seps, fmts, skip_rows): # cast to pathlib.Path instance # input file path may or may not include original_d input_filena = get_filepath(self.original_d, input_filena) if fmt.lower() == "free": # cast to string to work with pathlib objects if input_filena.suffix.lower() == ".csv": if sep is None: sep = "," else: # TODO - or not? raise NotImplementedError( "Only free format array par files currently supported" ) # file path relative to model workspace rel_filepath = input_filena.relative_to(self.original_d) dest_filepath = self.new_d / rel_filepath self.logger.log(f"loading array {dest_filepath}") if not dest_filepath.exists(): self.logger.lraise(f"par filename '{dest_filepath}' not found ") # read array type input file arr = np.loadtxt(dest_filepath, delimiter=sep, ndmin=2) self.logger.log(f"loading array {dest_filepath}") self.logger.statement( f"loaded array '{input_filena}' of shape {arr.shape}" ) # save copy of input file to `org` dir # make any subfolders if they don't exist np.savetxt(self.original_file_d / rel_filepath.name, arr) file_dict[rel_filepath] = arr fmt_dict[rel_filepath] = fmt sep_dict[rel_filepath] = sep skip_dict[rel_filepath] = skip # check for compatibility fnames = list(file_dict.keys()) for i in range(len(fnames)): for j in range(i + 1, len(fnames)): if file_dict[fnames[i]].shape != file_dict[fnames[j]].shape: self.logger.lraise( f"shape mismatch for array style, '{fnames[i]}' " f"shape {file_dict[fnames[i]].shape[1]} != " f"'{fnames[j]}' " f"shape {file_dict[fnames[j]].shape[1]}" ) return ( index_cols, use_cols, file_dict, fmt_dict, sep_dict, skip_dict, storehead, ) def _next_count(self, prefix): if prefix not in self._prefix_count: self._prefix_count[prefix] = 0 else: self._prefix_count[prefix] += 1 return self._prefix_count[prefix] def add_py_function( self, file_name, call_str=None, is_pre_cmd=True, function_name=None ): """add a python function to the forward run script Args: file_name (`str`): a python source file call_str (`str`): the call string for python function in `file_name`. `call_str` will be added to the forward run script, as is. is_pre_cmd (`bool` or `None`): flag to include `call_str` in PstFrom.pre_py_cmds. If False, `call_str` is added to PstFrom.post_py_cmds instead. If passed as `None`, then the function `call_str` is added to the forward run script but is not called. Default is True. function_name (`str`): DEPRECATED, used `call_str` Returns: None Note: `call_str` is expected to reference standalone a function that contains all the imports it needs or these imports should have been added to the forward run script through the `PstFrom.py_imports` list. This function adds the `call_str` call to the forward run script (either as a pre or post command). It is up to users to make sure `call_str` is a valid python function call that includes the parentheses and requisite arguments This function expects "def " + `function_name` to be flushed left at the outer most indentation level Example:: pf = PstFrom() # add the function "mult_well_function" from the script file "preprocess.py" as a # command to run before the model is run pf.add_py_function("preprocess.py", "mult_well_function(arg1='userarg')", is_pre_cmd = True) # add the post processor function "made_it_good" from the script file "post_processors.py" pf.add_py_function("post_processors.py","make_it_good(()",is_pre_cmd=False) """ if function_name is not None: warnings.warn( "add_py_function(): 'function_name' argument is deprecated, " "use 'call_str' instead", DeprecationWarning, ) if call_str is None: call_str = function_name if call_str is None: self.logger.lraise( "add_py_function(): No function call string passed in arg " "'call_str'" ) if not os.path.exists(file_name): self.logger.lraise( "add_py_function(): couldnt find python source file '{0}'".format( file_name ) ) if "(" not in call_str or ")" not in call_str: self.logger.lraise( "add_py_function(): call_str '{0}' missing paretheses".format(call_str) ) function_name = call_str[ : call_str.find("(") ] # strip to first occurance of '(' func_lines = [] search_str = "def " + function_name + "(" abet_set = set(string.ascii_uppercase) abet_set.update(set(string.ascii_lowercase)) with open(file_name, "r") as f: while True: line = f.readline() if line == "": self.logger.lraise( "add_py_function(): EOF while searching for function '{0}'".format( search_str ) ) if line.startswith( search_str ): # case sens and no strip since 'def' should be flushed left func_lines.append(line) while True: line = f.readline() if line == "": break if line[0] in abet_set: break func_lines.append(line) break self._function_lines_list.append(func_lines) if is_pre_cmd is True: self.pre_py_cmds.append(call_str) elif is_pre_cmd is False: self.post_py_cmds.append(call_str) else: self.logger.warn( "add_py_function() command: {0} is not being called directly".format( call_str ) ) def _process_array_obs( self, out_filename, ins_filename, prefix, ofile_sep, ofile_skip, zone_array, ): """private method to setup observations for an array-style file Args: out_filename (`str`): the output array file ins_filename (`str`): the instruction file to create prefix (`str`): the prefix to add to the observation names and also to use as the observation group name. ofile_sep (`str`): the separator in the output file. This is currently just a placeholder arg, only whitespace-delimited files are supported ofile_skip (`int`): number of header and/or comment lines to skip at the top of the output file zone_array (numpy.ndarray): an integer array used to identify positions to skip in the output array Returns: None Note: This method is called programmatically by `PstFrom.add_observations()` """ if ofile_sep is not None: self.logger.lraise( "array obs are currently only supported for whitespace delim" ) if not os.path.exists(self.new_d / out_filename): self.logger.lraise( "array obs output file '{0}' not found".format(out_filename) ) if len(prefix) == 0: prefix = Path(out_filename).stem f_out = open(self.new_d / out_filename, "r") f_ins = open(self.new_d / ins_filename, "w") f_ins.write("pif ~\n") iline = 0 if ofile_skip is not None: ofile_skip = int(ofile_skip) f_ins.write("l{0}\n".format(ofile_skip)) # read the output file forward for _ in range(ofile_skip): f_out.readline() iline += 1 onames, ovals = [], [] iidx = 0 for line in f_out: raw = line.split() f_ins.write("l1 ") for jr, r in enumerate(raw): try: fr = float(r) except Exception as e: self.logger.lraise( "array obs error casting: '{0}' on line {1} to a float: {2}".format( r, iline, str(e) ) ) zval = None if zone_array is not None: try: zval = zone_array[iidx, jr] except Exception as e: self.logger.lraise( "array obs error getting zone value for i,j {0},{1} in line {2}: {3}".format( iidx, jr, iline, str(e) ) ) if zval <= 0: f_ins.write(" !dum! ") if jr < len(raw) - 1: f_ins.write(" w ") continue oname = "oname:{0}_otype:arr_i:{1}_j:{2}".format(prefix, iidx, jr) if zval is not None: oname += "_zone:{0}".format(zval) f_ins.write(" !{0}! ".format(oname)) if jr < len(raw) - 1: f_ins.write(" w ") f_ins.write("\n") iline += 1 iidx += 1 def add_observations( self, filename, insfile=None, index_cols=None, use_cols=None, use_rows=None, prefix="", ofile_skip=None, ofile_sep=None, rebuild_pst=False, obsgp=None, zone_array=None, includes_header=True, ): """ Add values in output files as observations to PstFrom object Args: filename (`str`): model output file name(s) to set up as observations. By default filename should give relative loction from top level of pest template directory (`new_d` as passed to `PstFrom()`). insfile (`str`): desired instructions file filename index_cols (`list`-like or `int`): columns to denote are indices for obs use_cols (`list`-like or `int`): columns to set up as obs. If None, and `index_cols` is not None (i.e list-style obs assumed), observations will be set up for all columns in `filename` that are not in `index_cols`. use_rows (`list`-like or `int`): select only specific row of file for obs prefix (`str`): prefix for obsnmes ofile_skip (`int`): number of lines to skip in model output file ofile_sep (`str`): delimiter in output file. If `None`, the delimiter is eventually governed by the file extension (`,` for .csv). rebuild_pst (`bool`): (Re)Construct PstFrom.pst object after adding new obs obsgp (`str` of `list`-like): observation group name(s). If type `str` (or list of len == 1) and `use_cols` is None (i.e. all non-index cols are to be set up as obs), the same group name will be mapped to all obs in call. If None the obs group name will be derived from the base of the constructed observation name. If passed as `list` (and len(`list`) = `n` > 1), the entries in obsgp will be interpreted to explicitly define the grouped for the first `n` cols in `use_cols`, any remaining columns will default to None and the base of the observation name will be used. Default is None. zone_array (`np.ndarray`): array defining spatial limits or zones for array-style observations. Default is None includes_header (`bool`): flag indicating that the list-style file includes a header row. Default is True. Returns: `Pandas.DataFrame`: dataframe with info for new observations Note: This is the main entry for adding observations to the pest interface If `index_cols` and `use_cols` are both None, then it is assumed that array-style observations are being requested. In this case, `filenames` must be only one filename. `zone_array` is only used for array-style observations. Zone values less than or equal to zero are skipped (using the "dum" option) Example:: # setup observations for the 2nd thru 5th columns of the csv file # using the first column as the index df = pf.add_observations("heads.csv",index_col=0,use_cols=[1,2,3,4], ofile_sep=",") # add array-style observations, skipping model cells with an ibound # value less than or equal to zero df = pf.add_observations("conce_array.dat,index_col=None,use_cols=None, zone_array=ibound) """ use_cols_psd = copy.copy(use_cols) # store passed use_cols argument if insfile is None: # setup instruction file name insfile = "{0}.ins".format(filename) self.logger.log("adding observations from output file " "{0}".format(filename)) # precondition arguments ( filenames, fmts, seps, skip_rows, index_cols, use_cols, ) = self._prep_arg_list_lengths( filename, index_cols=index_cols, use_cols=use_cols, fmts=None, seps=ofile_sep, skip_rows=ofile_skip, ) # array style obs, if both index_cols and use_cols are None (default) if index_cols is None and use_cols is None: if not isinstance(filenames, str): if len(filenames) > 1: self.logger.lraise( "only a single filename can be used for array-style observations" ) filenames = filenames[0] self.logger.log( "adding observations from array output file '{0}'".format(filenames) ) # Setup obs for array style output, build and write instruction file self._process_array_obs( filenames, insfile, prefix, ofile_sep, ofile_skip, zone_array, ) # Add obs from ins file written by _process_array_obs() new_obs = self.add_observations_from_ins( ins_file=self.new_d / insfile, out_file=self.new_d / filename ) # Try to add an observation group name -- should default to `obgnme` # TODO: note list style default to base of obs name, here array default to `obgnme` if obsgp is not None: # if a group name is passed new_obs.loc[:, "obgnme"] = obsgp elif prefix is not None and len(prefix) != 0: # if prefix is passed new_obs.loc[:, "obgnme"] = prefix else: new_obs.loc[:, "obgnme"] = "oname:{0}_otype:arr".format(filenames) # else will default to `obgnme` self.logger.log( "adding observations from array output file '{0}'".format(filenames) ) if rebuild_pst: if self.pst is not None: self.logger.log("Adding obs to control file " "and rewriting pst") self.build_pst(filename=self.pst.filename, update="obs") else: self.build_pst(filename=self.pst.filename, update=False) self.logger.warn( "pst object not available, " "new control file will be written" ) return new_obs # list style obs self.logger.log( "adding observations from tabular output file " "'{0}'".format(filenames) ) # -- will end up here if either of index_cols or use_cols is not None df, storehead, inssep = self._load_listtype_file( filenames, index_cols, use_cols, fmts, seps, skip_rows ) if inssep != ",": inssep = seps else: inssep = [inssep] # rectify df? # if iloc[0] are strings and index_cols are ints, # can we assume that there were infact column headers? if all(isinstance(c, str) for c in df.iloc[0]) and all( isinstance(a, int) for a in index_cols ): index_cols = df.iloc[0][index_cols].to_list() # redefine index_cols if use_cols is not None: use_cols = df.iloc[0][use_cols].to_list() # redefine use_cols df = ( df.rename(columns=df.iloc[0].to_dict()) .drop(0) .reset_index(drop=True) .apply(pd.to_numeric, errors="ignore") ) # Select all non index cols if use_cols is None if use_cols is None: use_cols = df.columns.drop(index_cols).tolist() # Currently just passing through comments in header (i.e. before the table data) lenhead = 0 stkeys = np.array( sorted(storehead.keys()) ) # comments line numbers as sorted array if stkeys.size > 0 and stkeys.min() == 0: lenhead += 1 + np.sum(np.diff(stkeys) == 1) new_obs_l = [] for filename, sep in zip( filenames, inssep ): # should only ever be one but hey... self.logger.log( "building insfile for tabular output file {0}" "".format(filename) ) # Build dataframe from output file df for use in insfile df_temp = _get_tpl_or_ins_df( df, prefix, typ="obs", index_cols=index_cols, use_cols=use_cols, ) df.loc[:, "idx_str"] = df_temp.idx_strs # Select only certain rows if requested if use_rows is not None: if isinstance(use_rows, str): if use_rows not in df.idx_str: self.logger.warn( "can't find {0} in generated observation idx_str. " "setting up obs for all rows instead" "".format(use_rows) ) use_rows = None elif isinstance(use_rows, int): use_rows = [use_rows] use_rows = [r for r in use_rows if r <= len(df)] use_rows = df.iloc[use_rows].idx_str.unique() # Construct ins_file from df # first rectify group name with number of columns ncol = len(use_cols) fill = True # default fill=True means that the groupname will be # derived from the base of the observation name # if passed group name is a string or list with len < ncol # and passed use_cols was None or of len > len(obsgp) if obsgp is not None: if use_cols_psd is None: # no use_cols defined (all are setup) if len([obsgp] if isinstance(obsgp, str) else obsgp) == 1: # only 1 group provided, assume passed obsgp applys # to all use_cols fill = "first" else: # many obs groups passed, assume last will fill if < ncol fill = "last" # else fill will be set to True (base of obs name will be used) else: obsgp = True # will use base of col obsgp = _check_var_len(obsgp, ncol, fill=fill) nprefix = prefix if len(nprefix) == 0: nprefix = filenames[0] nprefix = "oname:{0}_otype:lst".format(nprefix) df_ins = pyemu.pst_utils.csv_to_ins_file( df.set_index("idx_str"), ins_filename=self.new_d / insfile, only_cols=use_cols, only_rows=use_rows, marker="~", includes_header=includes_header, includes_index=False, prefix=nprefix, head_lines_len=lenhead, sep=sep, gpname=obsgp, ) self.logger.log( "building insfile for tabular output file {0}" "".format(filename) ) new_obs = self.add_observations_from_ins( ins_file=self.new_d / insfile, out_file=self.new_d / filename ) if "obgnme" in df_ins.columns: new_obs.loc[:, "obgnme"] = df_ins.loc[new_obs.index, "obgnme"] new_obs_l.append(new_obs) new_obs = pd.concat(new_obs_l) self.logger.log( "adding observations from tabular output file " "'{0}'".format(filenames) ) if rebuild_pst: if self.pst is not None: self.logger.log("Adding obs to control file " "and rewriting pst") self.build_pst(filename=self.pst.filename, update="obs") else: pstname = Path(self.new_d, self.original_d.name) self.logger.warn( "pst object not available, " f"new control file will be written with filename {pstname}" ) self.build_pst(filename=None, update=False) return new_obs def add_observations_from_ins( self, ins_file, out_file=None, pst_path=None, inschek=True ): """add new observations to a control file from an existing instruction file Args: ins_file (`str`): instruction file with exclusively new observation names. N.B. if `ins_file` just contains base filename string (i.e. no directory name), the path to PEST directory will be automatically appended. out_file (`str`): model output file. If None, then ins_file.replace(".ins","") is used. Default is None. If `out_file` just contains base filename string (i.e. no directory name), the path to PEST directory will be automatically appended. pst_path (`str`): the path to append to the instruction file and out file in the control file. If not None, then any existing path in front of the template or ins file is split off and pst_path is prepended. If python is being run in a directory other than where the control file will reside, it is useful to pass `pst_path` as `.`. Default is None inschek (`bool`): flag to try to process the existing output file using the `pyemu.InstructionFile` class. If successful, processed outputs are used as obsvals Returns: `pandas.DataFrame`: the data for the new observations that were added Note: populates the new observation information with default values Example:: pf = pyemu.PstFrom("temp","template") pf.add_observations_from_ins(os.path.join("template","new_obs.dat.ins"), pst_path=".") """ # lifted almost completely from `Pst().add_observation()` if os.path.dirname(ins_file) in ["", "."]: # if insfile is passed as just a filename, # append pest directory name ins_file = self.new_d / ins_file pst_path = "." # reset and new assumed pst_path # else: # assuming that passed insfile is the full path to file from current location if not os.path.exists(ins_file): self.logger.lraise( "ins file not found: {0}, {1}" "".format(os.getcwd(), ins_file) ) if out_file is None: out_file = str(ins_file).replace(".ins", "") elif os.path.dirname(out_file) in ["", "."]: out_file = self.new_d / out_file if ins_file == out_file: self.logger.lraise("ins_file == out_file, doh!") # get the obs names in the instructions file self.logger.log( "adding observation from instruction file '{0}'".format(ins_file) ) obsnme = pyemu.pst_utils.parse_ins_file(ins_file) sobsnme = set(obsnme) if len(self.obs_dfs) > 0: sexist = pd.concat(self.obs_dfs).obsnme else: sexist = [] sexist = set(sexist) # todo need to check this here? sint = sobsnme.intersection(sexist) if len(sint) > 0: self.logger.lraise( "the following obs instruction file {0} are already in the " "control file:{1}".format(ins_file, ",".join(sint)) ) # find "new" obs that are not already in the control file new_obsnme = sobsnme - sexist if len(new_obsnme) == 0: self.logger.lraise( "no new observations found in instruction file {0}".format(ins_file) ) # extend observation_data new_obsnme = np.sort(list(new_obsnme)) new_obs_data = pyemu.pst_utils._populate_dataframe( new_obsnme, pyemu.pst_utils.pst_config["obs_fieldnames"], pyemu.pst_utils.pst_config["obs_defaults"], pyemu.pst_utils.pst_config["obs_dtype"], ) new_obs_data.loc[new_obsnme, "obsnme"] = new_obsnme new_obs_data.index = new_obsnme # need path relative to where control file ins_file_pstrel = Path(ins_file).relative_to(self.new_d) out_file_pstrel = Path(out_file).relative_to(self.new_d) if pst_path is not None: ins_file_pstrel = pst_path / ins_file_pstrel out_file_pstrel = pst_path / out_file_pstrel self.ins_filenames.append(ins_file_pstrel) self.output_filenames.append(out_file_pstrel) # add to temporary files to be removed at start of forward run self.tmp_files.append(out_file_pstrel) df = None if inschek: # df = pst_utils._try_run_inschek(ins_file,out_file,cwd=cwd) # ins_file = os.path.join(cwd, ins_file) # out_file = os.path.join(cwd, out_file) df = pyemu.pst_utils.try_process_output_file( ins_file=ins_file, output_file=out_file ) if df is not None: # print(self.observation_data.index,df.index) new_obs_data.loc[df.index, "obsval"] = df.obsval self.obs_dfs.append(new_obs_data) self.logger.log( "adding observation from instruction file '{0}'".format(ins_file) ) return new_obs_data def add_parameters( self, filenames, par_type, zone_array=None, dist_type="gaussian", sigma_range=4.0, upper_bound=None, lower_bound=None, transform="log", par_name_base="p", index_cols=None, use_cols=None, use_rows=None, pargp=None, pp_space=10, use_pp_zones=False, num_eig_kl=100, spatial_reference=None, geostruct=None, datetime=None, mfile_fmt="free", mfile_skip=None, mfile_sep=None, ult_ubound=None, ult_lbound=None, rebuild_pst=False, alt_inst_str="inst", comment_char=None, par_style="multiplier", initial_value=None, ): """ Add list or array style model input files to PstFrom object. This method is the main entry point for adding parameters to the pest interface Args: filenames (`str`): Model input filenames to parameterize par_type (`str`): One of `grid` - for every element, `constant` - for single parameter applied to every element, `zone` - for zone-based parameterization or `pilotpoint` - for pilot-point base parameterization of array style input files. Note `kl` not yet implemented # TODO zone_array (`np.ndarray`): array defining spatial limits or zones for parameterization. dist_type: not yet implemented # TODO sigma_range: not yet implemented # TODO upper_bound (`float`): PEST parameter upper bound. If `None`, then 1.0e+10 is used. Default is `None` # lower_bound (`float`): PEST parameter lower bound. If `None` and `transform` is "log", then 1.0e-10 is used. Otherwise, if `None`, -1.0e+10 is used. Default is `None` transform (`str`): PEST parameter transformation. Must be either "log","none" or "fixed. The "tied" transform must be used after calling `PstFrom.build_pst()`. par_name_base (`str` or `list`-like): basename for parameters that are set up. If parameter file is tabular list-style file (`index_cols` is not None) then : len(par_name_base) must equal len(use_cols) index_cols (`list`-like): if not None, will attempt to parameterize expecting a tabular-style model input file. `index_cols` defines the unique columns used to set up pars. If passed as a list of `str`, stings are expected to denote the columns headers in tabular-style parameter files; if `i` and `j` in list, these columns will be used to define spatial position for spatial correlations (if required). WARNING: If passed as list of `int`, `i` and `j` will be assumed to be in last two entries in the list. Can be passed as a dictionary using the keys `i` and `j` to explicitly speficy the columns that relate to model rows and columns to be identified and processed to x,y. use_cols (`list`-like or `int`): for tabular-style model input file, defines the columns to be parameterised use_rows (`list` of `int` or `tuple`): Setup parameters for only specific rows in list-style model input file. If list of `int` -- assumed to be a row index selection (zero-based). If list of `tuple` -- assumed to be selection based `index_cols` values. e.g. [(3,5,6)] would attempt to set parameters where the model file values for 3 `index_cols` are 3,5,6. N.B. values in tuple are actual model file entry values. If no rows in the model input file match `use_rows`, parameters will be set up for all rows. Only valid/effective if index_cols is not None. Default is None -- setup parameters for all rows. pargp (`str`): Parameter group to assign pars to. This is PESTs pargp but is also used to gather correlated parameters set up using multiple `add_parameters()` calls (e.g. temporal pars) with common geostructs. pp_space (`int`,`str` or `pd.DataFrame`): Spatial pilot point information. If `int` it is the spacing in rows and cols of where to place pilot points. If `pd.DataFrame`, then this arg is treated as a prefined set of pilot points and in this case, the dataframe must have "name", "x", "y", and optionally "zone" columns. If `str`, then an attempt is made to load a dataframe from a csv file (if `pp_space` ends with ".csv"), shapefile (if `pp_space` ends with ".shp") or from a pilot points file. If `pp_space` is None, an integer spacing of 10 is used. Default is None use_pp_zones (`bool`): a flag to use the greater-than-zero values in the zone_array as pilot point zones. If False, zone_array values greater than zero are treated as a single zone. This argument is only used if `pp_space` is None or `int`. Default is False. num_eig_kl: TODO - impliment with KL pars spatial_reference (`pyemu.helpers.SpatialReference`): If different spatial reference required for pilotpoint setup. If None spatial reference passed to `PstFrom()` will be used for pilot-points geostruct (`pyemu.geostats.GeoStruct()`): For specifying correlation geostruct for pilot-points and par covariance. datetime (`str`): optional %Y%m%d string or datetime object for setting up temporally correlated pars. Where datetime is passed correlation axis for pars will be set to timedelta. mfile_fmt (`str`): format of model input file - this will be preserved mfile_skip (`int` or `str`): header in model input file to skip when reading and reapply when writing. Can optionally be `str` in which case `mf_skip` will be treated as a `comment_char`. mfile_sep (`str`): separator/delimiter in model input file. If None, separator will be interpretted from file name extension. `.csv` is assumed to be comma separator. Default is None ult_ubound (`float`): Ultimate upper bound for model input parameter once all mults are applied - ensure physical model par vals. If not passed, it is set to 1.0e+30 ult_lbound (`float`): Ultimate lower bound for model input parameter once all mults are applied. If not passed, it is set to 1.0e-30 for log transform and -1.0e+30 for non-log transform rebuild_pst (`bool`): (Re)Construct PstFrom.pst object after adding new parameters alt_inst_str (`str`): Alternative to default `inst` string in parameter names. Specify ``None`` or ``""`` to exclude the instance information from parameter names. For example, if parameters that apply to more than one input/template file are desired. comment_char (`str`): option to skip comment lines in model file. This is not additive with `mfile_skip` option. Warning: currently comment lines within list-style tabular data will be lost. par_style (`str`): either "m"/"mult"/"multiplier", "a"/"add"/"addend", or "d"/"direct" where the former setups up a multiplier and addend parameters process against the existing model input array and the former setups a template file to write the model input file directly. Default is "multiplier". initial_value (`float`): the value to set for the `parval1` value in the control file Default is 1.0 Returns: `pandas.DataFrame`: dataframe with info for new parameters Example:: # setup grid-scale direct parameters for an array of numbers df = pf.add_parameters("hk.dat",par_type="grid",par_style="direct") # setup pilot point multiplier parameters for an array of numbers # with a pilot point being set in every 5th active model cell df = pf.add_parameters("recharge.dat",par_type="pilotpoint",pp_space=5, zone_array="ibound.dat") # setup a single multiplier parameter for the 4th column # of a column format (list/tabular type) file df = pf.add_parameters("wel_list_1.dat",par_type="constant", index_cols=[0,1,2],use_cols=[3]) """ # TODO need more support for temporal pars? # - As another partype using index_cols or an additional time_cols # TODO support passing par_file (i,j)/(x,y) directly where information # is not contained in model parameter file - e.g. no i,j columns self.add_pars_callcount += 1 self.ijwarned[self.add_pars_callcount] = False if transform.lower().strip() not in ["none", "log", "fixed"]: self.logger.lraise( "unrecognized transform ('{0}'), should be in ['none','log','fixed']".format( transform ) ) if transform == "fixed" and geostruct is not None: self.logger.lraise( "geostruct is not 'None', cant draw values for fixed pars" ) # some checks for direct parameters par_style = par_style.lower() if len(par_style) > 1: par_style = par_style[0] if par_style not in ["m", "d", "a"]: self.logger.lraise( "add_parameters(): unrecognized 'style': {0}, should be either 'm'/'mult'/'multiplier', 'a'/'add'/'addend' or 'd'/'direct'".format( par_style ) ) if initial_value is None: if par_style == "m": initial_value = 1.0 elif par_style == "a": initial_value = 0.0 elif par_style == "d": initial_value = 1.0 # ? if upper_bound is None: upper_bound = 1.0e10 if lower_bound is None: if transform.lower() == "log": lower_bound = 1.0e-10 else: lower_bound = -1.0e10 if isinstance(filenames, str) or isinstance(filenames, Path): filenames = [filenames] # data file paths relative to the pest parent directory filenames = [ get_relative_filepath(self.original_d, filename) for filename in filenames ] if len(filenames) == 0: self.logger.lraise("add_parameters(): filenames is empty") if par_style == "d": if len(filenames) != 1: self.logger.lraise( "add_parameters(): 'filenames' arg for 'direct' style " "must contain one and only one filename, " f"not {len(filenames)} files" ) if filenames[0] in self.direct_org_files: self.logger.lraise( f"add_parameters(): original model input file " f"'{filenames[0]}' already used for 'direct' parameterization" ) else: self.direct_org_files.append(filenames[0]) # Default par data columns used for pst par_data_cols = pyemu.pst_utils.pst_config["par_fieldnames"] self.logger.log( f"adding {par_type} type {par_style} style parameters for file(s) " f"{[str(f) for f in filenames]}" ) if geostruct is not None: self.logger.log("using geostruct:{0}".format(str(geostruct))) if geostruct.sill != 1.0: # and par_style != "multiplier": #TODO !=? self.logger.warn( "geostruct sill != 1.0" # for 'multiplier' style parameters" ) if geostruct.transform != transform: self.logger.warn( "0) Inconsistency between " "geostruct transform and partrans." ) self.logger.warn(f"1) Setting geostruct transform to " "{transform}") if geostruct not in self.par_struct_dict.keys(): # safe to just reset transform geostruct.transform = transform else: self.logger.warn("2) This will create a new copy of " "geostruct") # to avoid flip flopping transform need to make a new geostruct geostruct = copy.copy(geostruct) geostruct.transform = transform self.logger.warn( "-) Better to pass an appropriately " "transformed geostruct" ) # Get useful variables from arguments passed # if index_cols passed as a dictionary that maps i,j information idx_cols = index_cols ij_in_idx = None xy_in_idx = None if isinstance(index_cols, dict): # only useful if i and j are in keys .... or xy? # TODO: or datetime str? keys = np.array([k.lower() for k in index_cols.keys()]) idx_cols = [index_cols[k] for k in keys] if any(all(a in keys for a in aa) for aa in [["i", "j"], ["x", "y"]]): if all(ij in keys for ij in ["i", "j"]): o_idx = np.argsort(keys) ij_in_idx = o_idx[np.searchsorted(keys[o_idx], ["i", "j"])] if all(xy in keys for xy in ["x", "y"]): o_idx = np.argsort(keys) xy_in_idx = o_idx[np.searchsorted(keys[o_idx], ["x", "y"])] else: self.logger.lraise( "If passing `index_cols` as type == dict, " "keys need to contain [`i` and `j`] or " "[`x` and `y`]" ) ( index_cols, use_cols, file_dict, fmt_dict, sep_dict, skip_dict, headerlines, # needed for direct pars (need to be in tpl) ) = self._par_prep( filenames, idx_cols, use_cols, fmts=mfile_fmt, skip_rows=mfile_skip, c_char=comment_char, seps=mfile_sep, ) if datetime is not None: # convert and check datetime # TODO: something needed here to allow a different relative point. datetime = _get_datetime_from_str(datetime) if self.start_datetime is None: self.logger.warn( "NO START_DATEIME PROVIDED, ASSUMING PAR " "DATETIME IS START {}".format(datetime) ) self.start_datetime = datetime assert ( datetime >= self.start_datetime ), "passed datetime is earlier than start_datetime {0}, {1}".format( datetime, self.start_datetime ) t_offest = datetime - self.start_datetime # Pull out and construct name-base for parameters if isinstance(par_name_base, str): par_name_base = [par_name_base] # if `use_cols` is passed check number of base names is the same as cols if use_cols is None and len(par_name_base) == 1: pass elif use_cols is not None and len(par_name_base) == len(use_cols): pass else: self.logger.lraise( "par_name_base should be a string, " "single-element container, or container of " f"len use_cols, not '{str(par_name_base)}'" ) # otherewise, things get tripped up in the ensemble/cov stuff if pargp is not None: if isinstance(pargp, list): pargp = [pg.lower() for pg in pargp] else: pargp = pargp.lower() par_name_base = [pnb.lower() for pnb in par_name_base] fmt = "_{0}".format(alt_inst_str) + ":{0}" chk_prefix = "_{0}".format(alt_inst_str) # add `instance` identifier # increment name base if already passed for i in range(len(par_name_base)): # multiplier file name will be taken first par group, if passed # (the same multipliers will apply to all pars passed in this call) # Remove `:` for filenames # multiplier file needs instance number # regardless of whether instance is to be included # in the parameter names if i == 0: inst = self._next_count(par_name_base[i] +\ chk_prefix) par_name_store = (par_name_base[0] + fmt.format(inst)).replace(":", "") # if instance is to be included in the parameter names # add the instance suffix to the parameter name base if alt_inst_str is not None and len(alt_inst_str) > 0: par_name_base[0] += fmt.format(inst) # if instance is to be included in the parameter names # add the instance suffix to the parameter name base elif alt_inst_str is not None and len(alt_inst_str) > 0: par_name_base[i] += fmt.format( self._next_count(par_name_base[i] + chk_prefix) ) # multiplier file name will be taken first par group, if passed # (the same multipliers will apply to all pars passed in this call) # Remove `:` for filenames #par_name_store = par_name_base[0].replace(":", "") # for os filename # Define requisite filenames if par_style in ["m", "a"]: mlt_filename = "{0}_{1}.csv".format(par_name_store, par_type) # pst input file (for tpl->in pair) is multfile (in mult dir) in_fileabs = self.mult_file_d / mlt_filename # pst input file (for tpl->in pair) is multfile (in mult dir) in_filepst = in_fileabs.relative_to(self.new_d) tpl_filename = self.tpl_d / (mlt_filename + ".tpl") else: mlt_filename = np.NaN # absolute path to org/datafile in_fileabs = self.original_file_d / filenames[0].name # pst input file (for tpl->in pair) is orgfile (in org dir) # relative path to org/datafile (relative to dest model workspace): in_filepst = in_fileabs.relative_to(self.new_d) tpl_filename = self.tpl_d / (filenames[0].name + ".tpl") # this keeps denormal values for creeping into the model input arrays ubfill = None lbfill = None if ult_ubound is None: # no ultimate bounds are passed default to class set bounds ult_ubound = self.ult_ubound_fill ubfill = "first" # will fill for all use_cols if ult_lbound is None: ult_lbound = self.ult_lbound_fill lbfill = "first" pp_filename = None # setup placeholder variables fac_filename = None # Process model parameter files to produce appropriate pest pars if index_cols is not None: # Assume list/tabular type input files # ensure inputs are provided for all required cols ncol = len(use_cols) ult_lbound = _check_var_len(ult_lbound, ncol, fill=ubfill) ult_ubound = _check_var_len(ult_ubound, ncol, fill=lbfill) pargp = _check_var_len(pargp, ncol) lower_bound = _check_var_len(lower_bound, ncol, fill="first") upper_bound = _check_var_len(upper_bound, ncol, fill="first") if len(use_cols) != len(ult_lbound) != len(ult_ubound): self.logger.lraise( "mismatch in number of columns to use {0} " "and number of ultimate lower {0} or upper " "{1} par bounds defined" "".format(len(use_cols), len(ult_lbound), len(ult_ubound)) ) self.logger.log( "writing list-style template file '{0}'".format(tpl_filename) ) # Generate tabular type template - also returns par data # relative file paths are in file_dict as Path instances (kludgey) dfs = [file_dict[Path(filename)] for filename in filenames] get_xy = None if ( par_type.startswith("grid") or par_type.startswith("p") ) and geostruct is not None: get_xy = self.get_xy df = write_list_tpl( filenames, dfs, par_name_base, tpl_filename=tpl_filename, par_type=par_type, suffix="", index_cols=index_cols, use_cols=use_cols, use_rows=use_rows, zone_array=zone_array, gpname=pargp, ij_in_idx=ij_in_idx, xy_in_idx=xy_in_idx, get_xy=get_xy, zero_based=self.zero_based, input_filename=in_fileabs, par_style=par_style, headerlines=headerlines, fill_value=initial_value, logger=self.logger, ) assert ( np.mod(len(df), len(use_cols)) == 0.0 ), "Parameter dataframe wrong shape for number of cols {0}" "".format( use_cols ) # variables need to be passed to each row in df lower_bound = np.tile(lower_bound, int(len(df) / ncol)) upper_bound = np.tile(upper_bound, int(len(df) / ncol)) self.logger.log( "writing list-style template file '{0}'".format(tpl_filename) ) else: # Assume array type parameter file self.logger.log( "writing array-style template file '{0}'".format(tpl_filename) ) if pargp is None: pargp = par_name_base[0] shp = file_dict[list(file_dict.keys())[0]].shape # ARRAY constant, zones or grid (cell-by-cell) if par_type in {"constant", "zone", "grid"}: self.logger.log( "writing template file " "{0} for {1}".format(tpl_filename, par_name_base) ) # Generate array type template - also returns par data df = write_array_tpl( name=par_name_base[0], tpl_filename=tpl_filename, suffix="", par_type=par_type, zone_array=zone_array, shape=shp, get_xy=self.get_xy, fill_value=1.0, gpname=pargp, input_filename=in_fileabs, par_style=par_style, ) self.logger.log( "writing template file" " {0} for {1}".format(tpl_filename, par_name_base) ) # ARRAY PILOTPOINT setup elif par_type in { "pilotpoints", "pilot_points", "pilotpoint", "pilot_point", "pilot-point", "pilot-points", "pp" }: if par_style == "d": self.logger.lraise( "pilot points not supported for 'direct' par_style" ) # Setup pilotpoints for array type par files self.logger.log("setting up pilot point parameters") # finding spatial references for for setting up pilot points if spatial_reference is None: # if none passed with add_pars call self.logger.statement( "No spatial reference " "(containing cell spacing) passed." ) if self.spatial_reference is not None: # using global sr on PstFrom object self.logger.statement( "OK - using spatial reference " "in parent object." ) spatial_reference = self.spatial_reference else: # uhoh self.logger.lraise( "No spatial reference in parent " "object either. " "Can't set-up pilotpoints" ) # check that spatial reference lines up with the original array dimensions structured = False if not isinstance(spatial_reference, dict): structured = True for mod_file, ar in file_dict.items(): orgdata = ar.shape assert orgdata[0] == spatial_reference.nrow, ( "Spatial reference nrow not equal to original data nrow for\n" + os.path.join( *os.path.split(self.original_file_d)[1:], mod_file ) ) assert orgdata[1] == spatial_reference.ncol, ( "Spatial reference ncol not equal to original data ncol for\n" + os.path.join( *os.path.split(self.original_file_d)[1:], mod_file ) ) # (stolen from helpers.PstFromFlopyModel()._pp_prep()) # but only settting up one set of pps at a time pnb = par_name_base[0] pnb = "pname:{1}_ptype:pp_pstyle:{0}".format(par_style, pnb) pp_dict = {0: pnb} pp_filename = "{0}pp.dat".format(par_name_store) # pst inputfile (for tpl->in pair) is # par_name_storepp.dat table (in pst ws) in_filepst = pp_filename pp_filename_dict = {pnb: in_filepst} tpl_filename = self.tpl_d / (pp_filename + ".tpl") # tpl_filename = get_relative_filepath(self.new_d, tpl_filename) pp_locs = None if pp_space is None: # default spacing if not passed self.logger.warn("pp_space is None, using 10...\n") pp_space = 10 else: if not use_pp_zones and (isinstance(pp_space, int)): # if not using pp zones will set up pp for just one # zone (all non zero) -- for active domain... if zone_array is None: nr, nc = file_dict[list(file_dict.keys())[0]].shape zone_array = np.ones((nr,nc)) zone_array[zone_array > 0] = 1 # so can set all # gt-zero to 1 if isinstance(pp_space, float): pp_space = int(pp_space) elif isinstance(pp_space, int): pass elif isinstance(pp_space, str): if pp_space.lower().strip().endswith(".csv"): self.logger.statement( "trying to load pilot point location info from csv file '{0}'".format( self.new_d / Path(pp_space) ) ) pp_locs = pd.read_csv(self.new_d / pp_space) elif pp_space.lower().strip().endswith(".shp"): self.logger.statement( "trying to load pilot point location info from shapefile '{0}'".format( self.new_d / Path(pp_space) ) ) pp_locs = pyemu.pp_utils.pilot_points_from_shapefile( str(self.new_d / Path(pp_space)) ) else: self.logger.statement( "trying to load pilot point location info from pilot point file '{0}'".format( self.new_d / Path(pp_space) ) ) pp_locs = pyemu.pp_utils.pp_file_to_dataframe( self.new_d / pp_space ) self.logger.statement( "pilot points found in file '{0}' will be transferred to '{1}' for parameterization".format( pp_space, pp_filename ) ) elif isinstance(pp_space, pd.DataFrame): pp_locs = pp_space else: self.logger.lraise( "unrecognized 'pp_space' value, should be int, csv file, pp file or dataframe, not '{0}'".format( type(pp_space) ) ) if pp_locs is not None: cols = pp_locs.columns.tolist() if "name" not in cols: self.logger.lraise("'name' col not found in pp dataframe") if "x" not in cols: self.logger.lraise("'x' col not found in pp dataframe") if "y" not in cols: self.logger.lraise("'y' col not found in pp dataframe") if "zone" not in cols: self.logger.warn( "'zone' col not found in pp dataframe, adding generic zone" ) pp_locs.loc[:, "zone"] = 1 elif zone_array is not None: # check that all the zones in the pp df are in the zone array missing = [] for uz in pp_locs.zone.unique(): if int(uz) not in zone_array: missing.append(str(uz)) if len(missing) > 0: self.logger.lraise( "the following pp zone values were not found in the zone array: {0}".format( ",".join(missing) ) ) for uz in np.unique(zone_array): if uz < 1: continue if uz not in pp_locs.zone.values: missing.append(str(uz)) if len(missing) > 0: self.logger.warn( "the following zones don't have any pilot points:{0}".format( ",".join(missing) ) ) if not structured and pp_locs is None: self.logger.lraise( "pilot point type parameters with an unstructured grid requires 'pp_space' " "contain explict pilot point information" ) if not structured and zone_array is not None: # self.logger.lraise("'zone_array' not supported for unstructured grids and pilot points") if "zone" not in pp_locs.columns: self.logger.lraise( "'zone' not found in pp info dataframe and 'zone_array' passed" ) uvals = np.unique(zone_array) zvals = set([int(z) for z in pp_locs.zone.tolist()]) missing = [] for uval in uvals: if int(uval) not in zvals and int(uval) != 0: missing.append(str(int(uval))) if len(missing) > 0: self.logger.warn( "the following values in the zone array were not found in the pp info: {0}".format( ",".join(missing) ) ) if geostruct is None: # need a geostruct for pilotpoints # can use model default, if provided if self.geostruct is None: # but if no geostruct passed... if not structured: self.logger.lraise( "pilot point type parameters with an unstructured grid requires an" " explicit `geostruct` arg be passed to either PstFrom or add_parameters()" ) self.logger.warn( "pp_geostruct is None," "using ExpVario with contribution=1 " "and a=(pp_space*max(delr,delc))" ) # set up a default - could probably do something better if pp locs are passed if not isinstance(pp_space, int): space = 10 else: space = pp_space pp_dist = space * float( max( spatial_reference.delr.max(), spatial_reference.delc.max(), ) ) v = pyemu.geostats.ExpVario(contribution=1.0, a=pp_dist) pp_geostruct = pyemu.geostats.GeoStruct( variograms=v, name="pp_geostruct", transform=transform ) else: pp_geostruct = self.geostruct if pp_geostruct.transform != transform: self.logger.warn( "0) Inconsistency between " "pp_geostruct transform and " "partrans." ) self.logger.warn( "1) Setting pp_geostruct transform " "to {0}".format(transform) ) self.logger.warn( "2) This will create a new copy of " "pp_geostruct" ) self.logger.warn( "3) Better to pass an appropriately " "transformed geostruct" ) pp_geostruct = copy.copy(pp_geostruct) pp_geostruct.transform = transform else: pp_geostruct = geostruct if pp_locs is None: # Set up pilot points df = pyemu.pp_utils.setup_pilotpoints_grid( sr=spatial_reference, ibound=zone_array, use_ibound_zones=use_pp_zones, prefix_dict=pp_dict, every_n_cell=pp_space, pp_dir=self.new_d, tpl_dir=self.tpl_d, shapename=str(self.new_d / "{0}.shp".format(par_name_store)), pp_filename_dict=pp_filename_dict, ) else: df = pyemu.pp_utils.pilot_points_to_tpl( pp_locs, tpl_filename, pnb, ) df.loc[:, "pargp"] = pargp df.set_index("parnme", drop=False, inplace=True) # df includes most of the par info for par_dfs and also for # relate_parfiles self.logger.statement( "{0} pilot point parameters created".format(df.shape[0]) ) # should be only one group at a time pargp = df.pargp.unique() self.logger.statement("pilot point 'pargp':{0}".format(",".join(pargp))) self.logger.log("setting up pilot point parameters") # Calculating pp factors pg = pargp[0] # this reletvively quick ok_pp = pyemu.geostats.OrdinaryKrige(pp_geostruct, df) # build krige reference information on the fly - used to help # prevent unnecessary krig factor calculation pp_info_dict = { "pp_data": ok_pp.point_data.loc[:, ["x", "y", "zone"]], "cov": ok_pp.point_cov_df, "zn_ar": zone_array, "sr": spatial_reference, } fac_processed = False for facfile, info in self._pp_facs.items(): # check against # factors already calculated if ( info["pp_data"].equals(pp_info_dict["pp_data"]) and info["cov"].equals(pp_info_dict["cov"]) and np.array_equal(info["zn_ar"], pp_info_dict["zn_ar"]) ): if type(info["sr"]) == type(spatial_reference): if isinstance(spatial_reference, dict): if len(info["sr"]) != len(spatial_reference): continue else: continue fac_processed = True # don't need to re-calc same factors fac_filename = facfile # relate to existing fac file break if not fac_processed: # TODO need better way of naming sequential fac_files? self.logger.log("calculating factors for pargp={0}".format(pg)) fac_filename = self.new_d / "{0}pp.fac".format(par_name_store) var_filename = fac_filename.with_suffix(".var.dat") self.logger.statement( "saving krige variance file:{0}".format(var_filename) ) self.logger.statement( "saving krige factors file:{0}".format(fac_filename) ) # store info on pilotpoints self._pp_facs[fac_filename] = pp_info_dict # this is slow (esp on windows) so only want to do this # when required if structured: ok_pp.calc_factors_grid( spatial_reference, var_filename=var_filename, zone_array=zone_array, num_threads=10, ) ok_pp.to_grid_factors_file(fac_filename) else: # put the sr dict info into a df # but we only want to use the n if zone_array is not None: for zone in np.unique(zone_array): if int(zone) == 0: continue data = [] for node, (x, y) in spatial_reference.items(): if zone_array[0, node] == zone: data.append([node, x, y]) if len(data) == 0: continue node_df = pd.DataFrame(data, columns=["node", "x", "y"]) ok_pp.calc_factors( node_df.x, node_df.y, num_threads=1, pt_zone=zone, idx_vals=node_df.node.astype(int), ) ok_pp.to_grid_factors_file( fac_filename, ncol=len(spatial_reference) ) else: data = [] for node, (x, y) in spatial_reference.items(): data.append([node, x, y]) node_df = pd.DataFrame(data, columns=["node", "x", "y"]) ok_pp.calc_factors(node_df.x, node_df.y, num_threads=10) ok_pp.to_grid_factors_file( fac_filename, ncol=node_df.shape[0] ) self.logger.log("calculating factors for pargp={0}".format(pg)) # TODO - other par types - JTW? elif par_type == "kl": self.logger.lraise("array type 'kl' not implemented") else: self.logger.lraise( "unrecognized 'par_type': '{0}', " "should be in " "['constant','zone','grid','pilotpoints'," "'kl'" ) self.logger.log( "writing array-based template file " "'{0}'".format(tpl_filename) ) if datetime is not None: # add time info to par_dfs df["datetime"] = datetime df["timedelta"] = t_offest # accumulate information that relates mult_files (set-up here and # eventually filled by PEST) to actual model files so that actual # model input file can be generated # (using helpers.apply_list_and_array_pars()) zone_filename = None if zone_array is not None and zone_array.ndim < 3: # zone_filename = tpl_filename.replace(".tpl",".zone") zone_filename = Path(str(tpl_filename).replace(".tpl", ".zone")) self.logger.statement( "saving zone array {0} for tpl file {1}".format( zone_filename, tpl_filename ) ) np.savetxt(zone_filename, zone_array, fmt="%4d") zone_filename = zone_filename.name relate_parfiles = [] for mod_file in file_dict.keys(): mult_dict = { "org_file": Path(self.original_file_d.name, mod_file.name), "model_file": mod_file, "use_cols": use_cols, "index_cols": index_cols, "fmt": fmt_dict[mod_file], "sep": sep_dict[mod_file], "head_rows": skip_dict[mod_file], "upper_bound": ult_ubound, "lower_bound": ult_lbound, "operator": par_style, } if par_style in ["m", "a"]: mult_dict["mlt_file"] = Path(self.mult_file_d.name, mlt_filename) if pp_filename is not None: # if pilotpoint need to store more info assert fac_filename is not None, "missing pilot-point input filename" mult_dict["fac_file"] = os.path.relpath(fac_filename, self.new_d) mult_dict["pp_file"] = pp_filename mult_dict["pp_fill_value"] = 1.0 mult_dict["pp_lower_limit"] = 1.0e-10 mult_dict["pp_upper_limit"] = 1.0e10 if zone_filename is not None: mult_dict["zone_file"] = zone_filename relate_parfiles.append(mult_dict) relate_pars_df = pd.DataFrame(relate_parfiles) # store on self for use in pest build etc self._parfile_relations.append(relate_pars_df) # add cols required for pst.parameter_data df.loc[:, "partype"] = par_type df.loc[:, "partrans"] = transform df.loc[:, "parubnd"] = upper_bound df.loc[:, "parlbnd"] = lower_bound # df.loc[:,"tpl_filename"] = tpl_filename # store tpl --> in filename pair self.tpl_filenames.append(get_relative_filepath(self.new_d, tpl_filename)) self.input_filenames.append(in_filepst) for file_name in file_dict.keys(): # store mult --> original file pairs self.org_files.append(file_name) self.mult_files.append(mlt_filename) # add pars to par_data list BH: is this what we want? # - BH: think we can get away with dropping duplicates? missing = set(par_data_cols) - set(df.columns) for field in missing: # fill missing pst.parameter_data cols with defaults df[field] = pyemu.pst_utils.pst_config["par_defaults"][field] df = df.drop_duplicates(subset="parnme") # drop pars that appear multiple times # df = df.loc[:, par_data_cols] # just storing pst required cols # - need to store more for cov builder (e.g. x,y) # TODO - check when self.par_dfs gets used # if constructing struct_dict here.... # - possibly not necessary to store # only add pardata for new parameters # some parameters might already be in a par_df if they occur # in more than one instance (layer, for example) new_parnmes = set(df['parnme']).difference(self.unique_parnmes) df = df.loc[df['parnme'].isin(new_parnmes)].copy() self.par_dfs.append(df) self.unique_parnmes.update(new_parnmes) # pivot df to list of df per par group in this call # (all groups will be related to same geostruct) # TODO maybe use different marker to denote a relationship between pars # at the moment relating pars using common geostruct and pargp but may # want to reserve pargp for just PEST if "covgp" not in df.columns: gp_dict = {g: [d] for g, d in df.groupby("pargp")} else: gp_dict = {g: [d] for g, d in df.groupby("covgp")} # df_list = [d for g, d in df.groupby('pargp')] if geostruct is not None and ( par_type.lower() not in ["constant", "zone"] or datetime is not None ): # relating pars to geostruct.... if geostruct not in self.par_struct_dict.keys(): # add new geostruct self.par_struct_dict[geostruct] = gp_dict # self.par_struct_dict_l[geostruct] = list(gp_dict.values()) else: # append group to appropriate key associated with this geostruct # this is how pars setup with different calls are collected # so their correlations can be tracked for gp, gppars in gp_dict.items(): # if group not already set up if gp not in self.par_struct_dict[geostruct].keys(): # update dict entry with new {key:par} pair self.par_struct_dict[geostruct].update({gp: gppars}) else: # if gp already assigned to this geostruct append par # list to approprate group key self.par_struct_dict[geostruct][gp].extend(gppars) # self.par_struct_dict_l[geostruct].extend(list(gp_dict.values())) else: # TODO some rules for if geostruct is not passed.... if "x" in df.columns: pass # TODO warn that it looks like spatial pars but no geostruct? # if self.geostruct is not None: # geostruct = self.geostruct # elif pp_geostruct is not None: # geostruct = pp_geostruct # else: # TODO - do we need an error or warning and define a default? # options: # if spatial_reference is None: # spatial_reference = self.spatial_reference # TODO placeholder for now. but this needs improving, sr and self.sr might be None # dist = 10 * float( # max(spatial_reference.delr.max(), # spatial_reference.delc.max())) # v = pyemu.geostats.ExpVario(contribution=1.0, a=dist) # geostruct = pyemu.geostats.GeoStruct( # variograms=v) # temporal default: # v = pyemu.geostats.ExpVario(contribution=1.0, a=180.0) # 180 correlation length # geostruct = pyemu.geostats.GeoStruct( # variograms=v) self.logger.log( "adding {0} type {1} style parameters for file(s) {2}".format( par_type, par_style, [str(f) for f in filenames] ) ) if rebuild_pst: # may want to just update pst and rebuild # (with new relations) if self.pst is not None: self.logger.log("Adding pars to control file " "and rewriting pst") self.build_pst(filename=self.pst.filename, update="pars") else: self.build_pst(filename=self.pst.filename, update=False) self.logger.warn( "pst object not available, " "new control file will be written" ) return df def _load_listtype_file( self, filename, index_cols, use_cols, fmt=None, sep=None, skip=None, c_char=None ): if isinstance(filename, list): assert len(filename) == 1 filename = filename[0] # should only ever be one passed if isinstance(fmt, list): assert len(fmt) == 1 fmt = fmt[0] if isinstance(sep, list): assert len(sep) == 1 sep = sep[0] if isinstance(skip, list): assert len(skip) == 1 skip = skip[0] # trying to use use_cols and index_cols to work out whether to # read header from csv. # either use_cols or index_cols could still be None # -- case of both being None should already have been caught # but index_cols could still be None... check_args = [a for a in [index_cols, use_cols] if a is not None] # `a` should be list if it is not None if all(isinstance(a[0], str) for a in check_args): # index_cols can be from header str header = 0 # will need to read a header elif all(isinstance(a[0], int) for a in check_args): # index_cols are column numbers in input file header = None else: if len(check_args) > 1: # implies neither are None but they either both are not str,int # or are different self.logger.lraise( "unrecognized type for index_cols or use_cols " "should be str or int and both should be of the " "same type, not {0} or {1}".format( *[str(type(a[0])) for a in check_args] ) ) else: # implies not correct type self.logger.lraise( "unrecognized type for either index_cols or use_cols " "should be str or int, not {0}".format(type(check_args[0][0])) ) # checking no overlap between index_cols and use_cols if len(check_args) > 1: si = set(index_cols) su = set(use_cols) i = si.intersection(su) if len(i) > 0: self.logger.lraise(f"use_cols also listed in index_cols: {str(i)}") file_path = self.new_d / filename if not os.path.exists(file_path): self.logger.lraise(f"par/obs filename '{file_path}' not found ") self.logger.log(f"reading list-style file: {file_path}") if fmt.lower() == "free": if sep is None: sep = r"\s+" if Path(filename).suffix == ".csv": sep = "," else: # TODO support reading fixed-format # (based on value of fmt passed) # ... or not? self.logger.warn( "0) Only reading free format list-style par " "files currently supported." ) self.logger.warn("1) Assuming safe to read as whitespace delim.") self.logger.warn("2) Desired format string will still be passed through") sep = r"\s+" try: # read each input file if skip > 0 or c_char is not None: if c_char is None: with open(file_path, "r") as fp: storehead = { lp: line for lp, line in enumerate(fp) if lp < skip } else: with open(file_path, "r") as fp: storehead = { lp: line for lp, line in enumerate(fp) if lp < skip or line.strip().startswith(c_char) } else: storehead = {} except TypeError: c_char = skip skip = None with open(file_path, "r") as fp: storehead = { lp: line for lp, line in enumerate(fp) if line.strip().startswith(c_char) } df = pd.read_csv( file_path, comment=c_char, sep=sep, skiprows=skip, header=header, low_memory=False, ) self.logger.log(f"reading list-style file: {file_path}") # ensure that column ids from index_col is in input file missing = [] for index_col in index_cols: if index_col not in df.columns: missing.append(index_col) # df.loc[:, index_col] = df.loc[:, index_col].astype(np.int64) # TODO int? why? if len(missing) > 0: self.logger.lraise( "the following index_cols were not " "found in file '{0}':{1}" "".format(file_path, str(missing)) ) # ensure requested use_cols are in input file if use_cols is not None: for use_col in use_cols: if use_col not in df.columns: missing.append(use_cols) if len(missing) > 0: self.logger.lraise( "the following use_cols were not found " "in file '{0}':{1}" "".format(file_path, str(missing)) ) return df, storehead, sep def _prep_arg_list_lengths( self, filenames, fmts=None, seps=None, skip_rows=None, index_cols=None, use_cols=None, ): """ Private wrapper function to align filenames, formats, delimiters, reading options and setup columns for passing sequentially to load_listtype Args: filenames (`str`) or (`list`): names for files ot eventually read fmts (`str`) or (`list`): of column formaters for input file. If `None`, free-formatting is assumed seps (`str`) or (`list`): column separator free formatter files. If `None`, a list of `None`s is returned and the delimiter is eventually governed by the file extension (`,` for .csv) skip_rows (`str`) or (`list`): Number of rows in file header to not form part of the dataframe index_cols (`int`) or (`list`): Columns in tabular file to use as indicies use_cols (`int`) or (`list`): Columns in tabular file to use as par or obs cols Returns: algined lists of: filenames, fmts, seps, skip_rows, index_cols, use_cols for squentially passing to `_load_listtype_file()` """ if not isinstance(filenames, list): filenames = [filenames] if fmts is None: fmts = ["free" for _ in filenames] if not isinstance(fmts, list): fmts = [fmts] if len(fmts) != len(filenames): self.logger.warn( "Discrepancy between number of filenames ({0}) " "and number of formatter strings ({1}). " "Will repeat first ({2})" "".format(len(filenames), len(fmts), fmts[0]) ) fmts = [fmts[0] for _ in filenames] fmts = ["free" if fmt is None else fmt for fmt in fmts] if seps is None: seps = [None for _ in filenames] if not isinstance(seps, list): seps = [seps] if len(seps) != len(filenames): self.logger.warn( "Discrepancy between number of filenames ({0}) " "and number of seps defined ({1}). " "Will repeat first ({2})" "".format(len(filenames), len(seps), seps[0]) ) seps = [seps[0] for _ in filenames] if skip_rows is None: skip_rows = [None for _ in filenames] if not isinstance(skip_rows, list): skip_rows = [skip_rows] if len(skip_rows) != len(filenames): self.logger.warn( "Discrepancy between number of filenames ({0}) " "and number of skip_rows defined ({1}). " "Will repeat first ({2})" "".format(len(filenames), len(skip_rows), skip_rows[0]) ) skip_rows = [skip_rows[0] for _ in filenames] skip_rows = [0 if s is None else s for s in skip_rows] if index_cols is None and use_cols is not None: self.logger.lraise( "index_cols is None, but use_cols is not ({0})" "".format(str(use_cols)) ) if index_cols is not None: if not isinstance(index_cols, list): index_cols = [index_cols] if use_cols is not None: if not isinstance(use_cols, list): use_cols = [use_cols] return filenames, fmts, seps, skip_rows, index_cols, use_cols def write_list_tpl( filenames, dfs, name, tpl_filename, index_cols, par_type, use_cols=None, use_rows=None, suffix="", zone_array=None, gpname=None, get_xy=None, ij_in_idx=None, xy_in_idx=None, zero_based=True, input_filename=None, par_style="m", headerlines=None, fill_value=1.0, logger=None, ): """Write template files for a list style input. Args: filenames (`str` of `container` of `str`): original input filenames dfs (`pandas.DataFrame` or `container` of pandas.DataFrames): pandas representations of input file. name (`str` or container of str): parameter name prefixes. If more that one column to be parameterised, must be a container of strings providing the prefix for the parameters in the different columns. tpl_filename (`str`): Path (from current execution directory) for desired template file index_cols (`list`): column names to use as indices in tabular input dataframe par_type (`str`): 'constant','zone', or 'grid' used in parname generation. If `constant`, one par is set up for each `use_cols`. If `zone`, one par is set up for each zone for each `use_cols`. If `grid`, one par is set up for every unique index combination (from `index_cols`) for each `use_cols`. use_cols (`list`): Columns in tabular input file to paramerterise. If None, pars are set up for all columns apart from index cols. use_rows (`list` of `int` or `tuple`): Setup parameters for only specific rows in list-style model input file. If list of `int` -- assumed to be a row index selction (zero-based). If list of `tuple` -- assumed to be selection based `index_cols` values. e.g. [(3,5,6)] would attempt to set parameters where the model file values for 3 `index_cols` are 3,5,6. N.B. values in tuple are actual model file entry values. If no rows in the model input file match `use_rows` -- parameters will be set up for all rows. Only valid/effective if index_cols is not None. Default is None -- setup parameters for all rows. suffix (`str`): Optional par name suffix zone_array (`np.ndarray`): Array defining zone divisions. If not None and `par_type` is `grid` or `zone` it is expected that `index_cols` provide the indicies for querying `zone_array`. Therefore, array dimension should equal `len(index_cols)`. get_xy (`pyemu.PstFrom` method): Can be specified to get real-world xy from `index_cols` passed (to assist correlation definition) ij_in_idx (`list` or `array`): defining which `index_cols` contain i,j xy_in_idx (`list` or `array`): defining which `index_cols` contain x,y zero_based (`boolean`): IMPORTANT - pass as False if `index_cols` are NOT zero-based indicies (e.g. MODFLOW row/cols). If False 1 with be subtracted from `index_cols`. input_filename (`str`): Path to input file (paired with tpl file) par_style (`str`): either 'd','a', or 'm' headerlines ([`str`]): optional header lines in the original model file, used for direct style parameters Returns: `pandas.DataFrame`: dataframe with info for the new parameters Note: This function is called by `PstFrom` programmatically """ # get dataframe with autogenerated parnames based on `name`, `index_cols`, # `use_cols`, `suffix` and `par_type` if par_style == "d": df_tpl = _write_direct_df_tpl( filenames[0], tpl_filename, dfs[0], name, index_cols, par_type, use_cols=use_cols, use_rows=use_rows, suffix=suffix, gpname=gpname, zone_array=zone_array, get_xy=get_xy, ij_in_idx=ij_in_idx, xy_in_idx=xy_in_idx, zero_based=zero_based, headerlines=headerlines, logger=logger, ) else: df_tpl = _get_tpl_or_ins_df( dfs, name, index_cols, par_type, use_cols=use_cols, suffix=suffix, gpname=gpname, zone_array=zone_array, get_xy=get_xy, ij_in_idx=ij_in_idx, xy_in_idx=xy_in_idx, zero_based=zero_based, par_fill_value=fill_value, par_style=par_style, ) if use_rows is None: use_rows = df_tpl.index else: use_rows = _get_use_rows( df_tpl, use_rows, zero_based, tpl_filename, logger=logger ) df_tpl = df_tpl.loc[use_rows, :] # direct pars done in direct function # can we just slice df_tpl here for col in use_cols: # corellations flagged using pargp df_tpl["covgp{0}".format(col)] = df_tpl.loc[:, "pargp{0}".format(col)].values # needs modifying if colocated pars in same group if par_type == "grid" and "x" in df_tpl.columns: if df_tpl.duplicated(["x", "y"]).any(): # may need to use a different grouping for parameter correlations # where parameter x and y values are the same but pars are not # correlated (e.g. 2d correlation but different layers) # - this will only work if `index_cols` contains a third dimension. if len(index_cols) > 2: third_d = index_cols.copy() if xy_in_idx is not None: for idx in xy_in_idx: third_d.remove(index_cols[idx]) elif ij_in_idx is not None: for idx in ij_in_idx: third_d.remove(index_cols[idx]) else: # if xy_in_idx and ij_in_idx ar None # then parse_kij assumes that i is at idx[-2] and j at idx[-1] third_d.pop() # pops -1 third_d.pop() # pops -2 msg = ( "Coincidently located pars in list-style file, " "attempting to separate pars based on `index_cols` " f"passed - using index_col[{third_d[-1]}] " f"for third dimension" ) if logger is not None: logger.warn(msg) else: PyemuWarning(msg) for col in use_cols: df_tpl["covgp{0}".format(col)] = df_tpl.loc[ :, "covgp{0}".format(col) ].str.cat( pd.DataFrame(df_tpl.sidx.to_list()).iloc[:, 0].astype(str), "_cov", ) else: msg = ( "Coincidently located pars in list-style file. " "Likely to cause issues building par cov or " "drawing par ensemble. Can be resolved by passing " "an additional `index_col` as a basis for " "splitting colocated correlations (e.g. Layer)" ) if logger is not None: logger.warn(msg) else: PyemuWarning(msg) # pull out par details where multiple `use_cols` are requested parnme = list(df_tpl.loc[:, use_cols].values.flatten()) pargp = list( df_tpl.loc[:, ["pargp{0}".format(col) for col in use_cols]].values.flatten() ) covgp = list( df_tpl.loc[:, ["covgp{0}".format(col) for col in use_cols]].values.flatten() ) df_tpl = df_tpl.drop( [col for col in df_tpl.columns if str(col).startswith("covgp")], axis=1 ) df_par = pd.DataFrame( {"parnme": parnme, "pargp": pargp, "covgp": covgp}, index=parnme ) parval_cols = [c for c in df_tpl.columns if "parval1" in str(c)] parval = list(df_tpl.loc[:, [pc for pc in parval_cols]].values.flatten()) if ( par_type == "grid" and "x" in df_tpl.columns ): # TODO work out if x,y needed for constant and zone pars too df_par["x"], df_par["y"] = np.concatenate( df_tpl.apply(lambda r: [[r.x, r.y] for _ in use_cols], axis=1).values ).T for use_col in use_cols: df_tpl.loc[:, use_col] = df_tpl.loc[:, use_col].apply( lambda x: "~ {0} ~".format(x) ) if par_style in ["m", "a"]: pyemu.helpers._write_df_tpl( filename=tpl_filename, df=df_tpl, sep=",", tpl_marker="~" ) if input_filename is not None: df_in = df_tpl.copy() df_in.loc[:, use_cols] = fill_value df_in.to_csv(input_filename) df_par.loc[:, "tpl_filename"] = tpl_filename df_par.loc[:, "input_filename"] = input_filename df_par.loc[:, "parval1"] = parval return df_par def _write_direct_df_tpl( in_filename, tpl_filename, df, name, index_cols, typ, use_cols=None, use_rows=None, suffix="", zone_array=None, get_xy=None, ij_in_idx=None, xy_in_idx=None, zero_based=True, gpname=None, headerlines=None, logger=None, ): """ Private method to auto-generate parameter or obs names from tabular model files (input or output) read into pandas dataframes Args: tpl_filename (`str` ): template filename df (`pandas.DataFrame`): DataFrame of list-style input file name (`str`): Parameter name prefix index_cols (`str` or `list`): columns of dataframes to use as indicies typ (`str`): 'constant','zone', or 'grid' used in parname generation. If `constant`, one par is set up for each `use_cols`. If `zone`, one par is set up for each zone for each `use_cols`. If `grid`, one par is set up for every unique index combination (from `index_cols`) for each `use_cols`. use_cols (`list`): Columns to parameterise. If None, pars are set up for all columns apart from index cols suffix (`str`): Optional par name suffix. zone_array (`np.ndarray`): Array defining zone divisions. If not None and `par_type` is `grid` or `zone` it is expected that `index_cols` provide the indicies for querying `zone_array`. Therefore, array dimension should equal `len(index_cols)`. get_xy (`pyemu.PstFrom` method): Can be specified to get real-world xy from `index_cols` passed (to include in obs/par name) ij_in_idx (`list` or `array`): defining which `index_cols` contain i,j xy_in_idx (`list` or `array`): defining which `index_cols` contain x,y zero_based (`boolean`): IMPORTANT - pass as False if `index_cols` are NOT zero-based indicies (e.g. MODFLOW row/cols). If False 1 with be subtracted from `index_cols`. Returns: pandas.DataFrame with paranme and pargroup define for each `use_col` Note: This function is called by `PstFrom` programmatically """ # TODO much of this duplicates what is in _get_tpl_or_ins_df() -- could posssibly be consolidated # work out the union of indices across all dfs sidx = [] didx = df.loc[:, index_cols].apply(tuple, axis=1) sidx.extend(didx) df_ti = pd.DataFrame({"sidx": sidx}, columns=["sidx"]) inames, fmt = _get_index_strfmt(index_cols) df_ti = _get_index_strings(df_ti, fmt, zero_based) df_ti = _getxy_from_idx(df_ti, get_xy, xy_in_idx, ij_in_idx) df_ti, direct_tpl_df = _build_parnames( df_ti, typ, zone_array, index_cols, use_cols, name, gpname, suffix, par_style="d", init_df=df, init_fname=in_filename, ) if use_rows is None: use_rows = df_ti.index else: use_rows = _get_use_rows( df_ti, use_rows, zero_based, tpl_filename, logger=logger ) df_ti = df_ti.loc[use_rows] not_rows = ~direct_tpl_df.index.isin(use_rows) direct_tpl_df.loc[not_rows] = df.loc[not_rows, direct_tpl_df.columns] if isinstance(direct_tpl_df.columns[0], str): header = True else: header = False pyemu.helpers._write_df_tpl( tpl_filename, direct_tpl_df, index=False, header=header, headerlines=headerlines ) return df_ti def _get_use_rows(df, use_rows, zero_based, fnme, logger=None): """ private function to get use_rows index within df based on passed use_rows option, which could be in various forms... Args: df: use_rows: Returns: """ if ( isinstance(use_rows, str) or isinstance(use_rows, tuple) or isinstance(use_rows, int) ): # we only 1 use_row but best in a list use_rows = [use_rows] if not zero_based: # assume passed indicies are 1 based try: # try and slice df_tpl assuming tuple of index ids passed # adjust possible passed tuple. use_rows = [ tuple([i - 1 if isinstance(i, int) else i for i in r]) if not isinstance(r, str) else r for r in use_rows ] # will error if use rows is just ints except TypeError: msg = "write_list_tpl: Assuming passed use_rows are zero-based ints!" if logger is not None: logger.statement(msg) else: warnings.warn(msg, PyemuWarning) # dont need to do anything if in because should be zero-based orig_use_rows = use_rows use_rows = set(use_rows) sel = df.sidx.isin(use_rows) | df.idx_strs.isin(use_rows) if not sel.any(): # use_rows must be ints inidx = list(use_rows.intersection(df.index)) missing = use_rows.difference(df.index) use_rows = df.iloc[inidx].index.unique() else: missing = set(use_rows).difference(df.sidx, df.idx_strs) use_rows = df.loc[sel].index.unique() if len(missing) > 0: msg = ( "write_list_tpl: Requested rows missing from parameter file, " f"rows: {missing}, file: {fnme}." ) if logger is not None: logger.warn(msg) else: warnings.warn(msg, PyemuWarning) if len(use_rows) == 0: msg = ( "write_list_tpl: None of request rows found in parameter file, " f"rows: {orig_use_rows}, file: {fnme}. " "Will set up pars for all rows." ) if logger is not None: logger.warn(msg) else: warnings.warn(msg, PyemuWarning) use_rows = df.index return use_rows def _get_index_strfmt(index_cols): # get some index strings for naming j = "_" # fmt = "{0}|{1}" if isinstance(index_cols[0], str): inames = index_cols else: inames = ["idx{0}".format(i) for i in range(len(index_cols))] # full formatter string fmt = j.join([f"{iname}|{{{i}}}" for i, iname in enumerate(inames)]) # else: # # fmt = "{1:3}" # j = "" # if isinstance(index_cols[0], str): # inames = index_cols # else: # inames = ["{0}".format(i) for i in range(len(index_cols))] # # full formatter string # fmt = j.join([f"{{{i}:3}}" for i, iname in enumerate(inames)]) return inames, fmt def _get_index_strings(df, fmt, zero_based): if not zero_based: # only if indices are ints (trying to support strings as par ids) df.loc[:, "sidx"] = df.sidx.apply( lambda x: tuple(xx - 1 if isinstance(xx, int) else xx for xx in x) ) df.loc[:, "idx_strs"] = df.sidx.apply(lambda x: fmt.format(*x)).str.replace(" ", "") df.loc[:, "idx_strs"] = df.idx_strs.str.replace(":", "", regex=False).str.lower() df.loc[:, "idx_strs"] = df.idx_strs.str.replace("|", ":", regex=False) return df def _getxy_from_idx(df, get_xy, xy_in_idx, ij_in_idx): if get_xy is None: return df if xy_in_idx is not None: df[["x", "y"]] = pd.DataFrame(df.sidx.to_list()).iloc[:, xy_in_idx] return df df.loc[:, "xy"] = df.sidx.apply(get_xy, ij_id=ij_in_idx) df.loc[:, "x"] = df.xy.apply(lambda x: x[0]) df.loc[:, "y"] = df.xy.apply(lambda x: x[1]) return df def _build_parnames( df, typ, zone_array, index_cols, use_cols, basename, gpname, suffix, par_style, init_df=None, init_fname=None, fill_value=1.0, ): if par_style == "d": assert init_df is not None direct_tpl_df = init_df.copy() if typ == "constant": assert init_fname is not None if use_cols is None: use_cols = [c for c in df.columns if c not in index_cols] # if direct, we have more to deal with... for iuc, use_col in enumerate(use_cols): if not isinstance(basename, str): nname = basename[iuc] # if zone type, find the zones for each index position else: nname = basename if zone_array is not None and typ in ["zone", "grid"]: if zone_array.ndim != len(index_cols): raise Exception( "get_tpl_or_ins_df() error: " "zone_array.ndim " "({0}) != len(index_cols)({1})" "".format(zone_array.ndim, len(index_cols)) ) df.loc[:, "zval"] = df.sidx.apply(lambda x: zone_array[x]) if gpname is None or gpname[iuc] is None: ngpname = nname else: if not isinstance(gpname, str): ngpname = gpname[iuc] else: ngpname = gpname df.loc[:, "pargp{}".format(use_col)] = ngpname df.loc[:, "parval1_{0}".format(use_col)] = fill_value if typ == "constant": # one par for entire use_col column fmtr = "pname:{0}_ptype:cn_usecol:{1}" fmtr += "_pstyle:{0}".format(par_style) if suffix != "": fmtr += f"_{suffix}" # else: # fmtr = "{0}{1}" # if suffix != "": # fmtr += suffix df.loc[:, use_col] = fmtr.format(nname, use_col) if par_style == "d": _check_diff(init_df.loc[:, use_col].values, init_fname) df.loc[:, "parval1_{0}".format(use_col)] = init_df.loc[:, use_col][0] elif typ == "zone": # one par for each zone fmtr = "pname:{0}_ptype:zn_usecol:{1}" if par_style == "d": # todo raise NotImplementedError( "list-style direct zone-type parameters not implemented" ) fmtr += "_pstyle:d" else: fmtr += "_pstyle:m" if zone_array is not None: fmtr += "_zone:{2}" # df.loc[:, use_col] += df.zval.apply( # lambda x: "_zone:{0}".format(x) # ) if suffix != "": fmtr += f"_{suffix}" # df.loc[:, use_col] += "_{0}".format(suffix) # else: # fmtr = "{0}{1}" # if zone_array is not None: # fmtr += "z{2}" # if suffix != "": # fmtr += suffix if zone_array is not None: df.loc[:, use_col] = df.zval.apply( lambda x: fmtr.format(nname, use_col, x) ) else: df.loc[:, use_col] = fmtr.format(nname, use_col) # todo: Direct pars: # check that values are constant within zones and assign parval1 elif typ == "grid": # one par for each index fmtr = "pname:{0}_ptype:gr_usecol:{1}" fmtr += "_pstyle:{0}".format(par_style) if zone_array is not None: fmtr += "_zone:{2}_{3}" else: fmtr += "_{2}" if suffix != "": fmtr += f"_{suffix}" if zone_array is not None: df.loc[:, use_col] = df.apply( lambda x: fmtr.format(nname, use_col, x.zval, x.idx_strs), axis=1 ) else: df.loc[:, use_col] = df.idx_strs.apply( lambda x: fmtr.format(nname, use_col, x) ) if par_style == "d": df.loc[:, f"parval1_{use_col}"] = init_df.loc[:, use_col].values else: raise Exception( "get_tpl_or_ins_df() error: " "unrecognized 'typ', if not 'obs', " "should be 'constant','zone', " "or 'grid', not '{0}'".format(typ) ) if par_style == "d": direct_tpl_df.loc[:, use_col] = ( df.loc[:, use_col].apply(lambda x: "~ {0} ~".format(x)).values ) if par_style == "d": return df, direct_tpl_df return df def _get_tpl_or_ins_df( dfs, name, index_cols, typ, use_cols=None, suffix="", zone_array=None, get_xy=None, ij_in_idx=None, xy_in_idx=None, zero_based=True, gpname=None, par_fill_value=1.0, par_style="m", ): """ Private method to auto-generate parameter or obs names from tabular model files (input or output) read into pandas dataframes Args: filenames (`str` or `list` of str`): filenames dfs (`pandas.DataFrame` or `list`): DataFrames (can be list of DataFrames) to set up parameters or observations name (`str`): Parameter name or Observation name prefix index_cols (`str` or `list`): columns of dataframes to use as indicies typ (`str`): 'obs' to set up observation names or, 'constant','zone', or 'grid' used in parname generation. If `constant`, one par is set up for each `use_cols`. If `zone`, one par is set up for each zone for each `use_cols`. If `grid`, one par is set up for every unique index combination (from `index_cols`) for each `use_cols`. use_cols (`list`): Columns to parameterise. If None, pars are set up for all columns apart from index cols. Not used if `typ`==`obs`. suffix (`str`): Optional par name suffix. Not used if `typ`==`obs`. zone_array (`np.ndarray`): Only used for paremeters (`typ` != `obs`). Array defining zone divisions. If not None and `par_type` is `grid` or `zone` it is expected that `index_cols` provide the indicies for querying `zone_array`. Therefore, array dimension should equal `len(index_cols)`. get_xy (`pyemu.PstFrom` method): Can be specified to get real-world xy from `index_cols` passed (to include in obs/par name) ij_in_idx (`list` or `array`): defining which `index_cols` contain i,j xy_in_idx (`list` or `array`): defining which `index_cols` contain x,y zero_based (`boolean`): IMPORTANT - pass as False if `index_cols` are NOT zero-based indicies (e.g. MODFLOW row/cols). If False 1 with be subtracted from `index_cols`.= par_fill_value (float): value to use as `parval1`,Default is 1.0 Returns: if `typ`==`obs`: pandas.DataFrame with index strings for setting up obs names when passing through to pyemu.pst_utils.csv_to_ins_file(df.set_index('idx_str') else: pandas.DataFrame with paranme and pargroup define for each `use_col` """ if isinstance(dfs, pd.DataFrame): dfs = [dfs] if not isinstance(dfs, list): dfs = list(dfs) # work out the union of indices across all dfs if typ != "obs": sidx = set() for df in dfs: # looses ordering didx = set(df.loc[:, index_cols].apply(lambda x: tuple(x), axis=1)) sidx.update(didx) else: # order matters for obs sidx = [] for df in dfs: didx = df.loc[:, index_cols].values aidx = [i for i in didx if i not in sidx] sidx.extend(aidx) df_ti = pd.DataFrame({"sidx": list(sidx)}, columns=["sidx"]) inames, fmt = _get_index_strfmt(index_cols) df_ti = _get_index_strings(df_ti, fmt, zero_based) df_ti = _getxy_from_idx(df_ti, get_xy, xy_in_idx, ij_in_idx) if typ == "obs": return df_ti #################### RETURN if OBS df_ti = _build_parnames( df_ti, typ, zone_array, index_cols, use_cols, name, gpname, suffix, par_style, fill_value=par_fill_value, ) return df_ti def write_array_tpl( name, tpl_filename, suffix, par_type, zone_array=None, gpname=None, shape=None, fill_value=1.0, get_xy=None, input_filename=None, par_style="m", ): """ write a template file for a 2D array. Args: name (`str`): the base parameter name tpl_filename (`str`): the template file to write - include path suffix (`str`): suffix to append to par names par_type (`str`): type of parameter zone_array (`numpy.ndarray`): an array used to skip inactive cells. Values less than 1 are not parameterized and are assigned a value of fill_value. Default is None. gpname (`str`): pargp filed in dataframe shape (`tuple`): dimensions of array to write fill_value: get_xy: input_filename: par_style (`str`): either 'd','a', or 'm' Returns: df (`pandas.DataFrame`): a dataframe with parameter information Note: This function is called by `PstFrom` programmatically """ if shape is None and zone_array is None: raise Exception( "write_array_tpl() error: must pass either zone_array " "or shape" ) elif shape is not None and zone_array is not None: if shape != zone_array.shape: raise Exception( "write_array_tpl() error: passed " "shape {0} != zone_array.shape {1}".format(shape, zone_array.shape) ) elif shape is None: shape = zone_array.shape if len(shape) != 2: raise Exception( "write_array_tpl() error: shape '{0}' not 2D" "".format(str(shape)) ) par_style = par_style.lower() if par_style == "d": if not os.path.exists(input_filename): raise Exception( "write_grid_tpl() error: couldn't find input file " + " {0}, which is required for 'direct' par_style".format( input_filename ) ) org_arr = np.loadtxt(input_filename, ndmin=2) if par_type == "grid": pass elif par_type == "constant": _check_diff(org_arr, input_filename) elif par_type == "zone": for zval in np.unique(zone_array): if zval < 1: continue zone_org_arr = org_arr.copy() zone_org_arr[zone_array != zval] = np.NaN _check_diff(zone_org_arr, input_filename, zval) elif par_style == "m": org_arr = np.ones(shape) elif par_style == "a": org_arr = np.zeros(shape) else: raise Exception( "write_grid_tpl() error: unrecognized 'par_style' {0} ".format(par_style) + "should be 'd','a', or 'm'" ) def constant_namer(i, j): pname = "pname:{1}_ptype:cn_pstyle:{0}".format(par_style, name) if suffix != "": pname += "_{0}".format(suffix) return pname def zone_namer(i, j): zval = 1 if zone_array is not None: zval = zone_array[i, j] pname = "pname:{1}_ptype:zn_pstyle:{0}_zone:{2}".format( par_style, name, zval ) if suffix != "": pname += "_{0}".format(suffix) return pname def grid_namer(i, j): pname = "pname:{1}_ptype:gr_pstyle:{0}_i:{2}_j:{3}".format( par_style, name, i, j ) if get_xy is not None: pname += "_x:{0:0.2f}_y:{1:0.2f}".format( *get_xy([i, j], ij_id=[0, 1])) if zone_array is not None: pname += "_zone:{0}".format(zone_array[i, j]) if suffix != "": pname += "_{0}".format(suffix) return pname if par_type == "constant": namer = constant_namer elif par_type == "zone": namer = zone_namer elif par_type == "grid": namer = grid_namer else: raise Exception( "write_array_tpl() error: unsupported par_type" ", options are 'constant', 'zone', or 'grid', not" "'{0}'".format(par_type) ) parnme = [] org_par_val_dict = {} xx, yy, ii, jj = [], [], [], [] with open(tpl_filename, "w") as f: f.write("ptf ~\n") for i in range(shape[0]): for j in range(shape[1]): if zone_array is not None and zone_array[i, j] < 1: pname = " {0} ".format(fill_value) else: if get_xy is not None: x, y = get_xy([i, j], ij_id=[0, 1]) xx.append(x) yy.append(y) ii.append(i) jj.append(j) pname = namer(i, j) parnme.append(pname) org_par_val_dict[pname] = org_arr[i, j] pname = " ~ {0} ~".format(pname) f.write(pname) f.write("\n") df = pd.DataFrame({"parnme": parnme}, index=parnme) df.loc[:, "parval1"] = df.parnme.apply(lambda x: org_par_val_dict[x]) if par_type == "grid": df.loc[:, "i"] = ii df.loc[:, "j"] = jj if get_xy is not None: df.loc[:, "x"] = xx df.loc[:, "y"] = yy if gpname is None: gpname = name df.loc[:, "pargp"] = "{0}_{1}".format(gpname, suffix.replace("_", "")).rstrip("_") df.loc[:, "tpl_filename"] = tpl_filename df.loc[:, "input_filename"] = input_filename if input_filename is not None: if par_style in ["m", "d"]: arr = np.ones(shape) elif par_style == "a": arr = np.zeros(shape) np.savetxt(input_filename, arr, fmt="%2.1f") return df def _check_diff(org_arr, input_filename, zval=None): percent_diff = 100.0 * np.abs( (np.nanmax(org_arr) - np.nanmin(org_arr)) / np.nanmean(org_arr) ) if percent_diff > DIRECT_PAR_PERCENT_DIFF_TOL: message = "_check_diff() error: direct par for file '{0}'".format( input_filename ) + "exceeds tolerance for percent difference: {0} > {1}".format( percent_diff, DIRECT_PAR_PERCENT_DIFF_TOL ) if zval is not None: message += " in zone {0}".format(zval) raise Exception(message) def get_filepath(folder, filename): """Return a path to a file within a folder, without repeating the folder in the output path, if the input filename (path) already contains the folder.""" filename = Path(filename) folder = Path(folder) if folder not in filename.parents: filename = folder / filename return filename def get_relative_filepath(folder, filename): """Like :func:`~pyemu.utils.pst_from.get_filepath`, except return path for filename relative to folder. """ return get_filepath(folder, filename).relative_to(folder)
jtwhite79/pyemu
pyemu/utils/pst_from.py
Python
bsd-3-clause
164,481
[ "Gaussian" ]
d73c5df9bc0d2b97d6103ca2be056f16dea60a18b93183cb65fe1e7d7afb3b1e
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from distutils.util import strtobool def yn_prompt(query): """Generic Y/N Prompt""" sys.stdout.write('%s [y/n]: ' % query) val = raw_input() try: ret = strtobool(val) except ValueError: sys.stdout.write('Please answer with a y/n\n') return yn_prompt(query) return ret # prompts install = yn_prompt("\nInstall UCP using 'non-interactive' mode on the controller instance?") if install: txt = 'docker run --rm --name ucp -v /var/run/docker.sock:/var/run/docker.sock docker/ucp install --host-address $(curl http://169.254.169.254/latest/meta-data/public-hostname)' else: txt = 'docker run --name ucp --rm -v /var/run/docker.sock:/var/run/docker.sock docker/ucp images' # scripts PRIMARY_OS = 'Ubuntu-14.04' CONTROLLER = '''#!/bin/sh FQDN="{{fqdn}}" export DEBIAN_FRONTEND=noninteractive # locale sudo locale-gen en_US.UTF-8 # /etc/hostname - /etc/hosts sed -i "1 c\\127.0.0.1 $FQDN localhost" /etc/hosts echo $FQDN > /etc/hostname service hostname restart sleep 5 # docker curl -sSL https://get.docker.com/ | sh usermod -aG docker ubuntu # docker compose curl -L https://github.com/docker/compose/releases/download/1.6.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose # packages apt-get install -y git tree jq # download/install upc {0} {{dinfo}} '''.format(txt) NODE = '''#!/bin/sh FQDN="{fqdn}" export DEBIAN_FRONTEND=noninteractive # locale sudo locale-gen en_US.UTF-8 # /etc/hostname - /etc/hosts sed -i "1 c\\127.0.0.1 $FQDN localhost" /etc/hosts echo $FQDN > /etc/hostname service hostname restart sleep 5 # docker curl -sSL https://get.docker.com/ | sh usermod -aG docker ubuntu # docker compose curl -L https://github.com/docker/compose/releases/download/1.6.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose # packages apt-get install -y git tree jq # download upc docker run --name ucp --rm -v /var/run/docker.sock:/var/run/docker.sock docker/ucp images {dinfo} ''' AMIBUILD = '''#!/bin/sh # FQDN="{{fqdn}}" # /etc/hostname - /etc/hosts sed -i "1 c\\127.0.0.1 $FQDN localhost" /etc/hosts echo $FQDN > /etc/hostname service hostname restart sleep 5 {{dinfo}} reboot ''' def pre_process(): """Executed before launching instances in AWS""" pass def post_process(): """Executed after launching instances in AWS""" print "Instances Launched ...\n\nNOTE: If you selected the non-interactive install during launch the default user/pass is: admin/orca\n"
danielpalstra/train
train/labs/ucp/scripts/ubuntu-14.04.py
Python
apache-2.0
2,641
[ "ORCA" ]
5641a72619bea999791decb2f4683ed861443497a6d62669efc7de431e76231d
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"), url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name="about"), # Django Admin, use {% url 'admin:index' %} url(settings.ADMIN_URL, include(admin.site.urls)), # User management url(r'^users/', include("Reddit_Clone.users.urls", namespace="users")), url(r'^accounts/', include('allauth.urls')), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: # This allows the error pages to be debugged during development, just visit # these url in browser to see how these error pages look like. urlpatterns += [ url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception("Bad Request!")}), url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception("Permissin Denied")}), url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception("Page not Found")}), url(r'^500/$', default_views.server_error), ]
akarambir/reddit-clone
config/urls.py
Python
mit
1,435
[ "VisIt" ]
55dd98a9241de77ff253eb8bbf2e0f3b136859253c48492eac91fda94325f340
"""User-friendly public interface to polynomial functions. """ from sympy.core import ( S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple, Rational ) from sympy.core.mul import _keep_coeff from sympy.core.sympify import ( sympify, SympifyError, ) from sympy.core.decorators import ( _sympifyit, ) from sympy.polys.polyclasses import DMP from sympy.polys.polyutils import ( basic_from_dict, _sort_gens, _unify_gens, _dict_reorder, _dict_from_expr, _parallel_dict_from_expr, ) from sympy.polys.rationaltools import ( together, ) from sympy.polys.rootisolation import ( dup_isolate_real_roots_list, ) from sympy.polys.distributedpolys import ( sdp_from_dict, sdp_div, ) from sympy.polys.groebnertools import ( sdp_groebner, matrix_fglm, ) from sympy.polys.monomialtools import ( Monomial, monomial_key, ) from sympy.polys.polyerrors import ( OperationNotSupported, DomainError, CoercionFailed, UnificationFailed, GeneratorsNeeded, PolynomialError, MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, GeneratorsError, ) from sympy.utilities import group import sympy.polys import sympy.mpmath from sympy.polys.domains import FF, QQ from sympy.polys.constructor import construct_domain from sympy.polys import polyoptions as options from sympy.core.compatibility import iterable class Poly(Expr): """Generic class for representing polynomial expressions. """ __slots__ = ['rep', 'gens'] is_commutative = True is_Poly = True def __new__(cls, rep, *gens, **args): """Create a new polynomial instance out of something useful. """ opt = options.build_options(gens, args) if 'order' in opt: raise NotImplementedError("'order' keyword is not implemented yet") if iterable(rep, exclude=str): if isinstance(rep, dict): return cls._from_dict(rep, opt) else: return cls._from_list(list(rep), opt) else: rep = sympify(rep) if rep.is_Poly: return cls._from_poly(rep, opt) else: return cls._from_expr(rep, opt) @classmethod def new(cls, rep, *gens): """Construct :class:`Poly` instance from raw representation. """ if not isinstance(rep, DMP): raise PolynomialError("invalid polynomial representation: %s" % rep) elif rep.lev != len(gens)-1: raise PolynomialError("invalid arguments: %s, %s" % (rep, gens)) obj = Basic.__new__(cls) obj.rep = rep obj.gens = gens return obj @classmethod def from_dict(cls, rep, *gens, **args): """Construct a polynomial from a ``dict``. """ opt = options.build_options(gens, args) return cls._from_dict(rep, opt) @classmethod def from_list(cls, rep, *gens, **args): """Construct a polynomial from a ``list``. """ opt = options.build_options(gens, args) return cls._from_list(rep, opt) @classmethod def from_poly(cls, rep, *gens, **args): """Construct a polynomial from a polynomial. """ opt = options.build_options(gens, args) return cls._from_poly(rep, opt) @classmethod def from_expr(cls, rep, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return cls._from_expr(rep, opt) @classmethod def _from_dict(cls, rep, opt): """Construct a polynomial from a ``dict``. """ gens = opt.gens if not gens: raise GeneratorsNeeded("can't initialize from 'dict' without generators") level = len(gens)-1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: for monom, coeff in rep.iteritems(): rep[monom] = domain.convert(coeff) return cls.new(DMP.from_dict(rep, level, domain), *gens) @classmethod def _from_list(cls, rep, opt): """Construct a polynomial from a ``list``. """ gens = opt.gens if not gens: raise GeneratorsNeeded("can't initialize from 'list' without generators") elif len(gens) != 1: raise MultivariatePolynomialError("'list' representation not supported") level = len(gens)-1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: rep = map(domain.convert, rep) return cls.new(DMP.from_list(rep, level, domain), *gens) @classmethod def _from_poly(cls, rep, opt): """Construct a polynomial from a polynomial. """ if cls != rep.__class__: rep = cls.new(rep.rep, *rep.gens) gens = opt.gens field = opt.field domain = opt.domain if gens and rep.gens != gens: if set(rep.gens) != set(gens): return cls._from_expr(rep.as_expr(), opt) else: rep = rep.reorder(*gens) if 'domain' in opt and domain: rep = rep.set_domain(domain) elif field is True: rep = rep.to_field() return rep @classmethod def _from_expr(cls, rep, opt): """Construct a polynomial from an expression. """ rep, opt = _dict_from_expr(rep, opt) return cls._from_dict(rep, opt) def _hashable_content(self): """Allow SymPy to hash Poly instances. """ return (self.rep, self.gens) def __hash__(self): return super(Poly, self).__hash__() @property def free_symbols(self): """ Free symbols of a polynomial expression. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols set([x]) >>> Poly(x**2 + y).free_symbols set([x, y]) >>> Poly(x**2 + y, x).free_symbols set([x, y]) """ symbols = set([]) for gen in self.gens: symbols |= gen.free_symbols return symbols | self.free_symbols_in_domain @property def free_symbols_in_domain(self): """ Free symbols of the domain of ``self``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols_in_domain set() >>> Poly(x**2 + y).free_symbols_in_domain set() >>> Poly(x**2 + y, x).free_symbols_in_domain set([y]) """ domain, symbols = self.rep.dom, set() if domain.is_Composite: for gen in domain.gens: symbols |= gen.free_symbols elif domain.is_EX: for coeff in self.coeffs(): symbols |= coeff.free_symbols return symbols @property def args(self): """ Don't mess up with the core. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).args (x**2 + 1,) """ return (self.as_expr(),) @property def gen(self): """ Return the principal generator. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).gen x """ return self.gens[0] @property def domain(self): """Get the ground domain of ``self``. """ return self.get_domain() @property def zero(self): """Return zero polynomial with ``self``'s properties. """ return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens) @property def one(self): """Return one polynomial with ``self``'s properties. """ return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens) @property def unit(self): """Return unit polynomial with ``self``'s properties. """ return self.new(self.rep.unit(self.rep.lev, self.rep.dom), *self.gens) def unify(f, g): """ Make ``f`` and ``g`` belong to the same domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f, g = Poly(x/2 + 1), Poly(2*x + 1) >>> f Poly(1/2*x + 1, x, domain='QQ') >>> g Poly(2*x + 1, x, domain='ZZ') >>> F, G = f.unify(g) >>> F Poly(1/2*x + 1, x, domain='QQ') >>> G Poly(2*x + 1, x, domain='QQ') """ _, per, F, G = f._unify(g) return per(F), per(G) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("can't unify %s with %s" % (f, g)) if isinstance(f.rep, DMP) and isinstance(g.rep, DMP): gens = _unify_gens(f.gens, g.gens) dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens)-1 if f.gens != gens: f_monoms, f_coeffs = _dict_reorder(f.rep.to_dict(), f.gens, gens) if f.rep.dom != dom: f_coeffs = [ dom.convert(c, f.rep.dom) for c in f_coeffs ] F = DMP(dict(zip(f_monoms, f_coeffs)), dom, lev) else: F = f.rep.convert(dom) if g.gens != gens: g_monoms, g_coeffs = _dict_reorder(g.rep.to_dict(), g.gens, gens) if g.rep.dom != dom: g_coeffs = [ dom.convert(c, g.rep.dom) for c in g_coeffs ] G = DMP(dict(zip(g_monoms, g_coeffs)), dom, lev) else: G = g.rep.convert(dom) else: raise UnificationFailed("can't unify %s with %s" % (f, g)) cls = f.__class__ def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove]+gens[remove+1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G def per(f, rep, gens=None, remove=None): """ Create a Poly out of the given representation. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x, y >>> from sympy.polys.polyclasses import DMP >>> a = Poly(x**2 + 1) >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y]) Poly(y + 1, y, domain='ZZ') """ if gens is None: gens = f.gens if remove is not None: gens = gens[:remove]+gens[remove+1:] if not gens: return f.rep.dom.to_sympy(rep) return f.__class__.new(rep, *gens) def set_domain(f, domain): """Set the ground domain of ``f``. """ opt = options.build_options(f.gens, {'domain': domain}) return f.per(f.rep.convert(opt.domain)) def get_domain(f): """Get the ground domain of ``f``. """ return f.rep.dom def set_modulus(f, modulus): """ Set the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2) Poly(x**2 + 1, x, modulus=2) """ modulus = options.Modulus.preprocess(modulus) return f.set_domain(FF(modulus)) def get_modulus(f): """ Get the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, modulus=2).get_modulus() 2 """ domain = f.get_domain() if not domain.has_CharacteristicZero: return Integer(domain.characteristic()) else: raise PolynomialError("not a polynomial over a Galois field") def _eval_subs(f, old, new): """Internal implementation of :func:`subs`. """ if old in f.gens: if new.is_number: return f.eval(old, new) else: try: return f.replace(old, new) except PolynomialError: pass return f.as_expr().subs(old, new) def exclude(f): """ Remove unnecessary generators from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import a, b, c, d, x >>> Poly(a + x, a, b, c, d, x).exclude() Poly(a + x, a, x, domain='ZZ') """ J, new = f.rep.exclude() gens = [] for j in range(len(f.gens)): if j not in J: gens.append(f.gens[j]) return f.per(new, gens=gens) def replace(f, x, y=None): """ Replace ``x`` with ``y`` in generators list. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1, x).replace(x, y) Poly(y**2 + 1, y, domain='ZZ') """ if y is None: if f.is_univariate: x, y = f.gen, x else: raise PolynomialError("syntax supported only in univariate case") if x == y: return f if x in f.gens and y not in f.gens: dom = f.get_domain() if not dom.is_Composite or y not in dom.gens: gens = list(f.gens) gens[gens.index(x)] = y return f.per(f.rep, gens=gens) raise PolynomialError("can't replace %s with %s in %s" % (x, y, f)) def reorder(f, *gens, **args): """ Efficiently apply new order of generators. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y**2, x, y).reorder(y, x) Poly(y**2*x + x**2, y, x, domain='ZZ') """ opt = options.Options((), args) if not gens: gens = _sort_gens(f.gens, opt=opt) elif set(f.gens) != set(gens): raise PolynomialError("generators list can differ only up to order of elements") rep = dict(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens))) return f.per(DMP(rep, f.rep.dom, len(gens)-1), gens=gens) def ltrim(f, gen): """ Remove dummy generators from the "left" of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y) Poly(y**2 + y*z**2, y, z, domain='ZZ') """ rep = f.as_dict(native=True) j = f._gen_to_level(gen) terms = {} for monom, coeff in rep.iteritems(): monom = monom[j:] if monom not in terms: terms[monom] = coeff else: raise PolynomialError("can't left trim %s" % f) gens = f.gens[j:] return f.new(DMP.from_dict(terms, len(gens)-1, f.rep.dom), *gens) def has_only_gens(f, *gens): """ Return ``True`` if ``Poly(f, *gens)`` retains ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y) True >>> Poly(x*y + z, x, y, z).has_only_gens(x, y) False """ f_gens = list(f.gens) indices = set([]) for gen in gens: try: index = f_gens.index(gen) except ValueError: raise GeneratorsError("%s doesn't have %s as generator" % (f, gen)) else: indices.add(index) for monom in f.monoms(): for i, elt in enumerate(monom): if i not in indices and elt: return False return True def to_ring(f): """ Make the ground domain a ring. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, domain=QQ).to_ring() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'to_ring'): result = f.rep.to_ring() else: # pragma: no cover raise OperationNotSupported(f, 'to_ring') return f.per(result) def to_field(f): """ Make the ground domain a field. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(x**2 + 1, x, domain=ZZ).to_field() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_field'): result = f.rep.to_field() else: # pragma: no cover raise OperationNotSupported(f, 'to_field') return f.per(result) def to_exact(f): """ Make the ground domain exact. Examples ======== >>> from sympy import Poly, RR >>> from sympy.abc import x >>> Poly(x**2 + 1.0, x, domain=RR).to_exact() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_exact'): result = f.rep.to_exact() else: # pragma: no cover raise OperationNotSupported(f, 'to_exact') return f.per(result) def retract(f, field=None): """ Recalculate the ground domain of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 1, x, domain='QQ[y]') >>> f Poly(x**2 + 1, x, domain='QQ[y]') >>> f.retract() Poly(x**2 + 1, x, domain='ZZ') >>> f.retract(field=True) Poly(x**2 + 1, x, domain='QQ') """ dom, rep = construct_domain(f.as_dict(zero=True), field=field) return f.from_dict(rep, f.gens, domain=dom) def slice(f, x, m, n=None): """Take a continuous subsequence of terms of ``f``. """ if n is None: j, m, n = 0, x, m else: j = f._gen_to_level(x) m, n = int(m), int(n) if hasattr(f.rep, 'slice'): result = f.rep.slice(m, n, j) else: # pragma: no cover raise OperationNotSupported(f, 'slice') return f.per(result) def coeffs(f, order=None): """ Returns all non-zero coefficients from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x + 3, x).coeffs() [1, 2, 3] """ return [ f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order) ] def monoms(f, order=None): """ Returns all non-zero monomials from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms() [(2, 0), (1, 2), (1, 1), (0, 1)] """ return f.rep.monoms(order=order) def terms(f, order=None): """ Returns all non-zero terms from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms() [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)] """ return [ (m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order) ] def all_coeffs(f): """ Returns all coefficients from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_coeffs() [1, 0, 2, -1] """ return [ f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs() ] def all_monoms(f): """ Returns all monomials from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_monoms() [(3,), (2,), (1,), (0,)] """ return f.rep.all_monoms() def all_terms(f): """ Returns all terms from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_terms() [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)] """ return [ (m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms() ] def termwise(f, func, *gens, **args): """ Apply a function to all terms of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> def func((k,), coeff): ... return coeff//10**(2-k) >>> Poly(x**2 + 20*x + 400).termwise(func) Poly(x**2 + 2*x + 4, x, domain='ZZ') """ terms = {} for monom, coeff in f.terms(): result = func(monom, coeff) if isinstance(result, tuple): monom, coeff = result else: coeff = result if coeff: if monom not in terms: terms[monom] = coeff else: raise PolynomialError("%s monomial was generated twice" % monom) return f.from_dict(terms, *(gens or f.gens), **args) def length(f): """ Returns the number of non-zero terms in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x - 1).length() 3 """ return len(f.as_dict()) def as_dict(f, native=False, zero=False): """ Switch to a ``dict`` representation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict() {(0, 1): -1, (1, 2): 2, (2, 0): 1} """ if native: return f.rep.to_dict(zero=zero) else: return f.rep.to_sympy_dict(zero=zero) def as_list(f, native=False): """Switch to a ``list`` representation. """ if native: return f.rep.to_list() else: return f.rep.to_sympy_list() def as_expr(f, *gens): """ Convert a polynomial an expression. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 2*x*y**2 - y, x, y) >>> f.as_expr() x**2 + 2*x*y**2 - y >>> f.as_expr({x: 5}) 10*y**2 - y + 25 >>> f.as_expr(5, 6) 379 """ if not gens: gens = f.gens elif len(gens) == 1 and isinstance(gens[0], dict): mapping = gens[0] gens = list(f.gens) for gen, value in mapping.iteritems(): try: index = gens.index(gen) except ValueError: raise GeneratorsError("%s doesn't have %s as generator" % (f, gen)) else: gens[index] = value return basic_from_dict(f.rep.to_sympy_dict(), *gens) def lift(f): """ Convert algebraic coefficients to rationals. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**2 + I*x + 1, x, extension=I).lift() Poly(x**4 + 3*x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'lift'): result = f.rep.lift() else: # pragma: no cover raise OperationNotSupported(f, 'lift') return f.per(result) def deflate(f): """ Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate() ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'deflate'): J, result = f.rep.deflate() else: # pragma: no cover raise OperationNotSupported(f, 'deflate') return J, f.per(result) def inject(f, front=False): """ Inject ground domain generators into ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x) >>> f.inject() Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ') >>> f.inject(front=True) Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ') """ dom = f.rep.dom if dom.is_Numerical: return f elif not dom.is_Poly: raise DomainError("can't inject generators over %s" % dom) if hasattr(f.rep, 'inject'): result = f.rep.inject(front=front) else: # pragma: no cover raise OperationNotSupported(f, 'inject') if front: gens = dom.gens + f.gens else: gens = f.gens + dom.gens return f.new(result, *gens) def eject(f, *gens): """ Eject selected generators into the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) >>> f.eject(x) Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') >>> f.eject(y) Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') """ dom = f.rep.dom if not dom.is_Numerical: raise DomainError("can't eject generators over %s" % dom) n, k = len(f.gens), len(gens) if f.gens[:k] == gens: _gens, front = f.gens[n-k:], True elif f.gens[-k:] == gens: _gens, front = f.gens[:n-k], False else: raise NotImplementedError("can only eject front or back generators") dom = dom.inject(*gens) if hasattr(f.rep, 'eject'): result = f.rep.eject(dom, front=front) else: # pragma: no cover raise OperationNotSupported(f, 'eject') return f.new(result, *_gens) def terms_gcd(f): """ Remove GCD of terms from the polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd() ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'terms_gcd'): J, result = f.rep.terms_gcd() else: # pragma: no cover raise OperationNotSupported(f, 'terms_gcd') return J, f.per(result) def add_ground(f, coeff): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).add_ground(2) Poly(x + 3, x, domain='ZZ') """ if hasattr(f.rep, 'add_ground'): result = f.rep.add_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'add_ground') return f.per(result) def sub_ground(f, coeff): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).sub_ground(2) Poly(x - 1, x, domain='ZZ') """ if hasattr(f.rep, 'sub_ground'): result = f.rep.sub_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'sub_ground') return f.per(result) def mul_ground(f, coeff): """ Multiply ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).mul_ground(2) Poly(2*x + 2, x, domain='ZZ') """ if hasattr(f.rep, 'mul_ground'): result = f.rep.mul_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'mul_ground') return f.per(result) def quo_ground(f, coeff): """ Quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).quo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).quo_ground(2) Poly(x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'quo_ground'): result = f.rep.quo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'quo_ground') return f.per(result) def exquo_ground(f, coeff): """ Exact quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).exquo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).exquo_ground(2) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 3 in ZZ """ if hasattr(f.rep, 'exquo_ground'): result = f.rep.exquo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'exquo_ground') return f.per(result) def abs(f): """ Make all coefficients in ``f`` positive. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).abs() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'abs'): result = f.rep.abs() else: # pragma: no cover raise OperationNotSupported(f, 'abs') return f.per(result) def neg(f): """ Negate all coefficients in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).neg() Poly(-x**2 + 1, x, domain='ZZ') >>> -Poly(x**2 - 1, x) Poly(-x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'neg'): result = f.rep.neg() else: # pragma: no cover raise OperationNotSupported(f, 'neg') return f.per(result) def add(f, g): """ Add two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).add(Poly(x - 2, x)) Poly(x**2 + x - 1, x, domain='ZZ') >>> Poly(x**2 + 1, x) + Poly(x - 2, x) Poly(x**2 + x - 1, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.add_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'add'): result = F.add(G) else: # pragma: no cover raise OperationNotSupported(f, 'add') return per(result) def sub(f, g): """ Subtract two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x)) Poly(x**2 - x + 3, x, domain='ZZ') >>> Poly(x**2 + 1, x) - Poly(x - 2, x) Poly(x**2 - x + 3, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.sub_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'sub'): result = F.sub(G) else: # pragma: no cover raise OperationNotSupported(f, 'sub') return per(result) def mul(f, g): """ Multiply two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x)) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') >>> Poly(x**2 + 1, x)*Poly(x - 2, x) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.mul_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'mul'): result = F.mul(G) else: # pragma: no cover raise OperationNotSupported(f, 'mul') return per(result) def sqr(f): """ Square a polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).sqr() Poly(x**2 - 4*x + 4, x, domain='ZZ') >>> Poly(x - 2, x)**2 Poly(x**2 - 4*x + 4, x, domain='ZZ') """ if hasattr(f.rep, 'sqr'): result = f.rep.sqr() else: # pragma: no cover raise OperationNotSupported(f, 'sqr') return f.per(result) def pow(f, n): """ Raise ``f`` to a non-negative power ``n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).pow(3) Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') >>> Poly(x - 2, x)**3 Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') """ n = int(n) if hasattr(f.rep, 'pow'): result = f.rep.pow(n) else: # pragma: no cover raise OperationNotSupported(f, 'pow') return f.per(result) def pdiv(f, g): """ Polynomial pseudo-division of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x)) (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pdiv'): q, r = F.pdiv(G) else: # pragma: no cover raise OperationNotSupported(f, 'pdiv') return per(q), per(r) def prem(f, g): """ Polynomial pseudo-remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x)) Poly(20, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'prem'): result = F.prem(G) else: # pragma: no cover raise OperationNotSupported(f, 'prem') return per(result) def pquo(f, g): """ Polynomial pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x)) Poly(2*x + 4, x, domain='ZZ') >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pquo'): result = F.pquo(G) else: # pragma: no cover raise OperationNotSupported(f, 'pquo') return per(result) def pexquo(f, g): """ Polynomial exact pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pexquo'): try: result = F.pexquo(G) except ExactQuotientFailed, exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'pexquo') return per(result) def div(f, g, auto=True): """ Polynomial division with remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x)) (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ')) >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False) (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'div'): q, r = F.div(G) else: # pragma: no cover raise OperationNotSupported(f, 'div') if retract: try: Q, R = q.to_ring(), r.to_ring() except CoercionFailed: pass else: q, r = Q, R return per(q), per(r) def rem(f, g, auto=True): """ Computes the polynomial remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly, ZZ, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x)) Poly(5, x, domain='ZZ') >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False) Poly(x**2 + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'rem'): r = F.rem(G) else: # pragma: no cover raise OperationNotSupported(f, 'rem') if retract: try: r = r.to_ring() except CoercionFailed: pass return per(r) def quo(f, g, auto=True): """ Computes polynomial quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x)) Poly(1/2*x + 1, x, domain='QQ') >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'quo'): q = F.quo(G) else: # pragma: no cover raise OperationNotSupported(f, 'quo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def exquo(f, g, auto=True): """ Computes polynomial exact quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'exquo'): try: q = F.exquo(G) except ExactQuotientFailed, exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'exquo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def _gen_to_level(f, gen): """Returns level associated with the given generator. """ if isinstance(gen, int): length = len(f.gens) if -length <= gen < length: if gen < 0: return length + gen else: return gen else: raise PolynomialError("-%s <= gen < %s expected, got %s" % (length, length, gen)) else: try: return list(f.gens).index(sympify(gen)) except ValueError: raise PolynomialError("a valid generator expected, got %s" % gen) def degree(f, gen=0): """ Returns degree of ``f`` in ``x_j``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree() 2 >>> Poly(x**2 + y*x + y, x, y).degree(y) 1 """ j = f._gen_to_level(gen) if hasattr(f.rep, 'degree'): return f.rep.degree(j) else: # pragma: no cover raise OperationNotSupported(f, 'degree') def degree_list(f): """ Returns a list of degrees of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree_list() (2, 1) """ if hasattr(f.rep, 'degree_list'): return f.rep.degree_list() else: # pragma: no cover raise OperationNotSupported(f, 'degree_list') def total_degree(f): """ Returns the total degree of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).total_degree() 2 >>> Poly(x + y**5, x, y).total_degree() 5 """ if hasattr(f.rep, 'total_degree'): return f.rep.total_degree() else: # pragma: no cover raise OperationNotSupported(f, 'total_degree') def homogeneous_order(f): """ Returns the homogeneous order of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. This degree is the homogeneous order of ``f``. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4) >>> f.homogeneous_order() 5 """ if hasattr(f.rep, 'homogeneous_order'): return f.rep.homogeneous_order() else: # pragma: no cover raise OperationNotSupported(f, 'homogeneous_order') def LC(f, order=None): """ Returns the leading coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC() 4 """ if order is not None: return f.coeffs(order)[0] if hasattr(f.rep, 'LC'): result = f.rep.LC() else: # pragma: no cover raise OperationNotSupported(f, 'LC') return f.rep.dom.to_sympy(result) def TC(f): """ Returns the trailing coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).TC() 0 """ if hasattr(f.rep, 'TC'): result = f.rep.TC() else: # pragma: no cover raise OperationNotSupported(f, 'TC') return f.rep.dom.to_sympy(result) def EC(f, order=None): """ Returns the last non-zero coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).EC() 3 """ if hasattr(f.rep, 'coeffs'): return f.coeffs(order)[-1] else: # pragma: no cover raise OperationNotSupported(f, 'EC') def nth(f, *N): """ Returns the ``n``-th coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2) 2 >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2) 2 """ if hasattr(f.rep, 'nth'): result = f.rep.nth(*map(int, N)) else: # pragma: no cover raise OperationNotSupported(f, 'nth') return f.rep.dom.to_sympy(result) def LM(f, order=None): """ Returns the leading monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM() x**2*y**0 """ return Monomial(f.monoms(order)[0], f.gens) def EM(f, order=None): """ Returns the last non-zero monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM() x**0*y**1 """ return Monomial(f.monoms(order)[-1], f.gens) def LT(f, order=None): """ Returns the leading term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT() (x**2*y**0, 4) """ monom, coeff = f.terms(order)[0] return Monomial(monom, f.gens), coeff def ET(f, order=None): """ Returns the last non-zero term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET() (x**0*y**1, 3) """ monom, coeff = f.terms(order)[-1] return Monomial(monom, f.gens), coeff def max_norm(f): """ Returns maximum norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).max_norm() 3 """ if hasattr(f.rep, 'max_norm'): result = f.rep.max_norm() else: # pragma: no cover raise OperationNotSupported(f, 'max_norm') return f.rep.dom.to_sympy(result) def l1_norm(f): """ Returns l1 norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).l1_norm() 6 """ if hasattr(f.rep, 'l1_norm'): result = f.rep.l1_norm() else: # pragma: no cover raise OperationNotSupported(f, 'l1_norm') return f.rep.dom.to_sympy(result) def clear_denoms(f, convert=False): """ Clear denominators, but keep the ground domain. Examples ======== >>> from sympy import Poly, S, QQ >>> from sympy.abc import x >>> f = Poly(x/2 + S(1)/3, x, domain=QQ) >>> f.clear_denoms() (6, Poly(3*x + 2, x, domain='QQ')) >>> f.clear_denoms(convert=True) (6, Poly(3*x + 2, x, domain='ZZ')) """ if not f.rep.dom.has_Field: return S.One, f dom = f.rep.dom.get_ring() if hasattr(f.rep, 'clear_denoms'): coeff, result = f.rep.clear_denoms() else: # pragma: no cover raise OperationNotSupported(f, 'clear_denoms') coeff, f = dom.to_sympy(coeff), f.per(result) if not convert: return coeff, f else: return coeff, f.to_ring() def rat_clear_denoms(f, g): """ Clear denominators in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2/y + 1, x) >>> g = Poly(x**3 + y, x) >>> p, q = f.rat_clear_denoms(g) >>> p Poly(x**2 + y, x, domain='ZZ[y]') >>> q Poly(y*x**3 + y**2, x, domain='ZZ[y]') """ dom, per, f, g = f._unify(g) f = per(f) g = per(g) if not (dom.has_Field and dom.has_assoc_Ring): return f, g a, f = f.clear_denoms(convert=True) b, g = g.clear_denoms(convert=True) f = f.mul_ground(b) g = g.mul_ground(a) return f, g def integrate(f, *specs, **args): """ Computes indefinite integral of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).integrate() Poly(1/3*x**3 + x**2 + x, x, domain='QQ') >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0)) Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ') """ if args.get('auto', True) and f.rep.dom.has_Ring: f = f.to_field() if hasattr(f.rep, 'integrate'): if not specs: return f.per(f.rep.integrate(m=1)) rep = f.rep for spec in specs: if type(spec) is tuple: gen, m = spec else: gen, m = spec, 1 rep = rep.integrate(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'integrate') def diff(f, *specs): """ Computes partial derivative of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).diff() Poly(2*x + 2, x, domain='ZZ') >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1)) Poly(2*x*y, x, y, domain='ZZ') """ if hasattr(f.rep, 'diff'): if not specs: return f.per(f.rep.diff(m=1)) rep = f.rep for spec in specs: if type(spec) is tuple: gen, m = spec else: gen, m = spec, 1 rep = rep.diff(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'diff') def eval(f, x, a=None, auto=True): """ Evaluate ``f`` at ``a`` in the given variable. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 2*x + 3, x).eval(2) 11 >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2) Poly(5*y + 8, y, domain='ZZ') >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f.eval({x: 2}) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f.eval({x: 2, y: 5}) Poly(2*z + 31, z, domain='ZZ') >>> f.eval({x: 2, y: 5, z: 7}) 45 >>> f.eval((2, 5)) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') """ if a is None: if isinstance(x, dict): mapping = x for gen, value in mapping.iteritems(): f = f.eval(gen, value) return f elif isinstance(x, (tuple, list)): values = x if len(values) > len(f.gens): raise ValueError("too many values provided") for gen, value in zip(f.gens, values): f = f.eval(gen, value) return f else: j, a = 0, x else: j = f._gen_to_level(x) if not hasattr(f.rep, 'eval'): # pragma: no cover raise OperationNotSupported(f, 'eval') try: result = f.rep.eval(a, j) except CoercionFailed: if not auto: raise DomainError("can't evaluate at %s in %s" % (a, f.rep.dom)) else: domain, [a] = construct_domain([a]) f = f.set_domain(domain) result = f.rep.eval(a, j) return f.per(result, remove=j) def __call__(f, *values): """ Evaluate ``f`` at the give values. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f(2) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5, 7) 45 """ return f.eval(values) def half_gcdex(f, g, auto=True): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).half_gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.has_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'half_gcdex'): s, h = F.half_gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'half_gcdex') return per(s), per(h) def gcdex(f, g, auto=True): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.has_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'gcdex'): s, t, h = F.gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcdex') return per(s), per(t), per(h) def invert(f, g, auto=True): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x)) Poly(-4/3, x, domain='QQ') >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x)) Traceback (most recent call last): ... NotInvertible: zero divisor """ dom, per, F, G = f._unify(g) if auto and dom.has_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'invert'): result = F.invert(G) else: # pragma: no cover raise OperationNotSupported(f, 'invert') return per(result) def revert(f, n): """Compute ``f**(-1)`` mod ``x**n``. """ if hasattr(f.rep, 'revert'): result = f.rep.revert(int(n)) else: # pragma: no cover raise OperationNotSupported(f, 'revert') return f.per(result) def subresultants(f, g): """ Computes the subresultant PRS sequence of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x)) [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')] """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'subresultants'): result = F.subresultants(G) else: # pragma: no cover raise OperationNotSupported(f, 'subresultants') return map(per, result) def resultant(f, g): """ Computes the resultant of ``f`` and ``g`` via PRS. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).resultant(Poly(x**2 - 1, x)) 4 """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'resultant'): result = F.resultant(G) else: # pragma: no cover raise OperationNotSupported(f, 'resultant') return per(result, remove=0) def discriminant(f): """ Computes the discriminant of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x + 3, x).discriminant() -8 """ if hasattr(f.rep, 'discriminant'): result = f.rep.discriminant() else: # pragma: no cover raise OperationNotSupported(f, 'discriminant') return f.per(result, remove=0) def cofactors(f, g): """ Returns the GCD of ``f`` and ``g`` and their cofactors. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x)) (Poly(x - 1, x, domain='ZZ'), Poly(x + 1, x, domain='ZZ'), Poly(x - 2, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'cofactors'): h, cff, cfg = F.cofactors(G) else: # pragma: no cover raise OperationNotSupported(f, 'cofactors') return per(h), per(cff), per(cfg) def gcd(f, g): """ Returns the polynomial GCD of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x)) Poly(x - 1, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'gcd'): result = F.gcd(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcd') return per(result) def lcm(f, g): """ Returns polynomial LCM of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x)) Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'lcm'): result = F.lcm(G) else: # pragma: no cover raise OperationNotSupported(f, 'lcm') return per(result) def trunc(f, p): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3) Poly(-x**3 - x + 1, x, domain='ZZ') """ p = f.rep.dom.convert(p) if hasattr(f.rep, 'trunc'): result = f.rep.trunc(p) else: # pragma: no cover raise OperationNotSupported(f, 'trunc') return f.per(result) def monic(f, auto=True): """ Divides all coefficients by ``LC(f)``. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic() Poly(x**2 + 2*x + 3, x, domain='QQ') >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic() Poly(x**2 + 4/3*x + 2/3, x, domain='QQ') """ if auto and f.rep.dom.has_Ring: f = f.to_field() if hasattr(f.rep, 'monic'): result = f.rep.monic() else: # pragma: no cover raise OperationNotSupported(f, 'monic') return f.per(result) def content(f): """ Returns the GCD of polynomial coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(6*x**2 + 8*x + 12, x).content() 2 """ if hasattr(f.rep, 'content'): result = f.rep.content() else: # pragma: no cover raise OperationNotSupported(f, 'content') return f.rep.dom.to_sympy(result) def primitive(f): """ Returns the content and a primitive form of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 8*x + 12, x).primitive() (2, Poly(x**2 + 4*x + 6, x, domain='ZZ')) """ if hasattr(f.rep, 'primitive'): cont, result = f.rep.primitive() else: # pragma: no cover raise OperationNotSupported(f, 'primitive') return f.rep.dom.to_sympy(cont), f.per(result) def compose(f, g): """ Computes the functional composition of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x, x).compose(Poly(x - 1, x)) Poly(x**2 - x, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'compose'): result = F.compose(G) else: # pragma: no cover raise OperationNotSupported(f, 'compose') return per(result) def decompose(f): """ Computes a functional decomposition of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose() [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')] """ if hasattr(f.rep, 'decompose'): result = f.rep.decompose() else: # pragma: no cover raise OperationNotSupported(f, 'decompose') return map(f.per, result) def shift(f, a): """ Efficiently compute Taylor shift ``f(x + a)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).shift(2) Poly(x**2 + 2*x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'shift'): result = f.rep.shift(a) else: # pragma: no cover raise OperationNotSupported(f, 'shift') return f.per(result) def sturm(f, auto=True): """ Computes the Sturm sequence of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm() [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'), Poly(3*x**2 - 4*x + 1, x, domain='QQ'), Poly(2/9*x + 25/9, x, domain='QQ'), Poly(-2079/4, x, domain='QQ')] """ if auto and f.rep.dom.has_Ring: f = f.to_field() if hasattr(f.rep, 'sturm'): result = f.rep.sturm() else: # pragma: no cover raise OperationNotSupported(f, 'sturm') return map(f.per, result) def gff_list(f): """ Computes greatest factorial factorization of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> Poly(f).gff_list() [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'gff_list'): result = f.rep.gff_list() else: # pragma: no cover raise OperationNotSupported(f, 'gff_list') return [ (f.per(g), k) for g, k in result ] def sqf_norm(f): """ Computes square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm() >>> s 1 >>> f Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>') >>> r Poly(x**4 - 4*x**2 + 16, x, domain='QQ') """ if hasattr(f.rep, 'sqf_norm'): s, g, r = f.rep.sqf_norm() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_norm') return s, f.per(g), f.per(r) def sqf_part(f): """ Computes square-free part of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 3*x - 2, x).sqf_part() Poly(x**2 - x - 2, x, domain='ZZ') """ if hasattr(f.rep, 'sqf_part'): result = f.rep.sqf_part() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_part') return f.per(result) def sqf_list(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 >>> Poly(f).sqf_list() (2, [(Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) >>> Poly(f).sqf_list(all=True) (2, [(Poly(1, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) """ if hasattr(f.rep, 'sqf_list'): coeff, factors = f.rep.sqf_list(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list') return f.rep.dom.to_sympy(coeff), [ (f.per(g), k) for g, k in factors ] def sqf_list_include(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly, expand >>> from sympy.abc import x >>> f = expand(2*(x + 1)**3*x**4) >>> f 2*x**7 + 6*x**6 + 6*x**5 + 2*x**4 >>> Poly(f).sqf_list_include() [(Poly(2, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] >>> Poly(f).sqf_list_include(all=True) [(Poly(2, x, domain='ZZ'), 1), (Poly(1, x, domain='ZZ'), 2), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'sqf_list_include'): factors = f.rep.sqf_list_include(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list_include') return [ (f.per(g), k) for g, k in factors ] def factor_list(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list() (2, [(Poly(x + y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]) """ if hasattr(f.rep, 'factor_list'): try: coeff, factors = f.rep.factor_list() except DomainError: return S.One, [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list') return f.rep.dom.to_sympy(coeff), [ (f.per(g), k) for g, k in factors ] def factor_list_include(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list_include() [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)] """ if hasattr(f.rep, 'factor_list_include'): try: factors = f.rep.factor_list_include() except DomainError: return [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list_include') return [ (f.per(g), k) for g, k in factors ] def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).intervals() [((-2, -1), 1), ((1, 2), 1)] >>> Poly(x**2 - 3, x).intervals(eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = QQ.convert(inf) if sup is not None: sup = QQ.convert(sup) if hasattr(f.rep, 'intervals'): result = f.rep.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: # pragma: no cover raise OperationNotSupported(f, 'intervals') if sqf: def _real(interval): s, t = interval return (QQ.to_sympy(s), QQ.to_sympy(t)) if not all: return map(_real, result) def _complex(rectangle): (u, v), (s, t) = rectangle return (QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)) real_part, complex_part = result return map(_real, real_part), map(_complex, complex_part) else: def _real(interval): (s, t), k = interval return ((QQ.to_sympy(s), QQ.to_sympy(t)), k) if not all: return map(_real, result) def _complex(rectangle): ((u, v), (s, t)), k = rectangle return ((QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)), k) real_part, complex_part = result return map(_real, real_part), map(_complex, complex_part) def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2) (19/11, 26/15) """ if check_sqf and not f.is_sqf: raise PolynomialError("only square-free polynomials supported") s, t = QQ.convert(s), QQ.convert(t) if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if steps is not None: steps = int(steps) elif eps is None: steps = 1 if hasattr(f.rep, 'refine_root'): S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast) else: # pragma: no cover raise OperationNotSupported(f, 'refine_root') return QQ.to_sympy(S), QQ.to_sympy(T) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**4 - 4, x).count_roots(-3, 3) 2 >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I) 1 """ inf_real, sup_real = True, True if inf is not None: inf = sympify(inf) if inf is S.NegativeInfinity: inf = None else: re, im = inf.as_real_imag() if not im: inf = QQ.convert(inf) else: inf, inf_real = map(QQ.convert, (re, im)), False if sup is not None: sup = sympify(sup) if sup is S.Infinity: sup = None else: re, im = sup.as_real_imag() if not im: sup = QQ.convert(sup) else: sup, sup_real = map(QQ.convert, (re, im)), False if inf_real and sup_real: if hasattr(f.rep, 'count_real_roots'): count = f.rep.count_real_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_real_roots') else: if inf_real and inf is not None: inf = (inf, QQ.zero) if sup_real and sup is not None: sup = (sup, QQ.zero) if hasattr(f.rep, 'count_complex_roots'): count = f.rep.count_complex_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_complex_roots') return Integer(count) def root(f, index, radicals=True): """ Get an indexed root of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4) >>> f.root(0) -1/2 >>> f.root(1) 2 >>> f.root(2) 2 >>> f.root(3) Traceback (most recent call last): ... IndexError: root index out of [-3, 2] range, got 3 >>> Poly(x**5 + x + 1).root(0) RootOf(x**3 - x**2 + 1, 0) """ return sympy.polys.rootoftools.RootOf(f, index, radicals=radicals) def real_roots(f, multiple=True, radicals=True): """ Return a list of real roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).real_roots() [RootOf(x**3 + x + 1, 0)] """ reals = sympy.polys.rootoftools.RootOf.real_roots(f, radicals=radicals) if multiple: return reals else: return group(reals, multiple=False) def all_roots(f, multiple=True, radicals=True): """ Return a list of real and complex roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).all_roots() [RootOf(x**3 + x + 1, 0), RootOf(x**3 + x + 1, 1), RootOf(x**3 + x + 1, 2)] """ roots = sympy.polys.rootoftools.RootOf.all_roots(f, radicals=radicals) if multiple: return roots else: return group(roots, multiple=False) def nroots(f, n=15, maxsteps=50, cleanup=True, error=False): """ Compute numerical approximations of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3).nroots(n=15) [-1.73205080756888, 1.73205080756888] >>> Poly(x**2 - 3).nroots(n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ if f.is_multivariate: raise MultivariatePolynomialError("can't compute numerical roots of %s" % f) if f.degree() <= 0: return [] coeffs = [ coeff.evalf(n=n).as_real_imag() for coeff in f.all_coeffs() ] dps = sympy.mpmath.mp.dps sympy.mpmath.mp.dps = n try: try: coeffs = [ sympy.mpmath.mpc(*coeff) for coeff in coeffs ] except TypeError: raise DomainError("numerical domain expected, got %s" % f.rep.dom) result = sympy.mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=error) if error: roots, error = result else: roots, error = result, None roots = map(sympify, sorted(roots, key=lambda r: (r.real, r.imag))) finally: sympy.mpmath.mp.dps = dps if error is not None: return roots, sympify(error) else: return roots def ground_roots(f): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots() {0: 2, 1: 2} """ if f.is_multivariate: raise MultivariatePolynomialError("can't compute ground roots of %s" % f) roots = {} for factor, k in f.factor_list()[1]: if factor.is_linear: a, b = factor.all_coeffs() roots[-b/a] = k return roots def nth_power_roots_poly(f, n): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**4 - x**2 + 1) >>> f.nth_power_roots_poly(2) Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(3) Poly(x**4 + 2*x**2 + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(4) Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(12) Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ') """ if f.is_multivariate: raise MultivariatePolynomialError("must be a univariate polynomial") N = sympify(n) if N.is_Integer and N >= 1: n = int(N) else: raise ValueError("'n' must an integer and n >= 1, got %s" % n) x = f.gen t = Dummy('t') r = f.resultant(f.__class__.from_expr(x**n - t, x, t)) return r.replace(t, x) def cancel(f, g, include=False): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x)) (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True) (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) if hasattr(F, 'cancel'): result = F.cancel(G, include=include) else: # pragma: no cover raise OperationNotSupported(f, 'cancel') if not include: if dom.has_assoc_Ring: dom = dom.get_ring() cp, cq, p, q = result cp = dom.to_sympy(cp) cq = dom.to_sympy(cq) return cp/cq, per(p), per(q) else: return tuple(map(per, result)) @property def is_zero(f): """ Returns ``True`` if ``f`` is a zero polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_zero True >>> Poly(1, x).is_zero False """ return f.rep.is_zero @property def is_one(f): """ Returns ``True`` if ``f`` is a unit polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_one False >>> Poly(1, x).is_one True """ return f.rep.is_one @property def is_sqf(f): """ Returns ``True`` if ``f`` is a square-free polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).is_sqf False >>> Poly(x**2 - 1, x).is_sqf True """ return f.rep.is_sqf @property def is_monic(f): """ Returns ``True`` if the leading coefficient of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 2, x).is_monic True >>> Poly(2*x + 2, x).is_monic False """ return f.rep.is_monic @property def is_primitive(f): """ Returns ``True`` if GCD of the coefficients of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 6*x + 12, x).is_primitive False >>> Poly(x**2 + 3*x + 6, x).is_primitive True """ return f.rep.is_primitive @property def is_ground(f): """ Returns ``True`` if ``f`` is an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x, x).is_ground False >>> Poly(2, x).is_ground True >>> Poly(y, x).is_ground True """ return f.rep.is_ground @property def is_linear(f): """ Returns ``True`` if ``f`` is linear in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x + y + 2, x, y).is_linear True >>> Poly(x*y + 2, x, y).is_linear False """ return f.rep.is_linear @property def is_quadratic(f): """ Returns ``True`` if ``f`` is quadratic in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x*y + 2, x, y).is_quadratic True >>> Poly(x*y**2 + 2, x, y).is_quadratic False """ return f.rep.is_quadratic @property def is_monomial(f): """ Returns ``True`` if ``f`` is zero or has only one term. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(3*x**2, x).is_monomial True >>> Poly(3*x**2 + 1, x).is_monomial False """ return f.rep.is_monomial @property def is_homogeneous(f): """ Returns ``True`` if ``f`` is a homogeneous polynomial. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y, x, y).is_homogeneous True >>> Poly(x**3 + x*y, x, y).is_homogeneous False """ return f.rep.is_homogeneous @property def is_irreducible(f): """ Returns ``True`` if ``f`` has no factors over its domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible True >>> Poly(x**2 + 1, x, modulus=2).is_irreducible False """ return f.rep.is_irreducible @property def is_univariate(f): """ Returns ``True`` if ``f`` is a univariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_univariate True >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate False >>> Poly(x*y**2 + x*y + 1, x).is_univariate True >>> Poly(x**2 + x + 1, x, y).is_univariate False """ return len(f.gens) == 1 @property def is_multivariate(f): """ Returns ``True`` if ``f`` is a multivariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_multivariate False >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate True >>> Poly(x*y**2 + x*y + 1, x).is_multivariate False >>> Poly(x**2 + x + 1, x, y).is_multivariate True """ return len(f.gens) != 1 @property def is_cyclotomic(f): """ Returns ``True`` if ``f`` is a cyclotomic polnomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 >>> Poly(f).is_cyclotomic False >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 >>> Poly(g).is_cyclotomic True """ return f.rep.is_cyclotomic def __abs__(f): return f.abs() def __neg__(f): return f.neg() @_sympifyit('g', NotImplemented) def __add__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return f.as_expr() + g return f.add(g) @_sympifyit('g', NotImplemented) def __radd__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return g + f.as_expr() return g.add(f) @_sympifyit('g', NotImplemented) def __sub__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return f.as_expr() - g return f.sub(g) @_sympifyit('g', NotImplemented) def __rsub__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return g - f.as_expr() return g.sub(f) @_sympifyit('g', NotImplemented) def __mul__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return f.as_expr()*g return f.mul(g) @_sympifyit('g', NotImplemented) def __rmul__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return g*f.as_expr() return g.mul(f) @_sympifyit('n', NotImplemented) def __pow__(f, n): if n.is_Integer and n >= 0: return f.pow(n) else: return f.as_expr()**n @_sympifyit('g', NotImplemented) def __divmod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return f.div(g) @_sympifyit('g', NotImplemented) def __rdivmod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return g.div(f) @_sympifyit('g', NotImplemented) def __mod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return f.rem(g) @_sympifyit('g', NotImplemented) def __rmod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return g.rem(f) @_sympifyit('g', NotImplemented) def __floordiv__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return f.quo(g) @_sympifyit('g', NotImplemented) def __rfloordiv__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return g.quo(f) @_sympifyit('g', NotImplemented) def __div__(f, g): return f.as_expr()/g.as_expr() @_sympifyit('g', NotImplemented) def __rdiv__(f, g): return g.as_expr()/f.as_expr() __truediv__ = __div__ __rtruediv__ = __rdiv__ @_sympifyit('g', NotImplemented) def __eq__(f, g): if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if f.gens != g.gens: return False if f.rep.dom != g.rep.dom: try: dom = f.rep.dom.unify(g.rep.dom, f.gens) except UnificationFailed: return False f = f.set_domain(dom) g = g.set_domain(dom) return f.rep == g.rep @_sympifyit('g', NotImplemented) def __ne__(f, g): return not f.__eq__(g) def __nonzero__(f): return not f.is_zero def eq(f, g, strict=False): if not strict: return f.__eq__(g) else: return f._strict_eq(sympify(g)) def ne(f, g, strict=False): return not f.eq(g, strict=strict) def _strict_eq(f, g): return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True) class PurePoly(Poly): """Class for representing pure polynomials. """ def _hashable_content(self): """Allow SymPy to hash Poly instances. """ return (self.rep,) def __hash__(self): return super(PurePoly, self).__hash__() @property def free_symbols(self): """ Free symbols of a polynomial. Examples ======== >>> from sympy import PurePoly >>> from sympy.abc import x, y >>> PurePoly(x**2 + 1).free_symbols set() >>> PurePoly(x**2 + y).free_symbols set() >>> PurePoly(x**2 + y, x).free_symbols set([y]) """ return self.free_symbols_in_domain @_sympifyit('g', NotImplemented) def __eq__(f, g): if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if len(f.gens) != len(g.gens): return False if f.rep.dom != g.rep.dom: try: dom = f.rep.dom.unify(g.rep.dom, f.gens) except UnificationFailed: return False f = f.set_domain(dom) g = g.set_domain(dom) return f.rep == g.rep def _strict_eq(f, g): return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("can't unify %s with %s" % (f, g)) if len(f.gens) != len(g.gens): raise UnificationFailed("can't unify %s with %s" % (f, g)) if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)): raise UnificationFailed("can't unify %s with %s" % (f, g)) cls = f.__class__ gens = f.gens dom = f.rep.dom.unify(g.rep.dom, gens) F = f.rep.convert(dom) G = g.rep.convert(dom) def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove]+gens[remove+1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G def poly_from_expr(expr, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return _poly_from_expr(expr, opt) def _poly_from_expr(expr, opt): """Construct a polynomial from an expression. """ orig, expr = expr, sympify(expr) if not isinstance(expr, Basic): raise PolificationFailed(opt, orig, expr) elif expr.is_Poly: poly = expr.__class__._from_poly(expr, opt) opt['gens'] = poly.gens opt['domain'] = poly.domain if opt.polys is None: opt['polys'] = True return poly, opt elif opt.expand: expr = expr.expand() try: rep, opt = _dict_from_expr(expr, opt) except GeneratorsNeeded: raise PolificationFailed(opt, orig, expr) monoms, coeffs = zip(*rep.items()) domain = opt.domain if domain is None: domain, coeffs = construct_domain(coeffs, opt=opt) else: coeffs = map(domain.from_sympy, coeffs) level = len(opt.gens)-1 poly = Poly.new(DMP.from_monoms_coeffs(monoms, coeffs, level, domain), *opt.gens) opt['domain'] = domain if opt.polys is None: opt['polys'] = False return poly, opt def parallel_poly_from_expr(exprs, *gens, **args): """Construct polynomials from expressions. """ opt = options.build_options(gens, args) return _parallel_poly_from_expr(exprs, opt) def _parallel_poly_from_expr(exprs, opt): """Construct polynomials from expressions. """ if len(exprs) == 2: f, g = exprs if isinstance(f, Poly) and isinstance(g, Poly): f = f.__class__._from_poly(f, opt) g = g.__class__._from_poly(g, opt) f, g = f.unify(g) opt['gens'] = f.gens opt['domain'] = f.domain if opt.polys is None: opt['polys'] = True return [f, g], opt origs, exprs = list(exprs), [] _exprs, _polys = [], [] failed = False for i, expr in enumerate(origs): expr = sympify(expr) if isinstance(expr, Basic): if expr.is_Poly: _polys.append(i) else: _exprs.append(i) if opt.expand: expr = expr.expand() else: failed = True exprs.append(expr) if failed: raise PolificationFailed(opt, origs, exprs, True) if _polys: # XXX: this is a temporary solution for i in _polys: exprs[i] = exprs[i].as_expr() try: reps, opt = _parallel_dict_from_expr(exprs, opt) except GeneratorsNeeded: raise PolificationFailed(opt, origs, exprs, True) coeffs_list, lengths = [], [] all_monoms = [] all_coeffs = [] for rep in reps: monoms, coeffs = zip(*rep.items()) coeffs_list.extend(coeffs) all_monoms.append(monoms) lengths.append(len(coeffs)) domain = opt.domain if domain is None: domain, coeffs_list = construct_domain(coeffs_list, opt=opt) else: coeffs_list = map(domain.from_sympy, coeffs_list) for k in lengths: all_coeffs.append(coeffs_list[:k]) coeffs_list = coeffs_list[k:] polys, level = [], len(opt.gens)-1 for monoms, coeffs in zip(all_monoms, all_coeffs): rep = DMP.from_monoms_coeffs(monoms, coeffs, level, domain) polys.append(Poly.new(rep, *opt.gens)) opt['domain'] = domain if opt.polys is None: opt['polys'] = bool(_polys) return polys, opt def _update_args(args, key, value): """Add a new ``(key, value)`` pair to arguments ``dict``. """ args = dict(args) if key not in args: args[key] = value return args def degree(f, *gens, **args): """ Return the degree of ``f`` in the given variable. Examples ======== >>> from sympy import degree >>> from sympy.abc import x, y >>> degree(x**2 + y*x + 1, gen=x) 2 >>> degree(x**2 + y*x + 1, gen=y) 1 """ options.allowed_flags(args, ['gen', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('degree', 1, exc) return Integer(F.degree(opt.gen)) def degree_list(f, *gens, **args): """ Return a list of degrees of ``f`` in all variables. Examples ======== >>> from sympy import degree_list >>> from sympy.abc import x, y >>> degree_list(x**2 + y*x + 1) (2, 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('degree_list', 1, exc) degrees = F.degree_list() return tuple(map(Integer, degrees)) def LC(f, *gens, **args): """ Return the leading coefficient of ``f``. Examples ======== >>> from sympy import LC >>> from sympy.abc import x, y >>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y) 4 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('LC', 1, exc) return F.LC(order=opt.order) def LM(f, *gens, **args): """ Return the leading monomial of ``f``. Examples ======== >>> from sympy import LM >>> from sympy.abc import x, y >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('LM', 1, exc) monom = F.LM(order=opt.order) return monom.as_expr() def LT(f, *gens, **args): """ Return the leading term of ``f``. Examples ======== >>> from sympy import LT >>> from sympy.abc import x, y >>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y) 4*x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('LT', 1, exc) monom, coeff = F.LT(order=opt.order) return coeff*monom.as_expr() def pdiv(f, g, *gens, **args): """ Compute polynomial pseudo-division of ``f`` and ``g``. Examples ======== >>> from sympy import pdiv >>> from sympy.abc import x >>> pdiv(x**2 + 1, 2*x - 4) (2*x + 4, 20) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('pdiv', 2, exc) q, r = F.pdiv(G) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r def prem(f, g, *gens, **args): """ Compute polynomial pseudo-remainder of ``f`` and ``g``. Examples ======== >>> from sympy import prem >>> from sympy.abc import x >>> prem(x**2 + 1, 2*x - 4) 20 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('prem', 2, exc) r = F.prem(G) if not opt.polys: return r.as_expr() else: return r def pquo(f, g, *gens, **args): """ Compute polynomial pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pquo >>> from sympy.abc import x >>> pquo(x**2 + 1, 2*x - 4) 2*x + 4 >>> pquo(x**2 - 1, 2*x - 1) 2*x + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('pquo', 2, exc) q = F.pquo(G) if not opt.polys: return q.as_expr() else: return q def pexquo(f, g, *gens, **args): """ Compute polynomial exact pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pexquo >>> from sympy.abc import x >>> pexquo(x**2 - 1, 2*x - 2) 2*x + 2 >>> pexquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('pexquo', 2, exc) q = F.pexquo(G) if not opt.polys: return q.as_expr() else: return q def div(f, g, *gens, **args): """ Compute polynomial division of ``f`` and ``g``. Examples ======== >>> from sympy import div, ZZ, QQ >>> from sympy.abc import x >>> div(x**2 + 1, 2*x - 4, domain=ZZ) (0, x**2 + 1) >>> div(x**2 + 1, 2*x - 4, domain=QQ) (x/2 + 1, 5) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('div', 2, exc) q, r = F.div(G, auto=opt.auto) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r def rem(f, g, *gens, **args): """ Compute polynomial remainder of ``f`` and ``g``. Examples ======== >>> from sympy import rem, ZZ, QQ >>> from sympy.abc import x >>> rem(x**2 + 1, 2*x - 4, domain=ZZ) x**2 + 1 >>> rem(x**2 + 1, 2*x - 4, domain=QQ) 5 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('rem', 2, exc) r = F.rem(G, auto=opt.auto) if not opt.polys: return r.as_expr() else: return r def quo(f, g, *gens, **args): """ Compute polynomial quotient of ``f`` and ``g``. Examples ======== >>> from sympy import quo >>> from sympy.abc import x >>> quo(x**2 + 1, 2*x - 4) x/2 + 1 >>> quo(x**2 - 1, x - 1) x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('quo', 2, exc) q = F.quo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q def exquo(f, g, *gens, **args): """ Compute polynomial exact quotient of ``f`` and ``g``. Examples ======== >>> from sympy import exquo >>> from sympy.abc import x >>> exquo(x**2 - 1, x - 1) x + 1 >>> exquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('exquo', 2, exc) q = F.exquo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q def half_gcdex(f, g, *gens, **args): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import half_gcdex >>> from sympy.abc import x >>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (-x/5 + 3/5, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: s, h = domain.half_gcdex(a, b) except NotImplementedError: raise ComputationFailed('half_gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(h) s, h = F.half_gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), h.as_expr() else: return s, h def gcdex(f, g, *gens, **args): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import gcdex >>> from sympy.abc import x >>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (-x/5 + 3/5, x**2/5 - 6*x/5 + 2, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: s, t, h = domain.gcdex(a, b) except NotImplementedError: raise ComputationFailed('gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(t),domain.to_sympy(h) s, t, h = F.gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), t.as_expr(), h.as_expr() else: return s, t, h def invert(f, g, *gens, **args): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import invert >>> from sympy.abc import x >>> invert(x**2 - 1, 2*x - 1) -4/3 >>> invert(x**2 - 1, x - 1) Traceback (most recent call last): ... NotInvertible: zero divisor """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.invert(a, b)) except NotImplementedError: raise ComputationFailed('invert', 2, exc) h = F.invert(G, auto=opt.auto) if not opt.polys: return h.as_expr() else: return h def subresultants(f, g, *gens, **args): """ Compute subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import subresultants >>> from sympy.abc import x >>> subresultants(x**2 + 1, x**2 - 1) [x**2 + 1, x**2 - 1, -2] """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('subresultants', 2, exc) result = F.subresultants(G) if not opt.polys: return [ r.as_expr() for r in result ] else: return result def resultant(f, g, *gens, **args): """ Compute resultant of ``f`` and ``g``. Examples ======== >>> from sympy import resultant >>> from sympy.abc import x >>> resultant(x**2 + 1, x**2 - 1) 4 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('resultant', 2, exc) result = F.resultant(G) if not opt.polys: return result.as_expr() else: return result def discriminant(f, *gens, **args): """ Compute discriminant of ``f``. Examples ======== >>> from sympy import discriminant >>> from sympy.abc import x >>> discriminant(x**2 + 2*x + 3) -8 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('discriminant', 1, exc) result = F.discriminant() if not opt.polys: return result.as_expr() else: return result def cofactors(f, g, *gens, **args): """ Compute GCD and cofactors of ``f`` and ``g``. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import cofactors >>> from sympy.abc import x >>> cofactors(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: h, cff, cfg = domain.cofactors(a, b) except NotImplementedError: raise ComputationFailed('cofactors', 2, exc) else: return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg) h, cff, cfg = F.cofactors(G) if not opt.polys: return h.as_expr(), cff.as_expr(), cfg.as_expr() else: return h, cff, cfg def gcd_list(seq, *gens, **args): """ Compute GCD of a list of polynomials. Examples ======== >>> from sympy import gcd_list >>> from sympy.abc import x >>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x - 1 """ seq = sympify(seq) if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.zero elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.gcd(result, number) if domain.is_one(result): break return domain.to_sympy(result) options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('gcd_list', len(seq), exc) if not polys: if not opt.polys: return S.Zero else: return Poly(0, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.gcd(poly) if result.is_one: break if not opt.polys: return result.as_expr() else: return result def gcd(f, g=None, *gens, **args): """ Compute GCD of ``f`` and ``g``. Examples ======== >>> from sympy import gcd >>> from sympy.abc import x >>> gcd(x**2 - 1, x**2 - 3*x + 2) x - 1 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return gcd_list(f, *gens, **args) elif g is None: raise TypeError("gcd() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.gcd(a, b)) except NotImplementedError: raise ComputationFailed('gcd', 2, exc) result = F.gcd(G) if not opt.polys: return result.as_expr() else: return result def lcm_list(seq, *gens, **args): """ Compute LCM of a list of polynomials. Examples ======== >>> from sympy import lcm_list >>> from sympy.abc import x >>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x**5 - x**4 - 2*x**3 - x**2 + x + 2 """ seq = sympify(seq) if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.one elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.lcm(result, number) return domain.to_sympy(result) options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('lcm_list', len(seq), exc) if not polys: if not opt.polys: return S.One else: return Poly(1, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.lcm(poly) if not opt.polys: return result.as_expr() else: return result def lcm(f, g=None, *gens, **args): """ Compute LCM of ``f`` and ``g``. Examples ======== >>> from sympy import lcm >>> from sympy.abc import x >>> lcm(x**2 - 1, x**2 - 3*x + 2) x**3 - 2*x**2 - x + 2 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return lcm_list(f, *gens, **args) elif g is None: raise TypeError("lcm() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.lcm(a, b)) except NotImplementedError: raise ComputationFailed('lcm', 2, exc) result = F.lcm(G) if not opt.polys: return result.as_expr() else: return result def terms_gcd(f, *gens, **args): """ Remove GCD of terms from ``f``. If the ``deep`` flag is True, then the arguments of ``f`` will have terms_gcd applied to them. If a fraction is factored out of ``f`` and ``f`` is an Add, then an unevaluated Mul will be returned so that automatic simplification does not redistribute it. The hint ``clear``, when set to False, can be used to prevent such factoring when all coefficients are not fractions. Examples ======== >>> from sympy import terms_gcd, cos, pi >>> from sympy.abc import x, y >>> terms_gcd(x**6*y**2 + x**3*y, x, y) x**3*y*(x**3*y + 1) The default action of polys routines is to expand the expression given to them. terms_gcd follows this behavior: >>> terms_gcd((3+3*x)*(x+x*y)) 3*x*(x*y + x + y + 1) If this is not desired then the hint ``expand`` can be set to False. In this case the expression will be treated as though it were comprised of one or more terms: >>> terms_gcd((3+3*x)*(x+x*y), expand=False) (3*x + 3)*(x*y + x) In order to traverse factors of a Mul or the arguments of other functions, the ``deep`` hint can be used: >>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True) 3*x*(x + 1)*(y + 1) >>> terms_gcd(cos(x + x*y), deep=True) cos(x*(y + 1)) Rationals are factored out by default: >>> terms_gcd(x + y/2) (2*x + y)/2 Only the y-term had a coefficient that was a fraction; if one does not want to factor out the 1/2 in cases like this, the flag ``clear`` can be set to False: >>> terms_gcd(x + y/2, clear=False) x + y/2 >>> terms_gcd(x*y/2 + y**2, clear=False) y*(x/2 + y) The ``clear`` flag is ignored if all coefficients are fractions: >>> terms_gcd(x/3 + y/2, clear=False) (2*x + 3*y)/6 See Also ======== sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms """ if not isinstance(f, Expr) or f.is_Atom: return sympify(f) if args.get('deep', False): new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args]) args.pop('deep') args['expand'] = False return terms_gcd(new, *gens, **args) clear = args.pop('clear', True) options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: return exc.expr J, f = F.terms_gcd() if opt.domain.has_Ring: if opt.domain.has_Field: denom, f = f.clear_denoms(convert=True) coeff, f = f.primitive() if opt.domain.has_Field: coeff /= denom else: coeff = S.One term = Mul(*[ x**j for x, j in zip(f.gens, J) ]) if clear: return _keep_coeff(coeff, term*f.as_expr()) # base the clearing on the form of the original expression, not # the (perhaps) Mul that we have now coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul() return _keep_coeff(coeff, term*f, clear=False) def trunc(f, p, *gens, **args): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import trunc >>> from sympy.abc import x >>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3) -x**3 - x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('trunc', 1, exc) result = F.trunc(sympify(p)) if not opt.polys: return result.as_expr() else: return result def monic(f, *gens, **args): """ Divide all coefficients of ``f`` by ``LC(f)``. Examples ======== >>> from sympy import monic >>> from sympy.abc import x >>> monic(3*x**2 + 4*x + 2) x**2 + 4*x/3 + 2/3 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('monic', 1, exc) result = F.monic(auto=opt.auto) if not opt.polys: return result.as_expr() else: return result def content(f, *gens, **args): """ Compute GCD of coefficients of ``f``. Examples ======== >>> from sympy import content >>> from sympy.abc import x >>> content(6*x**2 + 8*x + 12) 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('content', 1, exc) return F.content() def primitive(f, *gens, **args): """ Compute content and the primitive form of ``f``. Examples ======== >>> from sympy.polys.polytools import primitive >>> from sympy.abc import x, y >>> primitive(6*x**2 + 8*x + 12) (2, 3*x**2 + 4*x + 6) >>> eq = (2 + 2*x)*x + 2 Expansion is performed by default: >>> primitive(eq) (2, x**2 + x + 1) Set ``expand`` to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction. >>> primitive(eq, expand=False) (1, x*(2*x + 2) + 2) >>> eq.as_content_primitive() (2, x*(x + 1) + 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('primitive', 1, exc) cont, result = F.primitive() if not opt.polys: return cont, result.as_expr() else: return cont, result def compose(f, g, *gens, **args): """ Compute functional composition ``f(g)``. Examples ======== >>> from sympy import compose >>> from sympy.abc import x >>> compose(x**2 + x, x - 1) x**2 - x """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('compose', 2, exc) result = F.compose(G) if not opt.polys: return result.as_expr() else: return result def decompose(f, *gens, **args): """ Compute functional decomposition of ``f``. Examples ======== >>> from sympy import decompose >>> from sympy.abc import x >>> decompose(x**4 + 2*x**3 - x - 1) [x**2 - x - 1, x**2 + x] """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('decompose', 1, exc) result = F.decompose() if not opt.polys: return [ r.as_expr() for r in result ] else: return result def sturm(f, *gens, **args): """ Compute Sturm sequence of ``f``. Examples ======== >>> from sympy import sturm >>> from sympy.abc import x >>> sturm(x**3 - 2*x**2 + x - 3) [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4] """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('sturm', 1, exc) result = F.sturm(auto=opt.auto) if not opt.polys: return [ r.as_expr() for r in result ] else: return result def gff_list(f, *gens, **args): """ Compute a list of greatest factorial factors of ``f``. Examples ======== >>> from sympy import gff_list, ff >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> gff_list(f) [(x, 1), (x + 2, 4)] >>> (ff(x, 1)*ff(x + 2, 4)).expand() == f True """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('gff_list', 1, exc) factors = F.gff_list() if not opt.polys: return [ (g.as_expr(), k) for g, k in factors ] else: return factors def gff(f, *gens, **args): """Compute greatest factorial factorization of ``f``. """ raise NotImplementedError('symbolic falling factorial') def sqf_norm(f, *gens, **args): """ Compute square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import sqf_norm, sqrt >>> from sympy.abc import x >>> sqf_norm(x**2 + 1, extension=[sqrt(3)]) (1, x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('sqf_norm', 1, exc) s, g, r = F.sqf_norm() if not opt.polys: return Integer(s), g.as_expr(), r.as_expr() else: return Integer(s), g, r def sqf_part(f, *gens, **args): """ Compute square-free part of ``f``. Examples ======== >>> from sympy import sqf_part >>> from sympy.abc import x >>> sqf_part(x**3 - 3*x - 2) x**2 - x - 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('sqf_part', 1, exc) result = F.sqf_part() if not opt.polys: return result.as_expr() else: return result def _sorted_factors(factors, method): """Sort a list of ``(expr, exp)`` pairs. """ if method == 'sqf': def key(obj): poly, exp = obj rep = poly.rep.rep return (exp, len(rep), rep) else: def key(obj): poly, exp = obj rep = poly.rep.rep return (len(rep), exp, rep) return sorted(factors, key=key) def _factors_product(factors): """Multiply a list of ``(expr, exp)`` pairs. """ return Mul(*[ f.as_expr()**k for f, k in factors ]) def _symbolic_factor_list(expr, opt, method): """Helper function for :func:`_symbolic_factor`. """ coeff, factors = S.One, [] for arg in Mul.make_args(expr): if arg.is_Number: coeff *= arg continue elif arg.is_Pow: base, exp = arg.args if base.is_Number: factors.append((base, exp)) continue else: base, exp = arg, S.One try: poly, _ = _poly_from_expr(base, opt) except PolificationFailed, exc: factors.append((exc.expr, exp)) else: func = getattr(poly, method + '_list') _coeff, _factors = func() if _coeff is not S.One: if exp.is_Integer: coeff *= _coeff**exp elif _coeff.is_positive: factors.append((_coeff, exp)) else: _factors.append((_coeff, None)) if exp is S.One: factors.extend(_factors) elif exp.is_integer or len(_factors) == 1: factors.extend([ (f, k*exp) for f, k in _factors ]) else: other = [] for f, k in _factors: if f.as_expr().is_positive: factors.append((f, k*exp)) elif k is not None: other.append((f, k)) else: other.append((f, S.One)) if len(other) == 1: f, k = other[0] factors.append((f, k*exp)) else: factors.append((_factors_product(other), exp)) return coeff, factors def _symbolic_factor(expr, opt, method): """Helper function for :func:`_factor`. """ if isinstance(expr, Expr) and not expr.is_Relational: coeff, factors = _symbolic_factor_list(together(expr), opt, method) return _keep_coeff(coeff, _factors_product(factors)) elif hasattr(expr, 'args'): return expr.func(*[ _symbolic_factor(arg, opt, method) for arg in expr.args ]) elif hasattr(expr, '__iter__'): return expr.__class__([ _symbolic_factor(arg, opt, method) for arg in expr ]) else: return expr def _generic_factor_list(expr, gens, args, method): """Helper function for :func:`sqf_list` and :func:`factor_list`. """ options.allowed_flags(args, ['frac', 'polys']) opt = options.build_options(gens, args) expr = sympify(expr) if isinstance(expr, Expr) and not expr.is_Relational: numer, denom = together(expr).as_numer_denom() cp, fp = _symbolic_factor_list(numer, opt, method) cq, fq = _symbolic_factor_list(denom, opt, method) if fq and not opt.frac: raise PolynomialError("a polynomial expected, got %s" % expr) _opt = opt.clone(dict(expand=True)) for factors in (fp, fq): for i, (f, k) in enumerate(factors): if not f.is_Poly: f, _ = _poly_from_expr(f, _opt) factors[i] = (f, k) fp = _sorted_factors(fp, method) fq = _sorted_factors(fq, method) if not opt.polys: fp = [ (f.as_expr(), k) for f, k in fp ] fq = [ (f.as_expr(), k) for f, k in fq ] coeff = cp/cq if not opt.frac: return coeff, fp else: return coeff, fp, fq else: raise PolynomialError("a polynomial expected, got %s" % expr) def _generic_factor(expr, gens, args, method): """Helper function for :func:`sqf` and :func:`factor`. """ options.allowed_flags(args, []) opt = options.build_options(gens, args) return _symbolic_factor(sympify(expr), opt, method) def sqf_list(f, *gens, **args): """ Compute a list of square-free factors of ``f``. Examples ======== >>> from sympy import sqf_list >>> from sympy.abc import x >>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) (2, [(x + 1, 2), (x + 2, 3)]) """ return _generic_factor_list(f, gens, args, method='sqf') def sqf(f, *gens, **args): """ Compute square-free factorization of ``f``. Examples ======== >>> from sympy import sqf >>> from sympy.abc import x >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) 2*(x + 1)**2*(x + 2)**3 """ return _generic_factor(f, gens, args, method='sqf') def factor_list(f, *gens, **args): """ Compute a list of irreducible factors of ``f``. Examples ======== >>> from sympy import factor_list >>> from sympy.abc import x, y >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) (2, [(x + y, 1), (x**2 + 1, 2)]) """ return _generic_factor_list(f, gens, args, method='factor') def factor(f, *gens, **args): """ Compute the factorization of ``f`` into irreducibles. (Use factorint to factor an integer.) There two modes implemented: symbolic and formal. If ``f`` is not an instance of :class:`Poly` and generators are not specified, then the former mode is used. Otherwise, the formal mode is used. In symbolic mode, :func:`factor` will traverse the expression tree and factor its components without any prior expansion, unless an instance of :class:`Add` is encountered (in this case formal factorization is used). This way :func:`factor` can handle large or symbolic exponents. By default, the factorization is computed over the rationals. To factor over other domain, e.g. an algebraic or finite field, use appropriate options: ``extension``, ``modulus`` or ``domain``. Examples ======== >>> from sympy import factor, sqrt >>> from sympy.abc import x, y >>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) 2*(x + y)*(x**2 + 1)**2 >>> factor(x**2 + 1) x**2 + 1 >>> factor(x**2 + 1, modulus=2) (x + 1)**2 >>> factor(x**2 + 1, gaussian=True) (x - I)*(x + I) >>> factor(x**2 - 2, extension=sqrt(2)) (x - sqrt(2))*(x + sqrt(2)) >>> factor((x**2 - 1)/(x**2 + 4*x + 4)) (x - 1)*(x + 1)/(x + 2)**2 >>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1)) (x + 2)**20000000*(x**2 + 1) """ try: return _generic_factor(f, gens, args, method='factor') except PolynomialError, msg: if not f.is_commutative: from sympy.core.exprtools import factor_nc return factor_nc(f) else: raise PolynomialError(msg) def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. Examples ======== >>> from sympy import intervals >>> from sympy.abc import x >>> intervals(x**2 - 3) [((-2, -1), 1), ((1, 2), 1)] >>> intervals(x**2 - 3, eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if not hasattr(F, '__iter__'): try: F = Poly(F) except GeneratorsNeeded: return [] return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: polys, opt = parallel_poly_from_expr(F, domain='QQ') if len(opt.gens) > 1: raise MultivariatePolynomialError for i, poly in enumerate(polys): polys[i] = poly.rep.rep if eps is not None: eps = opt.domain.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = opt.domain.convert(inf) if sup is not None: sup = opt.domain.convert(sup) intervals = dup_isolate_real_roots_list(polys, opt.domain, eps=eps, inf=inf, sup=sup, strict=strict, fast=fast) result = [] for (s, t), indices in intervals: s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t) result.append(((s, t), indices)) return result def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import refine_root >>> from sympy.abc import x >>> refine_root(x**2 - 3, 1, 2, eps=1e-2) (19/11, 26/15) """ try: F = Poly(f) except GeneratorsNeeded: raise PolynomialError("can't refine a root of %s, not a polynomial" % f) return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. If one of ``inf`` or ``sup`` is complex, it will return the number of roots in the complex rectangle with corners at ``inf`` and ``sup``. Examples ======== >>> from sympy import count_roots, I >>> from sympy.abc import x >>> count_roots(x**4 - 4, -3, 3) 2 >>> count_roots(x**4 - 4, 0, 1 + 3*I) 1 """ try: F = Poly(f, greedy=False) except GeneratorsNeeded: raise PolynomialError("can't count roots of %s, not a polynomial" % f) return F.count_roots(inf=inf, sup=sup) def real_roots(f, multiple=True): """ Return a list of real roots with multiplicities of ``f``. Examples ======== >>> from sympy import real_roots >>> from sympy.abc import x >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4) [-1/2, 2, 2] """ try: F = Poly(f, greedy=False) except GeneratorsNeeded: raise PolynomialError("can't compute real roots of %s, not a polynomial" % f) return F.real_roots(multiple=multiple) def nroots(f, n=15, maxsteps=50, cleanup=True, error=False): """ Compute numerical approximations of roots of ``f``. Examples ======== >>> from sympy import nroots >>> from sympy.abc import x >>> nroots(x**2 - 3, n=15) [-1.73205080756888, 1.73205080756888] >>> nroots(x**2 - 3, n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ try: F = Poly(f, greedy=False) except GeneratorsNeeded: raise PolynomialError("can't compute numerical roots of %s, not a polynomial" % f) return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup, error=error) def ground_roots(f, *gens, **args): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import ground_roots >>> from sympy.abc import x >>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2) {0: 2, 1: 2} """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('ground_roots', 1, exc) return F.ground_roots() def nth_power_roots_poly(f, n, *gens, **args): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import nth_power_roots_poly, factor, roots >>> from sympy.abc import x >>> f = x**4 - x**2 + 1 >>> g = factor(nth_power_roots_poly(f, 2)) >>> g (x**2 - x + 1)**2 >>> R_f = [ (r**2).expand() for r in roots(f) ] >>> R_g = roots(g).keys() >>> set(R_f) == set(R_g) True """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('nth_power_roots_poly', 1, exc) result = F.nth_power_roots_poly(n) if not opt.polys: return result.as_expr() else: return result def cancel(f, *gens, **args): """ Cancel common factors in a rational function ``f``. Examples ======== >>> from sympy import cancel >>> from sympy.abc import x >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) (2*x + 2)/(x - 1) """ options.allowed_flags(args, ['polys']) f = sympify(f) if not isinstance(f, (tuple, Tuple)): if f.is_Number: return f else: p, q = f.as_numer_denom() else: p, q = f try: (F, G), opt = parallel_poly_from_expr((p, q), *gens, **args) except PolificationFailed: if not isinstance(f, (tuple, Tuple)): return f else: return S.One, p, q c, P, Q = F.cancel(G) if not isinstance(f, (tuple, Tuple)): return c*(P.as_expr()/Q.as_expr()) else: if not opt.polys: return c, P.as_expr(), Q.as_expr() else: return c, P, Q def reduced(f, G, *gens, **args): """ Reduces a polynomial ``f`` modulo a set of polynomials ``G``. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import reduced >>> from sympy.abc import x, y >>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y]) ([2*x, 1], x**2 + y**2 + y) """ options.allowed_flags(args, ['polys', 'auto']) try: polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('reduced', 0, exc) domain = opt.domain retract = False if opt.auto and domain.has_Ring and not domain.has_Field: opt = opt.clone(dict(domain = domain.get_field())) retract = True for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = sdp_from_dict(poly, opt.order) level = len(opt.gens)-1 Q, r = sdp_div(polys[0], polys[1:], level, opt.order, opt.domain) Q = [ Poly._from_dict(dict(q), opt) for q in Q ] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [ q.to_ring() for q in Q ], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [ q.as_expr() for q in Q ], r.as_expr() else: return Q, r def groebner(F, *gens, **args): """ Computes the reduced Groebner basis for a set of polynomials. Use the ``order`` argument to set the monomial ordering that will be used to compute the basis. Allowed orders are ``lex``, ``grlex`` and ``grevlex``. If no order is specified, it defaults to ``lex``. Examples ======== >>> from sympy import groebner >>> from sympy.abc import x, y >>> F = [x*y - 2*y, 2*y**2 - x**2] >>> groebner(F, x, y, order='lex') GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, order='grlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grlex') >>> groebner(F, x, y, order='grevlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grevlex') By default, an improved implementation of the Buchberger algorithm is used. Optionally, an implementation of the F5B algorithm can be used. The algorithm can be set using ``method`` flag or with the :func:`setup` function from :mod:`sympy.polys.polyconfig`: >>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)] >>> groebner(F, x, y, method='buchberger') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, method='f5b') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') References ========== 1. [Buchberger01]_ 2. [Cox97]_ """ return GroebnerBasis(F, *gens, **args) def is_zero_dimensional(F, *gens, **args): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ return GroebnerBasis(F, *gens, **args).is_zero_dimensional class GroebnerBasis(Basic): """Represents a reduced Groebner basis. """ __slots__ = ['_basis', '_options'] def __new__(cls, F, *gens, **args): """Compute a reduced Groebner basis for a system of polynomials. """ options.allowed_flags(args, ['polys', 'method']) try: polys, opt = parallel_poly_from_expr(F, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('groebner', len(F), exc) domain = opt.domain if domain.has_assoc_Field: opt.domain = domain.get_field() else: raise DomainError("can't compute a Groebner basis over %s" % opt.domain) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = sdp_from_dict(poly, opt.order) level = len(opt.gens) - 1 G = sdp_groebner(polys, level, opt.order, opt.domain, method=opt.method) G = [ Poly._from_dict(dict(g), opt) for g in G ] if not domain.has_Field: G = [ g.clear_denoms(convert=True)[1] for g in G ] opt.domain = domain return cls._new(G, opt) @classmethod def _new(cls, basis, options): obj = Basic.__new__(cls) obj._basis = tuple(basis) obj._options = options return obj @property def args(self): return (Tuple(*self._basis), Tuple(*self._options.gens)) @property def exprs(self): return [ poly.as_expr() for poly in self._basis ] @property def polys(self): return list(self._basis) @property def gens(self): return self._options.gens @property def domain(self): return self._options.domain @property def order(self): return self._options.order def __len__(self): return len(self._basis) def __iter__(self): if self._options.polys: return iter(self.polys) else: return iter(self.exprs) def __getitem__(self, item): if self._options.polys: basis = self.polys else: basis = self.exprs return basis[item] def __hash__(self): return hash((self._basis, tuple(self._options.items()))) def __eq__(self, other): if isinstance(other, self.__class__): return self._basis == other._basis and self._options == other._options elif iterable(other): return self.polys == list(other) or self.exprs == list(other) else: return False def __ne__(self, other): return not self.__eq__(other) @property def is_zero_dimensional(self): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ def single_var(monomial): return sum(map(bool, monomial)) == 1 exponents = Monomial([0]*len(self.gens)) order = self._options.order for poly in self.polys: monomial = poly.LM(order=order) if single_var(monomial): exponents *= monomial # If any element of the exponents vector is zero, then there's # a variable for which there's no degree bound and the ideal # generated by this Groebner basis isn't zero-dimensional. return all(exponents) def fglm(self, order): """ Convert a Groebner basis from one ordering to another. The FGLM algorithm converts reduced Groebner bases of zero-dimensional ideals from one ordering to another. This method is often used when it is infeasible to compute a Groebner basis with respect to a particular ordering directly. Examples ======== >>> from sympy.abc import x, y >>> from sympy import groebner >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] >>> G = groebner(F, x, y, order='grlex') >>> list(G.fglm('lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] >>> list(groebner(F, x, y, order='lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] References ========== J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient Computation of Zero-dimensional Groebner Bases by Change of Ordering J.C. Faugere's lecture notes: http://www-salsa.lip6.fr/~jcf/Papers/2010_MPRI5e.pdf """ opt = self._options src_order = opt.order dst_order = monomial_key(order) if src_order == dst_order: return self if not self.is_zero_dimensional: raise NotImplementedError("can't convert Groebner bases of ideals with positive dimension") polys = list(self._basis) domain = opt.domain opt = opt.clone(dict( domain = domain.get_field(), order = dst_order, )) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = sdp_from_dict(poly, src_order) level = len(opt.gens) - 1 G = matrix_fglm(polys, level, src_order, dst_order, opt.domain) G = [ Poly._from_dict(dict(g), opt) for g in G ] if not domain.has_Field: G = [ g.clear_denoms(convert=True)[1] for g in G ] opt.domain = domain return self._new(G, opt) def reduce(self, expr, auto=True): """ Reduces a polynomial modulo a Groebner basis. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import groebner, expand >>> from sympy.abc import x, y >>> f = 2*x**4 - x**2 + y**3 + y**2 >>> G = groebner([x**3 - x, y**3 - y]) >>> G.reduce(f) ([2*x, 1], x**2 + y**2 + y) >>> Q, r = _ >>> expand(sum(q*g for q, g in zip(Q, G)) + r) 2*x**4 - x**2 + y**3 + y**2 >>> _ == f True """ poly = Poly._from_expr(expr, self._options) polys = [poly] + list(self._basis) opt = self._options domain = opt.domain retract = False if auto and domain.has_Ring and not domain.has_Field: opt = opt.clone(dict(domain = domain.get_field())) retract = True for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = sdp_from_dict(poly, opt.order) level = len(opt.gens) - 1 Q, r = sdp_div(polys[0], polys[1:], level, opt.order, opt.domain) Q = [ Poly._from_dict(dict(q), opt) for q in Q ] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [ q.to_ring() for q in Q ], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [ q.as_expr() for q in Q ], r.as_expr() else: return Q, r def contains(self, poly): """ Check if ``poly`` belongs the ideal generated by ``self``. Examples ======== >>> from sympy import groebner >>> from sympy.abc import x, y >>> f = 2*x**3 + y**3 + 3*y >>> G = groebner([x**2 + y**2 - 1, x*y - 2]) >>> G.contains(f) True >>> G.contains(f + 1) False """ return self.reduce(poly)[1] == 0 def poly(expr, *gens, **args): """ Efficiently transform an expression into a polynomial. Examples ======== >>> from sympy import poly >>> from sympy.abc import x >>> poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') """ options.allowed_flags(args, []) def _poly(expr, opt): terms, poly_terms = [], [] for term in Add.make_args(expr): factors, poly_factors = [], [] for factor in Mul.make_args(term): if factor.is_Add: poly_factors.append(_poly(factor, opt)) elif factor.is_Pow and factor.base.is_Add and factor.exp.is_Integer: poly_factors.append(_poly(factor.base, opt).pow(factor.exp)) else: factors.append(factor) if not poly_factors: terms.append(term) else: product = poly_factors[0] for factor in poly_factors[1:]: product = product.mul(factor) if factors: factor = Mul(*factors) if factor.is_Number: product = product.mul(factor) else: product = product.mul(Poly._from_expr(factor, opt)) poly_terms.append(product) if not poly_terms: result = Poly._from_expr(expr, opt) else: result = poly_terms[0] for term in poly_terms[1:]: result = result.add(term) if terms: term = Add(*terms) if term.is_Number: result = result.add(term) else: result = result.add(Poly._from_expr(term, opt)) return result.reorder(*opt.get('gens', ()), **args) expr = sympify(expr) if expr.is_Poly: return Poly(expr, *gens, **args) if 'expand' not in args: args['expand'] = False opt = options.build_options(gens, args) return _poly(expr, opt)
flacjacket/sympy
sympy/polys/polytools.py
Python
bsd-3-clause
151,151
[ "Gaussian" ]
4721a81a5ada0f355410bfa60094fbfde8f0ca4f1520b9f1c7ac1489a7694b04
#!/usr/bin/env python3 import numpy as np from matplotlib import pyplot as plt from LoLIM.utilities import processed_data_dir, v_air from LoLIM.interferometry import read_interferometric_PSE as R_IPSE from LoLIM.interferometry import impulsive_imager_tools as inter_tools from LoLIM.signal_processing import half_hann_window from scipy.optimize import minimize ## these lines are anachronistic and should be fixed at some point from LoLIM import utilities utilities.default_raw_data_loc = "/exp_app2/appexp1/lightning_data" utilities.default_processed_data_loc = "/home/brian/processed_files" if __name__ == "__main__": timeID = "D20180813T153001.413Z" # input_folder = "interferometry_out2_TEST" # unique_ID = 24070 # N = 10 input_folder = "interferometry_out2" # unique_ID = 240700 unique_ID = 240783 N = 100 block_help = [int(unique_ID/N)] image_widths = [100,100,100] # image_widths = [30,30,120] max_pixel_size = 0.2 num_threads = 4 ### open data ### processed_data_folder = processed_data_dir(timeID) data_dir = processed_data_folder + "/" + input_folder interferometry_header, IPSE_list = R_IPSE.load_interferometric_PSE( data_dir, blocks_to_open=block_help ) IPSE_to_image = [IPSE for IPSE in IPSE_list if IPSE.unique_index==unique_ID][0] print("intensity:", IPSE_to_image.intensity) print(" loc:", IPSE_to_image.loc) # prefered_antenna_index = IPSE_to_image.prefered_antenna_index ## prep imager ### # antennas = interferometry_header.antenna_data ## all antennas = [ant for ant in interferometry_header.antenna_data if interferometry_header.use_core_stations_S2 or np.isfinite( ant.no_core_ant_i ) ] num_antennas = len( antennas ) antenna_delays = np.zeros(num_antennas) antenna_locs = np.zeros( (num_antennas,3) ) for ant_info in antennas: index = ant_info.no_core_ant_i if interferometry_header.use_core_stations_S2: index = ant_info.with_core_ant_i antenna_delays[ index ] = ant_info.timing_delay antenna_locs[ index ] = ant_info.location # if ant_info.antenna_index == IPSE_to_image.prefered_antenna_index: # prefered_antenna_index = index pref_ant_loc = None pref_ant_delay = None for ant in interferometry_header.antenna_data: if ant.with_core_ant_i == IPSE_to_image.prefered_antenna_index: pref_ant_loc = np.array( ant.location ) pref_ant_delay = ant.timing_delay imager = inter_tools.image_data_stage2_absBefore( antenna_locs, antenna_delays, interferometry_header.trace_length_stage2, interferometry_header.upsample_factor ) # imager = inter_tools.image_data_stage2ABSafter( antenna_locs, antenna_delays, interferometry_header.trace_length_stage2, interferometry_header.upsample_factor ) imaging_function = imager.intensity_multiprocessed_ABSbefore # imager = inter_tools.image_data_sumLog(antenna_locs, antenna_delays, interferometry_header.trace_length_stage2, interferometry_header.upsample_factor ) # imaging_function = imager.intensity_multiprocessed_sumLog file_dataset = IPSE_to_image.h5_dataset_opener.get_object() stage_2_window = half_hann_window(interferometry_header.pulse_length, interferometry_header.hann_window_fraction) for ant_i in range(num_antennas): old_ant_index = antennas[ant_i].antenna_index modeled_dt = -( np.linalg.norm( pref_ant_loc - IPSE_to_image.loc ) - np.linalg.norm( antenna_locs[ant_i]-IPSE_to_image.loc ) )/v_air A = modeled_dt modeled_dt -= pref_ant_delay - antenna_delays[ant_i] modeled_dt /= 5.0E-9 modeled_dt += IPSE_to_image.peak_index modeled_dt = -int(modeled_dt)*5.0E-9 read_data = np.array( file_dataset[old_ant_index], dtype=np.complex ) read_data *= stage_2_window imager.set_data( read_data, ant_i, modeled_dt ) imager.prepare_image( ) ### prep variables ### nX_pixels = int(2*image_widths[0]/max_pixel_size) + 1 nY_pixels = int(2*image_widths[1]/max_pixel_size) + 1 nZ_pixels = int(2*image_widths[2]/max_pixel_size) + 1 X_array = np.linspace( IPSE_to_image.loc[0]-image_widths[0], IPSE_to_image.loc[0]+image_widths[0], nX_pixels ) Y_array = np.linspace( IPSE_to_image.loc[1]-image_widths[1], IPSE_to_image.loc[1]+image_widths[1], nY_pixels ) Z_array = np.linspace( IPSE_to_image.loc[2]-image_widths[2], IPSE_to_image.loc[2]+image_widths[2], nZ_pixels ) ## image just X print("image X") XYZs = np.zeros( (nX_pixels, 3) ) for xi in range(nX_pixels): XYZs[xi,0] = X_array[xi] XYZs[xi,1] = IPSE_to_image.loc[1] XYZs[xi,2] = IPSE_to_image.loc[2] image = np.zeros( nX_pixels ) imaging_function( XYZs, image, num_threads ) print("plotting X") XYZs[:,0] -= IPSE_to_image.loc[0] image *= -1 plt.plot(XYZs[:,0], image) ## calculate the variance step = 5 values = [] for X in [-step, 0.0, step]: I = -imager.intensity_ABSbefore( np.array([IPSE_to_image.loc[0]+X,IPSE_to_image.loc[1],IPSE_to_image.loc[2]] ) ) values.append( -np.log( I ) ) D = ( values[2]-2*values[1]+values[0] ) /(step*step ) var = 1.0/D intensity = -imager.intensity_ABSbefore( np.array([IPSE_to_image.loc[0],IPSE_to_image.loc[1],IPSE_to_image.loc[2]] ) ) print( var,intensity ) def G(X): return intensity*np.exp(-X*X*D*0.5) plt.plot(XYZs[:,0], G(XYZs[:,0]), 'k') plt.show() ## image just Y print("image Y") XYZs = np.zeros( (nY_pixels, 3) ) for i in range(nY_pixels): XYZs[i,0] = IPSE_to_image.loc[0] XYZs[i,1] = Y_array[i] XYZs[i,2] = IPSE_to_image.loc[2] image = np.zeros( nY_pixels ) imaging_function( XYZs, image, num_threads ) print("plotting Y") XYZs[:,1] -= IPSE_to_image.loc[1] image *= -1 # for XYZ, I in zip(XYZs, image): # print(XYZ[1], I) plt.plot(XYZs[:,1], image) ## calculate the variance step = 5 values = [] for X in [-step, 0.0, step]: I = -imager.intensity_ABSbefore( np.array([IPSE_to_image.loc[0],IPSE_to_image.loc[1]+X,IPSE_to_image.loc[2]] ) ) values.append( -np.log( I ) ) D = ( values[2]-2*values[1]+values[0] ) /(step*step ) var = 1.0/D intensity = -imager.intensity_ABSbefore( np.array([IPSE_to_image.loc[0],IPSE_to_image.loc[1],IPSE_to_image.loc[2]] ) ) print( var,intensity ) def G(X): return intensity*np.exp(-X*X*D*0.5) plt.plot(XYZs[:,1], G(XYZs[:,1]), 'k') plt.show() ## image just Z print("image Z") XYZs = np.zeros( (nZ_pixels, 3) ) for i in range(nZ_pixels): XYZs[i,0] = IPSE_to_image.loc[0] XYZs[i,1] = IPSE_to_image.loc[1] XYZs[i,2] = Z_array[i] image = np.zeros( nZ_pixels ) imaging_function( XYZs, image, num_threads ) print("plotting Z") XYZs[:,2] -= IPSE_to_image.loc[2] image *= -1 plt.plot(XYZs[:,2], image) ## calculate the variance step = 5 values = [] for X in [-step, 0.0, step]: I = -imager.intensity_ABSbefore( np.array([IPSE_to_image.loc[0],IPSE_to_image.loc[1],IPSE_to_image.loc[2]+X] ) ) values.append( -np.log( I ) ) D = ( values[2]-2*values[1]+values[0] ) /(step*step ) print("ARG", values) var = 1.0/D intensity = -imager.intensity_ABSbefore( np.array([IPSE_to_image.loc[0],IPSE_to_image.loc[1],IPSE_to_image.loc[2]] ) ) print( var,intensity ) def G(X): return intensity*np.exp(-X*X*D*0.5) plt.plot(XYZs[:,2], G(XYZs[:,2]), 'k') plt.show() quit() ## image X, Y ## print("image XY") XYZs = np.zeros( (nX_pixels*nY_pixels, 3) ) for xi in range(nX_pixels): for yj in range(nY_pixels): i = nY_pixels*xi + yj XYZs[i,0] = X_array[xi] XYZs[i,1] = Y_array[yj] XYZs[i,2] = IPSE_to_image.loc[2] image = np.zeros( nX_pixels*nY_pixels ) imaging_function( XYZs, image, num_threads ) print("plotting XY") image *= -1 image = np.swapaxes(image.reshape( nX_pixels, nY_pixels ), 0,1) plt.pcolormesh(X_array-IPSE_to_image.loc[0], Y_array-IPSE_to_image.loc[1], image, vmin=0.3, vmax=1.0) plt.colorbar() circle1 = plt.Circle((0.0,0.0), radius=0.25, alpha=.3, color='k') plt.gca().add_patch( circle1 ) plt.show() ## image X, Z ## print("image XZ") XYZs = np.zeros( (nX_pixels*nZ_pixels, 3) ) for xi in range(nX_pixels): for zk in range(nZ_pixels): i = nZ_pixels*xi + zk XYZs[i,0] = X_array[xi] XYZs[i,1] = IPSE_to_image.loc[1] XYZs[i,2] = Z_array[zk] image = np.zeros( nX_pixels*nZ_pixels ) imaging_function( XYZs, image, num_threads ) print("plotting XZ") image *= -1 image = np.swapaxes(image.reshape( nX_pixels, nZ_pixels ), 0,1) plt.pcolormesh(X_array-IPSE_to_image.loc[0], Z_array-IPSE_to_image.loc[2], image, vmin=0.3, vmax=1.0) plt.colorbar() circle1 = plt.Circle((0.0,0.0), radius=0.25, alpha=.3, color='k') plt.gca().add_patch( circle1 ) plt.show() ## image X, Z ## # print("image YZ") # XYZs = np.zeros( (nY_pixels*nZ_pixels, 3) ) # for yj in range(nY_pixels): # for zk in range(nZ_pixels): # i = nZ_pixels*yj + zk # XYZs[i,0] = IPSE_to_image.loc[0] # XYZs[i,1] = Y_array[yj] # XYZs[i,2] = Z_array[zk] # # image = np.zeros( nY_pixels*nZ_pixels ) # imaging_function( XYZs, image, num_threads ) # # print("plotting YZ") # # image *= -1 # image = np.swapaxes( image.reshape( nY_pixels, nZ_pixels ), 0,1) # # plt.pcolormesh(Y_array, Z_array, image) # plt.colorbar() # circle1 = plt.Circle((IPSE_to_image.loc[1],IPSE_to_image.loc[2]), radius=0.25, alpha=.3, color='k') # plt.gca().add_patch( circle1 ) # plt.show()
Bhare8972/LOFAR-LIM
LIM_scripts/interferometry/examples/image_source.py
Python
mit
10,342
[ "Brian" ]
383d34ffeb5a42b0830fe6b706184193f86c4ebb3b6746f5ae342ef6ed1af2a5
# ---------------------------------------------------------------------- # LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator # https://www.lammps.org/ Sandia National Laboratories # Steve Plimpton, sjplimp@sandia.gov # # Copyright (2003) Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains # certain rights in this software. This software is distributed under # the GNU General Public License. # # See the README file in the top-level LAMMPS directory. # ------------------------------------------------------------------------- ################################################################################ # Alternative Python Wrapper # Written by Richard Berger <richard.berger@temple.edu> ################################################################################ # for python2/3 compatibility from __future__ import print_function import io import os import re import sys import tempfile from collections import namedtuple from .core import lammps # ------------------------------------------------------------------------- class OutputCapture(object): """ Utility class to capture LAMMPS library output """ def __init__(self): self.stdout_fd = 1 self.captured_output = "" def __enter__(self): self.tmpfile = tempfile.TemporaryFile(mode='w+b') sys.stdout.flush() # make copy of original stdout self.stdout_orig = os.dup(self.stdout_fd) # replace stdout and redirect to temp file os.dup2(self.tmpfile.fileno(), self.stdout_fd) return self def __exit__(self, exc_type, exc_value, traceback): os.dup2(self.stdout_orig, self.stdout_fd) os.close(self.stdout_orig) self.tmpfile.close() @property def output(self): sys.stdout.flush() self.tmpfile.flush() self.tmpfile.seek(0, io.SEEK_SET) self.captured_output = self.tmpfile.read().decode('utf-8') return self.captured_output # ------------------------------------------------------------------------- class Variable(object): def __init__(self, pylammps_instance, name, style, definition): self._pylmp = pylammps_instance self.name = name self.style = style self.definition = definition.split() @property def value(self): if self.style == 'atom': return list(self._pylmp.lmp.extract_variable(self.name, "all", 1)) else: value = self._pylmp.lmp_print('"${%s}"' % self.name).strip() try: return float(value) except ValueError: return value # ------------------------------------------------------------------------- class AtomList(object): """ A dynamic list of atoms that returns either an :py:class:`Atom` or :py:class:`Atom2D` instance for each atom. Instances are only allocated when accessed. :ivar natoms: total number of atoms :ivar dimensions: number of dimensions in system """ def __init__(self, pylammps_instance): self._pylmp = pylammps_instance self.natoms = self._pylmp.system.natoms self.dimensions = self._pylmp.system.dimensions self._loaded = {} def __getitem__(self, index): """ Return Atom with given local index :param index: Local index of atom :type index: int :rtype: Atom or Atom2D """ if index not in self._loaded: if self.dimensions == 2: atom = Atom2D(self._pylmp, index) else: atom = Atom(self._pylmp, index) self._loaded[index] = atom return self._loaded[index] def __len__(self): return self.natoms # ------------------------------------------------------------------------- class Atom(object): """ A wrapper class then represents a single atom inside of LAMMPS It provides access to properties of the atom and allows you to change some of them. """ def __init__(self, pylammps_instance, index): self._pylmp = pylammps_instance self.index = index def __dir__(self): return [k for k in super().__dir__() if not k.startswith('_')] def get(self, name, index): prop = self._pylmp.lmp.numpy.extract_atom(name) if prop is not None: return prop[index] return None @property def id(self): """ Return the atom ID :type: int """ return self.get("id", self.index) @property def type(self): """ Return the atom type :type: int """ return self.get("type", self.index) @property def mol(self): """ Return the atom molecule index :type: int """ return self.get("mol", self.index) @property def mass(self): """ Return the atom mass :type: float """ return self.get("mass", self.index) @property def radius(self): """ Return the particle radius :type: float """ return self.get("radius", self.index) @property def position(self): """ :getter: Return position of atom :setter: Set position of atom :type: numpy.array (float, float, float) """ return self.get("x", self.index) @position.setter def position(self, value): current = self.position current[:] = value @property def velocity(self): """ :getter: Return velocity of atom :setter: Set velocity of atom :type: numpy.array (float, float, float) """ return self.get("v", self.index) @velocity.setter def velocity(self, value): current = self.velocity current[:] = value @property def force(self): """ Return the total force acting on the atom :type: numpy.array (float, float, float) """ return self.get("f", self.index) @force.setter def force(self, value): current = self.force current[:] = value @property def torque(self): """ Return the total torque acting on the atom :type: numpy.array (float, float, float) """ return self.get("torque", self.index) @force.setter def torque(self, value): current = self.torque current[:] = value @property def omega(self): """ Return the rotational velocity of the particle :type: numpy.array (float, float, float) """ return self.get("torque", self.index) @omega.setter def omega(self, value): current = self.torque current[:] = value @property def torque(self): """ Return the total torque acting on the particle :type: numpy.array (float, float, float) """ return self.get("torque", self.index) @torque.setter def torque(self, value): current = self.torque current[:] = value @property def angular_momentum(self): """ Return the angular momentum of the particle :type: numpy.array (float, float, float) """ return self.get("angmom", self.index) @angular_momentum.setter def angular_momentum(self, value): current = self.angular_momentum current[:] = value @property def charge(self): """ Return the atom charge :type: float """ return self.get("q", self.index) # ------------------------------------------------------------------------- class Atom2D(Atom): """ A wrapper class then represents a single 2D atom inside of LAMMPS Inherits all properties from the :py:class:`Atom` class, but returns 2D versions of position, velocity, and force. It provides access to properties of the atom and allows you to change some of them. """ def __init__(self, pylammps_instance, index): super(Atom2D, self).__init__(pylammps_instance, index) @property def position(self): """Access to coordinates of an atom :getter: Return position of atom :setter: Set position of atom :type: numpy.array (float, float) """ return super(Atom2D, self).position[0:2] @position.setter def position(self, value): current = self.position current[:] = value @property def velocity(self): """Access to velocity of an atom :getter: Return velocity of atom :setter: Set velocity of atom :type: numpy.array (float, float) """ return super(Atom2D, self).velocity[0:2] @velocity.setter def velocity(self, value): current = self.velocity current[:] = value @property def force(self): """Access to force of an atom :getter: Return force of atom :setter: Set force of atom :type: numpy.array (float, float) """ return super(Atom2D, self).force[0:2] @force.setter def force(self, value): current = self.force current[:] = value # ------------------------------------------------------------------------- class variable_set: def __init__(self, name, variable_dict): self._name = name array_pattern = re.compile(r"(?P<arr>.+)\[(?P<index>[0-9]+)\]") for key, value in variable_dict.items(): m = array_pattern.match(key) if m: g = m.groupdict() varname = g['arr'] idx = int(g['index']) if varname not in self.__dict__: self.__dict__[varname] = {} self.__dict__[varname][idx] = value else: self.__dict__[key] = value def __str__(self): return "{}({})".format(self._name, ','.join(["{}={}".format(k, self.__dict__[k]) for k in self.__dict__.keys() if not k.startswith('_')])) def __dir__(self): return [k for k in self.__dict__.keys() if not k.startswith('_')] def __repr__(self): return self.__str__() # ------------------------------------------------------------------------- def get_thermo_data(output): """ traverse output of runs and extract thermo data columns """ if isinstance(output, str): lines = output.splitlines() else: lines = output runs = [] columns = [] in_run = False current_run = {} for line in lines: if line.startswith("Per MPI rank memory allocation"): in_run = True elif in_run and len(columns) == 0: # first line after memory usage are column names columns = line.split() current_run = {} for col in columns: current_run[col] = [] elif line.startswith("Loop time of "): in_run = False columns = [] thermo_data = variable_set('ThermoData', current_run) r = {'thermo' : thermo_data } runs.append(namedtuple('Run', list(r.keys()))(*list(r.values()))) elif in_run and len(columns) > 0: items = line.split() # Convert thermo output and store it. # It must have the same number of columns and # all of them must be convertible to floats. # Otherwise we ignore the line if len(items) == len(columns): try: values = [float(x) for x in items] for i, col in enumerate(columns): current_run[col].append(values[i]) except ValueError: # cannot convert. must be a non-thermo output. ignore. pass return runs # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- class PyLammps(object): """ This is a Python wrapper class around the lower-level :py:class:`lammps` class, exposing a more Python-like, object-oriented interface for prototyping system inside of IPython and Jupyter notebooks. It either creates its own instance of :py:class:`lammps` or can be initialized with an existing instance. The arguments are the same of the lower-level interface. The original interface can still be accessed via :py:attr:`PyLammps.lmp`. :param name: "machine" name of the shared LAMMPS library ("mpi" loads ``liblammps_mpi.so``, "" loads ``liblammps.so``) :type name: string :param cmdargs: list of command line arguments to be passed to the :cpp:func:`lammps_open` function. The executable name is automatically added. :type cmdargs: list :param ptr: pointer to a LAMMPS C++ class instance when called from an embedded Python interpreter. None means load symbols from shared library. :type ptr: pointer :param comm: MPI communicator (as provided by `mpi4py <mpi4py_docs_>`_). ``None`` means use ``MPI_COMM_WORLD`` implicitly. :type comm: MPI_Comm :ivar lmp: instance of original LAMMPS Python interface :vartype lmp: :py:class:`lammps` :ivar runs: list of completed runs, each storing the thermo output :vartype run: list """ def __init__(self, name="", cmdargs=None, ptr=None, comm=None): self.has_echo = False if cmdargs: if '-echo' in cmdargs: idx = cmdargs.index('-echo') # ensures that echo line is ignored during output capture self.has_echo = idx+1 < len(cmdargs) and cmdargs[idx+1] in ('screen', 'both') if ptr: if isinstance(ptr,PyLammps): self.lmp = ptr.lmp elif isinstance(ptr,lammps): self.lmp = ptr else: self.lmp = lammps(name=name,cmdargs=cmdargs,ptr=ptr,comm=comm) else: self.lmp = lammps(name=name,cmdargs=cmdargs,ptr=None,comm=comm) print("LAMMPS output is captured by PyLammps wrapper") self._cmd_history = [] self._enable_cmd_history = False self.runs = [] def __enter__(self): return self def __exit__(self, ex_type, ex_value, ex_traceback): self.close() def __del__(self): if self.lmp: self.lmp.close() self.lmp = None def close(self): """Explicitly delete a LAMMPS instance This is a wrapper around the :py:meth:`lammps.close` of the Python interface. """ if self.lmp: self.lmp.close() self.lmp = None def version(self): """Return a numerical representation of the LAMMPS version in use. This is a wrapper around the :py:meth:`lammps.version` function of the Python interface. :return: version number :rtype: int """ return self.lmp.version() def file(self, file): """Read LAMMPS commands from a file. This is a wrapper around the :py:meth:`lammps.file` function of the Python interface. :param path: Name of the file/path with LAMMPS commands :type path: string """ self.lmp.file(file) @property def enable_cmd_history(self): """ :getter: Return whether command history is saved :setter: Set if command history should be saved :type: bool """ return self._enable_cmd_history @enable_cmd_history.setter def enable_cmd_history(self, value): """ :getter: Return whether command history is saved :setter: Set if command history should be saved :type: bool """ self._enable_cmd_history = (value == True) def write_script(self, filepath): """ Write LAMMPS script file containing all commands executed up until now :param filepath: path to script file that should be written :type filepath: string """ with open(filepath, "w") as f: for cmd in self._cmd_history: print(cmd, file=f) def clear_cmd_history(self): """ Clear LAMMPS command history up to this point """ self._cmd_history = [] def command(self, cmd): """ Execute LAMMPS command If :py:attr:`PyLammps.enable_cmd_history` is set to ``True``, commands executed will be recorded. The entire command history can be written to a file using :py:meth:`PyLammps.write_script()`. To clear the command history, use :py:meth:`PyLammps.clear_cmd_history()`. :param cmd: command string that should be executed :type: cmd: string """ self.lmp.command(cmd) if self.enable_cmd_history: self._cmd_history.append(cmd) def run(self, *args, **kwargs): """ Execute LAMMPS run command with given arguments All thermo output during the run is captured and saved as new entry in :py:attr:`PyLammps.runs`. The latest run can be retrieved by :py:attr:`PyLammps.last_run`. """ output = self.__getattr__('run')(*args, **kwargs) self.runs += get_thermo_data(output) return output @property def last_run(self): """ Return data produced of last completed run command :getter: Returns an object containing information about the last run command :type: dict """ if len(self.runs) > 0: return self.runs[-1] return None @property def atoms(self): """ All atoms of this LAMMPS instance :getter: Returns a list of atoms currently in the system :type: AtomList """ return AtomList(self) @property def system(self): """ The system state of this LAMMPS instance :getter: Returns an object with properties storing the current system state :type: namedtuple """ output = self.lmp_info("system") output = output[output.index("System information:")+1:] d = self._parse_info_system(output) return namedtuple('System', d.keys())(*d.values()) @property def communication(self): """ The communication state of this LAMMPS instance :getter: Returns an object with properties storing the current communication state :type: namedtuple """ output = self.lmp_info("communication") output = output[output.index("Communication information:")+1:] d = self._parse_info_communication(output) return namedtuple('Communication', d.keys())(*d.values()) @property def computes(self): """ The list of active computes of this LAMMPS instance :getter: Returns a list of computes that are currently active in this LAMMPS instance :type: list """ output = self.lmp_info("computes") output = output[output.index("Compute information:")+1:] return self._parse_element_list(output) @property def dumps(self): """ The list of active dumps of this LAMMPS instance :getter: Returns a list of dumps that are currently active in this LAMMPS instance :type: list """ output = self.lmp_info("dumps") output = output[output.index("Dump information:")+1:] return self._parse_element_list(output) @property def fixes(self): """ The list of active fixes of this LAMMPS instance :getter: Returns a list of fixes that are currently active in this LAMMPS instance :type: list """ output = self.lmp_info("fixes") output = output[output.index("Fix information:")+1:] return self._parse_element_list(output) @property def groups(self): """ The list of active atom groups of this LAMMPS instance :getter: Returns a list of atom groups that are currently active in this LAMMPS instance :type: list """ output = self.lmp_info("groups") output = output[output.index("Group information:")+1:] return self._parse_groups(output) @property def variables(self): """ Returns a dictionary of all variables defined in the current LAMMPS instance :getter: Returns a dictionary of all variables that are defined in this LAMMPS instance :type: dict """ output = self.lmp_info("variables") output = output[output.index("Variable information:")+1:] variables = {} for v in self._parse_element_list(output): variables[v['name']] = Variable(self, v['name'], v['style'], v['def']) return variables def eval(self, expr): """ Evaluate expression :param expr: the expression string that should be evaluated inside of LAMMPS :type expr: string :return: the value of the evaluated expression :rtype: float if numeric, string otherwise """ value = self.lmp_print('"$(%s)"' % expr).strip() try: return float(value) except ValueError: return value def _split_values(self, line): return [x.strip() for x in line.split(',')] def _get_pair(self, value): return [x.strip() for x in value.split('=')] def _parse_info_system(self, output): system = {} for line in output: if line.startswith("Units"): system['units'] = self._get_pair(line)[1] elif line.startswith("Atom style"): system['atom_style'] = self._get_pair(line)[1] elif line.startswith("Atom map"): system['atom_map'] = self._get_pair(line)[1] elif line.startswith("Atoms"): parts = self._split_values(line) system['natoms'] = int(self._get_pair(parts[0])[1]) system['ntypes'] = int(self._get_pair(parts[1])[1]) system['style'] = self._get_pair(parts[2])[1] elif line.startswith("Kspace style"): system['kspace_style'] = self._get_pair(line)[1] elif line.startswith("Dimensions"): system['dimensions'] = int(self._get_pair(line)[1]) elif line.startswith("Orthogonal box"): system['orthogonal_box'] = [float(x) for x in self._get_pair(line)[1].split('x')] elif line.startswith("Boundaries"): system['boundaries'] = self._get_pair(line)[1] elif line.startswith("xlo"): keys, values = [self._split_values(x) for x in self._get_pair(line)] for key, value in zip(keys, values): system[key] = float(value) elif line.startswith("ylo"): keys, values = [self._split_values(x) for x in self._get_pair(line)] for key, value in zip(keys, values): system[key] = float(value) elif line.startswith("zlo"): keys, values = [self._split_values(x) for x in self._get_pair(line)] for key, value in zip(keys, values): system[key] = float(value) elif line.startswith("Molecule type"): system['molecule_type'] = self._get_pair(line)[1] elif line.startswith("Bonds"): parts = self._split_values(line) system['nbonds'] = int(self._get_pair(parts[0])[1]) system['nbondtypes'] = int(self._get_pair(parts[1])[1]) system['bond_style'] = self._get_pair(parts[2])[1] elif line.startswith("Angles"): parts = self._split_values(line) system['nangles'] = int(self._get_pair(parts[0])[1]) system['nangletypes'] = int(self._get_pair(parts[1])[1]) system['angle_style'] = self._get_pair(parts[2])[1] elif line.startswith("Dihedrals"): parts = self._split_values(line) system['ndihedrals'] = int(self._get_pair(parts[0])[1]) system['ndihedraltypes'] = int(self._get_pair(parts[1])[1]) system['dihedral_style'] = self._get_pair(parts[2])[1] elif line.startswith("Impropers"): parts = self._split_values(line) system['nimpropers'] = int(self._get_pair(parts[0])[1]) system['nimpropertypes'] = int(self._get_pair(parts[1])[1]) system['improper_style'] = self._get_pair(parts[2])[1] return system def _parse_info_communication(self, output): comm = {} for line in output: if line.startswith("MPI library"): comm['mpi_version'] = line.split(':')[1].strip() elif line.startswith("Comm style"): parts = self._split_values(line) comm['comm_style'] = self._get_pair(parts[0])[1] comm['comm_layout'] = self._get_pair(parts[1])[1] elif line.startswith("Processor grid"): comm['proc_grid'] = [int(x) for x in self._get_pair(line)[1].split('x')] elif line.startswith("Communicate velocities for ghost atoms"): comm['ghost_velocity'] = (self._get_pair(line)[1] == "yes") elif line.startswith("Nprocs"): parts = self._split_values(line) comm['nprocs'] = int(self._get_pair(parts[0])[1]) comm['nthreads'] = int(self._get_pair(parts[1])[1]) return comm def _parse_element_list(self, output): elements = [] for line in output: if not line or (":" not in line): continue element_info = self._split_values(line.split(':')[1].strip()) element = {'name': element_info[0]} for key, value in [self._get_pair(x) for x in element_info[1:]]: element[key] = value elements.append(element) return elements def _parse_groups(self, output): groups = [] group_pattern = re.compile(r"(?P<name>.+) \((?P<type>.+)\)") for line in output: m = group_pattern.match(line.split(':')[1].strip()) group = {'name': m.group('name'), 'type': m.group('type')} groups.append(group) return groups def lmp_print(self, s): """ needed for Python2 compatibility, since print is a reserved keyword """ return self.__getattr__("print")(s) def __dir__(self): return sorted(set(['angle_coeff', 'angle_style', 'atom_modify', 'atom_style', 'atom_style', 'bond_coeff', 'bond_style', 'boundary', 'change_box', 'communicate', 'compute', 'create_atoms', 'create_box', 'delete_atoms', 'delete_bonds', 'dielectric', 'dihedral_coeff', 'dihedral_style', 'dimension', 'dump', 'fix', 'fix_modify', 'group', 'improper_coeff', 'improper_style', 'include', 'kspace_modify', 'kspace_style', 'lattice', 'mass', 'minimize', 'min_style', 'neighbor', 'neigh_modify', 'newton', 'nthreads', 'pair_coeff', 'pair_modify', 'pair_style', 'processors', 'read', 'read_data', 'read_restart', 'region', 'replicate', 'reset_timestep', 'restart', 'run', 'run_style', 'thermo', 'thermo_modify', 'thermo_style', 'timestep', 'undump', 'unfix', 'units', 'variable', 'velocity', 'write_restart'] + self.lmp.available_styles("command"))) def lmp_info(self, s): # skip anything before and after Info-Info-Info # also skip timestamp line output = self.__getattr__("info")(s) indices = [index for index, line in enumerate(output) if line.startswith("Info-Info-Info-Info")] start = indices[0] end = indices[1] return [line for line in output[start+2:end] if line] def __getattr__(self, name): """ This method is where the Python 'magic' happens. If a method is not defined by the class PyLammps, it assumes it is a LAMMPS command. It takes all the arguments, concatinates them to a single string, and executes it using :py:meth:`lammps.PyLammps.command()`. :param verbose: Print output of command :type verbose: bool :return: line or list of lines of output, None if no output :rtype: list or string """ def handler(*args, **kwargs): cmd_args = [name] + [str(x) for x in args] self.lmp.flush_buffers() with OutputCapture() as capture: cmd = ' '.join(cmd_args) self.command(cmd) self.lmp.flush_buffers() output = capture.output comm = self.lmp.get_mpi_comm() if comm: output = self.lmp.comm.bcast(output, root=0) if 'verbose' in kwargs and kwargs['verbose']: print(output) lines = output.splitlines() if self.has_echo: lines = lines[1:] if len(lines) > 1: return lines elif len(lines) == 1: return lines[0] return None return handler class IPyLammps(PyLammps): """ IPython wrapper for LAMMPS which adds embedded graphics capabilities to PyLammmps interface It either creates its own instance of :py:class:`lammps` or can be initialized with an existing instance. The arguments are the same of the lower-level interface. The original interface can still be accessed via :py:attr:`PyLammps.lmp`. :param name: "machine" name of the shared LAMMPS library ("mpi" loads ``liblammps_mpi.so``, "" loads ``liblammps.so``) :type name: string :param cmdargs: list of command line arguments to be passed to the :cpp:func:`lammps_open` function. The executable name is automatically added. :type cmdargs: list :param ptr: pointer to a LAMMPS C++ class instance when called from an embedded Python interpreter. None means load symbols from shared library. :type ptr: pointer :param comm: MPI communicator (as provided by `mpi4py <mpi4py_docs_>`_). ``None`` means use ``MPI_COMM_WORLD`` implicitly. :type comm: MPI_Comm """ def __init__(self,name="",cmdargs=None,ptr=None,comm=None): super(IPyLammps, self).__init__(name=name,cmdargs=cmdargs,ptr=ptr,comm=comm) def image(self, filename="snapshot.png", group="all", color="type", diameter="type", size=None, view=None, center=None, up=None, zoom=1.0, background_color="white"): """ Generate image using write_dump command and display it See :doc:`dump image <dump_image>` for more information. :param filename: Name of the image file that should be generated. The extension determines whether it is PNG or JPEG :type filename: string :param group: the group of atoms write_image should use :type group: string :param color: name of property used to determine color :type color: string :param diameter: name of property used to determine atom diameter :type diameter: string :param size: dimensions of image :type size: tuple (width, height) :param view: view parameters :type view: tuple (theta, phi) :param center: center parameters :type center: tuple (flag, center_x, center_y, center_z) :param up: vector pointing to up direction :type up: tuple (up_x, up_y, up_z) :param zoom: zoom factor :type zoom: float :param background_color: background color of scene :type background_color: string :return: Image instance used to display image in notebook :rtype: :py:class:`IPython.core.display.Image` """ cmd_args = [group, "image", filename, color, diameter] if size is not None: width = size[0] height = size[1] cmd_args += ["size", width, height] if view is not None: theta = view[0] phi = view[1] cmd_args += ["view", theta, phi] if center is not None: flag = center[0] Cx = center[1] Cy = center[2] Cz = center[3] cmd_args += ["center", flag, Cx, Cy, Cz] if up is not None: Ux = up[0] Uy = up[1] Uz = up[2] cmd_args += ["up", Ux, Uy, Uz] if zoom is not None: cmd_args += ["zoom", zoom] cmd_args.append("modify backcolor " + background_color) self.write_dump(*cmd_args) from IPython.core.display import Image return Image(filename) def video(self, filename): """ Load video from file Can be used to visualize videos from :doc:`dump movie <dump_image>`. :param filename: Path to video file :type filename: string :return: HTML Video Tag used by notebook to embed a video :rtype: :py:class:`IPython.display.HTML` """ from IPython.display import HTML return HTML("<video controls><source src=\"" + filename + "\"></video>")
akohlmey/lammps
python/lammps/pylammps.py
Python
gpl-2.0
30,546
[ "LAMMPS" ]
2e258cb4a107883b59785ebbf44ef83c253f4ea81e88ef9bcdb243e6d8c8d612
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from absl.testing import parameterized import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib.data.python.ops import resampling from tensorflow.python.data.kernel_tests import test_base from tensorflow.python.data.ops import dataset_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import string_ops from tensorflow.python.platform import test from tensorflow.python.util import compat def _time_resampling( test_obj, data_np, target_dist, init_dist, num_to_sample): dataset = dataset_ops.Dataset.from_tensor_slices(data_np).repeat() # Reshape distribution via rejection sampling. dataset = dataset.apply( resampling.rejection_resample( class_func=lambda x: x, target_dist=target_dist, initial_dist=init_dist, seed=142)) get_next = dataset.make_one_shot_iterator().get_next() with test_obj.test_session() as sess: start_time = time.time() for _ in xrange(num_to_sample): sess.run(get_next) end_time = time.time() return end_time - start_time class ResampleTest(test_base.DatasetTestBase, parameterized.TestCase): @parameterized.named_parameters( ("InitialDistributionKnown", True), ("InitialDistributionUnknown", False)) def testDistribution(self, initial_known): classes = np.random.randint(5, size=(20000,)) # Uniformly sampled target_dist = [0.9, 0.05, 0.05, 0.0, 0.0] initial_dist = [0.2] * 5 if initial_known else None classes = math_ops.to_int64(classes) # needed for Windows build. dataset = dataset_ops.Dataset.from_tensor_slices(classes).shuffle( 200, seed=21).map(lambda c: (c, string_ops.as_string(c))).repeat() get_next = dataset.apply( resampling.rejection_resample( target_dist=target_dist, initial_dist=initial_dist, class_func=lambda c, _: c, seed=27)).make_one_shot_iterator().get_next() with self.cached_session() as sess: returned = [] while len(returned) < 4000: returned.append(sess.run(get_next)) returned_classes, returned_classes_and_data = zip(*returned) _, returned_data = zip(*returned_classes_and_data) self.assertAllEqual([compat.as_bytes(str(c)) for c in returned_classes], returned_data) total_returned = len(returned_classes) class_counts = np.array([ len([True for v in returned_classes if v == c]) for c in range(5)]) returned_dist = class_counts / total_returned self.assertAllClose(target_dist, returned_dist, atol=1e-2) @parameterized.named_parameters( ("OnlyInitial", True), ("NotInitial", False)) def testEdgeCasesSampleFromInitialDataset(self, only_initial_dist): init_dist = [0.5, 0.5] target_dist = [0.5, 0.5] if only_initial_dist else [0.0, 1.0] num_classes = len(init_dist) # We don't need many samples to test that this works. num_samples = 100 data_np = np.random.choice(num_classes, num_samples, p=init_dist) dataset = dataset_ops.Dataset.from_tensor_slices(data_np) # Reshape distribution. dataset = dataset.apply( resampling.rejection_resample( class_func=lambda x: x, target_dist=target_dist, initial_dist=init_dist)) get_next = dataset.make_one_shot_iterator().get_next() with self.cached_session() as sess: returned = [] with self.assertRaises(errors.OutOfRangeError): while True: returned.append(sess.run(get_next)) def testRandomClasses(self): init_dist = [0.25, 0.25, 0.25, 0.25] target_dist = [0.0, 0.0, 0.0, 1.0] num_classes = len(init_dist) # We don't need many samples to test a dirac-delta target distribution. num_samples = 100 data_np = np.random.choice(num_classes, num_samples, p=init_dist) dataset = dataset_ops.Dataset.from_tensor_slices(data_np) # Apply a random mapping that preserves the data distribution. def _remap_fn(_): return math_ops.cast(random_ops.random_uniform([1]) * num_classes, dtypes.int32)[0] dataset = dataset.map(_remap_fn) # Reshape distribution. dataset = dataset.apply( resampling.rejection_resample( class_func=lambda x: x, target_dist=target_dist, initial_dist=init_dist)) get_next = dataset.make_one_shot_iterator().get_next() with self.cached_session() as sess: returned = [] with self.assertRaises(errors.OutOfRangeError): while True: returned.append(sess.run(get_next)) classes, _ = zip(*returned) bincount = np.bincount( np.array(classes), minlength=num_classes).astype(np.float32) / len(classes) self.assertAllClose(target_dist, bincount, atol=1e-2) class ResampleDatasetBenchmark(test.Benchmark): def benchmarkResamplePerformance(self): init_dist = [0.25, 0.25, 0.25, 0.25] target_dist = [0.0, 0.0, 0.0, 1.0] num_classes = len(init_dist) # We don't need many samples to test a dirac-delta target distribution num_samples = 1000 data_np = np.random.choice(num_classes, num_samples, p=init_dist) resample_time = _time_resampling( self, data_np, target_dist, init_dist, num_to_sample=1000) self.report_benchmark( iters=1000, wall_time=resample_time, name="benchmark_resample") if __name__ == "__main__": test.main()
kobejean/tensorflow
tensorflow/contrib/data/python/kernel_tests/resample_test.py
Python
apache-2.0
6,486
[ "DIRAC" ]
9a4b0e50313755b9e0238b6f6496dfea7a86d7ddacf7492bcf38e808e52e8f74
import scipy.io as sio import matplotlib.pyplot as plt from v1_lstm import * from costs_v1 import * from layers_v1 import * from neon.backends import gen_backend from neon.initializers import GlorotUniform from neon.layers import GeneralizedCost, LSTM, Affine, RecurrentLast, Dropout, GRU, RecurrentSum from neon.models import Model from neon.optimizers import * from neon.transforms import * from neon.transforms.cost import Metric from neon.callbacks.callbacks import Callbacks, MetricCallback from neon import logger as neon_logger from neon.util.argparser import NeonArgparser, extract_valid_args from kohn_v1_dataset import KohnV1Dataset def main(): parser = NeonArgparser(__doc__) args = parser.parse_args(gen_be=False) #mat_data = sio.loadmat('../data/timeseries/02_timeseries.mat') #ts = V1TimeSeries(mat_data['timeseries'], mat_data['stim'], binning=10) seq_len = 30 hidden = 20 be = gen_backend(**extract_valid_args(args, gen_backend)) kohn = KohnV1Dataset(path='../tmp/') kohn.gen_iterators(seq_len) import pdb; pdb.set_trace() train_spike_set = V1IteratorSequence(ts.train, seq_len, return_sequences=False) valid_spike_set = V1IteratorSequence(ts.test, seq_len, return_sequences=False) init = GlorotUniform() # dataset = MNIST(path=args.data_dir) # (X_train, y_train), (X_test, y_test), nclass = dataset.load_data() # train_set = ArrayIterator([X_train, X_train], y_train, nclass=nclass, lshape=(1, 28, 28)) # valid_set = ArrayIterator([X_test, X_test], y_test, nclass=nclass, lshape=(1, 28, 28)) # # weight initialization # init_norm = Gaussian(loc=0.0, scale=0.01) # # initialize model # path1 = Sequential(layers=[Affine(nout=100, init=init_norm, activation=Rectlin()), # Affine(nout=100, init=init_norm, activation=Rectlin())]) # path2 = Sequential(layers=[Affine(nout=100, init=init_norm, activation=Rectlin()), # Affine(nout=100, init=init_norm, activation=Rectlin())]) # layers = [MergeMultistream(layers=[path1, path2], merge="stack"), # Affine(nout=10, init=init_norm, activation=Logistic(shortcut=True))] spike_rnn_path = Sequential( layers = [ LSTM(hidden, init, activation=Logistic(), gate_activation=Logistic(), reset_cells=False), Dropout(keep=0.5), LSTM(hidden, init, activation=Logistic(), gate_activation=Logistic(), reset_cells=False), #Dropout(keep=0.85), RecurrentLast(), Affine(train_set.nfeatures, init, bias=init, activation=Identity(), name='spike_in')]) stim_rnn_path = Sequential( layers = [ LSTM(hidden, init, activation=Logistic(), gate_activation=Logistic(), reset_cells=False), Dropout(keep=0.5), RecurrentLast(), Affine(1, init, bias=init, activation=Identity(), name='stim')]) layers = [ MergeMultiStream( layers = [ spike_rnn_path, stim_rnn_path], merge="stack"), Affine(train_set.nfeatures, init, bias=init, activation=Identity(), name='spike_out'), Round() ] model = Model(layers=layers) sched = ExpSchedule(decay=0.7) # cost = GeneralizedCost(SumSquared()) cost = GeneralizedCost(MeanSquared()) optimizer_two = RMSProp(stochastic_round=args.rounding) optimizer_one = GradientDescentMomentum(learning_rate=0.1, momentum_coef=0.9, schedule=sched) opt = MultiOptimizer({'default': optimizer_one, 'Bias': optimizer_two, 'special_linear': optimizer_two}) callbacks = Callbacks(model, eval_set=valid_set, **args.callback_args) callbacks.add_hist_callback(filter_key = ['W']) #callbacks.add_callback(MetricCallback(eval_set=valid_set, metric=FractionExplainedVariance(), epoch_freq=args.eval_freq)) #callbacks.add_callback(MetricCallback(eval_set=valid_set,metric=Accuracy(), epoch_freq=args.eval_freq)) model.fit(train_set, optimizer=opt, num_epochs=args.epochs, cost=cost, callbacks=callbacks) train_output = model.get_outputs( train_set).reshape(-1, train_set.nfeatures) valid_output = model.get_outputs( valid_set).reshape(-1, valid_set.nfeatures) train_target = train_set.y_series valid_target = valid_set.y_series tfev = fev(train_output, train_target, train_set.mean) vfev = fev(valid_output, valid_target, valid_set.mean) neon_logger.display('Train FEV: %g, Valid FEV: %g' % (tfev, vfev)) # neon_logger.display('Train Mean: %g, Valid Mean: %g' % (train_set.mean, valid_set.mean)) plt.figure() plt.plot(train_output[:, 0], train_output[ :, 1], 'bo', label='prediction') plt.plot(train_target[:, 0], train_target[:, 1], 'r.', label='target') plt.legend() plt.title('Neon on training set') plt.savefig('neon_series_training_output.png') plt.figure() plt.plot(valid_output[:, 0], valid_output[ :, 1], 'bo', label='prediction') plt.plot(valid_target[:, 0], valid_target[:, 1], 'r.', label='target') plt.legend() plt.title('Neon on validation set') plt.savefig('neon_series_validation_output.png') def fev(y,t, x_mean): sse = np.square(y-t).sum() var = np.square(x_mean.round()-t).sum() fev = 1 - (sse/var) return fev if __name__ == '__main__': main()
elijahc/ml_v1
rnn/neon/test_v1_lstm.py
Python
mit
5,537
[ "Gaussian" ]
711926648c810134a3cd8d86a368469df184eabe8a016dd3e12493ce60bb6352
import unittest import os import ruamel.yaml as yaml from pymatgen import SETTINGS_FILE, _load_pmg_settings, get_structure_from_mp, \ SETTINGS, loadfn from pymatgen import Structure from pymatgen.io.vasp import Vasprun import warnings test_dir = os.path.join(os.path.dirname(__file__), "..", "..", 'test_files') class SettingsTestCase(unittest.TestCase): # def test_something(self): # SETTINGS = _load_pmg_settings() # if os.path.exists(SETTINGS_FILE): # with open(SETTINGS_FILE, "rt") as f: # d = yaml.safe_load(f) # for k, v in d.items(): # self.assertEqual(v, SETTINGS[k]) # else: # for k, v in SETTINGS.items(): # self.assertEqual(v, os.environ.get(k)) @unittest.skipIf(not SETTINGS.get("PMG_MAPI_KEY"), "PMG_MAPI_KEY environment variable not set.") def test_get_structure_from_mp(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assertEqual(get_structure_from_mp("Li2O").formula, "Li2 O1") self.assertRaises(ValueError, get_structure_from_mp, "LiNaKCs") def test_loadfn(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") obj = loadfn(os.path.join(test_dir, "Li2O.cif")) self.assertIsInstance(obj, Structure) obj = loadfn(os.path.join(test_dir, "POSCAR")) self.assertIsInstance(obj, Structure) obj = loadfn(os.path.join(test_dir, "LiFePO4.vasp")) self.assertIsInstance(obj, Structure) obj = loadfn(os.path.join(test_dir, "vasprun.xml")) self.assertIsInstance(obj, Vasprun) if __name__ == '__main__': unittest.main()
gVallverdu/pymatgen
pymatgen/tests/test_init.py
Python
mit
1,797
[ "VASP", "pymatgen" ]
a8efb58ec6e9251d99048e0e395ea3865f856eaa4f59ef57c22ebac2311c7736
#------------------------------------------------------------------------------- # Name: results_analysis # Purpose: Contains graphing and analysis functions to look at results # # Author: dd # # Created: 12/02/2015 # Copyright: (c) dd 2015 # Licence: <your licence> #------------------------------------------------------------------------------- from __future__ import absolute_import from __future__ import print_function import glob import pandas from pandas import Series, DataFrame from scipy.stats.mstats import mode import matplotlib.pyplot as plt import seaborn as sns import db.corpora as cp from proc.general_utils import ensureTrailingBackslash, getFileDir, getFileName from six.moves import range ##from testingPipeline5 import measureCitationResolution, AZ_ZONES_LIST, CORESC_LIST def generateEqualWeights(): weights={x:INITIAL_VALUE for x in all_doc_methods[method]["runtime_parameters"]} def statsOnResults(data, metric="avg_mrr"): """ Returns the mean of the top results that have the same number """ res={} if len(data)==0: return val_to_match=data[metric].iloc[0] index=0 while data[metric].iloc[index]==val_to_match: index+=1 lines=data.iloc[:index] means=lines.mean() print("Averages:") for zone in AZ_ZONES_LIST: res[zone]=means[zone] print(zone,":",means[zone]) return res def drawSimilaritiesGraph(filename,metric, smooth_graph=False): """ Draws graph from CSV file """ dir=getFileDir(filename) if dir=="": filename=cp.Corpus.dir_output+filename print("Drawing graph for",filename) data=pandas.read_csv(filename) ## columns=AZ_ZONES_LIST+[metric] columns=[u"ilc_CSC_"+zone for zone in CORESC_LIST]+[metric] if columns[0] not in data.columns: columns=[zone for zone in CORESC_LIST]+[metric] if columns[0] not in data.columns: columns=[zone for zone in AZ_ZONES_LIST]+[metric] ## columns=["OWN","OTH","CTR","BKG","AIM"]+[metric] ## columns=["OWN","OTH","CTR"]+[metric] ## f = lambda x: mode(x, axis=None)[0] ## print data[columns].head(20).apply(f) ## print data.describe() numrows=data.shape[0] # (y,x) ## print data[columns].head(10).mean() data=data.sort(metric, ascending=False) # smoothing function rows_to_group=100 ## rows_to_group=numrows/700 f=lambda x:100-(x/rows_to_group) results=[] ## index=0 ## while index < numrows: ## means=data[columns].iloc[index:index+rows_to_group].mean() #### print means[metric] ## index+=rows_to_group ## results.append(means) ## results.reverse() if smooth_graph: df=data[columns].groupby([f], sort=True) results=df[columns].mean() else: data["g_"+metric]=data[metric] results=data.groupby(["g_"+metric])[columns].mean() ## colors = ["windows blue", "amber", "greyish", "faded green", "dusty purple", "baby pink"] ## sns.palplot(sns.xkcd_palette(colors)) ## flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71", "#002354", ""] ## sns.palplot(sns.color_palette(flatui)) ## print sns.color_palette("Set2") ## sns.set_style("white") sns.set_style("whitegrid") ## sns.set_style("whitegrid", {"grid.linewidth": .5}) ## sns.set_context("talk") sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) ## sns.set_palette(sns.color_palette("hls", 7)) ## sns.set_palette(sns.color_palette("husl", 7)) ## sns.set_palette("bright",n_colors=14,desat=0.9) sns.set_palette(sns.color_palette("gist_rainbow", 11),11,0.9) ## sns.palplot(sns.color_palette()) ## sns.palplot(sns.color_palette(n_colors=14) ) results_data=DataFrame(results) ## results_data.plot(x=metric, kind="line") results_data[columns].plot(title=filename,fontsize=20, x=metric) sns.despine() def compareResultsBetweenSimilarities(filenames): """ Loads a CSV of parameter-based results, compares selected measures by re-running them with a different simliarity, outputs results """ metric="precision_total" ## metric="avg_mrr" for filename in filenames: ## data['precision_2'] = Series(0, index=data.index) drawSimilaritiesGraph(filename,metric, True) plt.show() ## plt.savefig() def saveGraphForResults(filename,metric): """ """ dir=ensureTrailingBackslash(getFileDir(filename)) drawSimilaritiesGraph(filename,metric,True) name=getFileName(filename) plt.savefig(dir+name+'.png', bbox_inches='tight') plt.close() def computeOverlap(filename, overlap_in="rank", overlap_between=["az_annotated_1_ALL","az_annotated_1_ALL_EXPLAIN"]): """ """ data=pandas.read_csv(cp.Corpus.dir_output+filename) ## data['precision_2'] = Series(0, index=data.index) ## data=DataFrame(self.overall_results) print(data.describe()) group=data.groupby(["file_guid","citation_id"]) all_overlaps=[] for a,b in group: numitems=b.shape[0] results=[] for i in range(numitems): doc_method=b.iloc[i]["doc_method"] rank=b.iloc[i][overlap_in] if doc_method in overlap_between: results.append(rank) this_one=1 for index in range(len(results)-1): if results[index] != results[index+1]: this_one=0 break all_overlaps.append(this_one) print("Overlap between", overlap_between," in ",overlap_in,": %02.4f" % (sum(all_overlaps) / float(len(all_overlaps)))) def drawGraphOfScorePerMethod(data): """ """ # !TODO IMPLEMENT columns=[] print(data.describe()) numrows=data.shape[0] # (y,x) print(data[columns].head(10).mean()) data=data.sort(metric, ascending=False) rows_to_group=100 f=lambda x:100-(x/rows_to_group) results=[] ## index=0 ## while index < numrows: ## means=data[columns].iloc[index:index+rows_to_group].mean() #### print means[metric] ## index+=rows_to_group ## results.append(means) ## results.reverse() ## data["g_"+metric]=data[metric] ## results=data.groupby(["g_"+metric])[columns].mean() results=data[columns].groupby([f], sort=True)[columns].mean() sns.set_style("whitegrid") sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) sns.set_palette("bright",8,0.9) results_data=DataFrame(results) ## results_data.plot(x=metric, kind="line") results_data[columns].plot(title=filename,fontsize=20, x=metric) sns.despine() def compareResultsBetweenMethods(filename, metric="precision_total"): """ """ # !TODO IMPLEMENT data=pandas.read_csv(cp.Corpus.dir_output+filename) ## metric="avg_mrr" for filename in filenames: ## data['precision_2'] = Series(0, index=data.index) drawSimilaritiesGraph(filename,metric) plt.show() def drawNewSimilaritiesGraph(filename, metric, single_out="OWN", smooth_graph=False): """ Draws graph from CSV file """ data=pandas.read_csv(cp.Corpus.dir_output+filename) columns=AZ_ZONES_LIST+[metric] ## f = lambda x: mode(x, axis=None)[0] ## print data[columns].head(20).apply(f) for zone in AZ_ZONES_LIST: data["pct_"+zone]=data[zone]/data[AZ_ZONES_LIST].sum(axis=1) columns.append("pct_"+zone) print(data.describe()) numrows=data.shape[0] # (y,x) print(data[columns].head(10).mean()) data=data.sort(metric, ascending=False) # smoothing function rows_to_group=100 f=lambda x:100-(x/rows_to_group) results=[] if smooth_graph: results=data[columns].groupby([f], sort=True)[columns].mean() else: data["g_"+metric]=data[metric] results=data.groupby(["g_"+metric])[columns].mean() sns.set_style("whitegrid") sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) sns.set_palette("bright",8,0.9) results_data=DataFrame(results) ## results_data.plot(x=metric, kind="line") ax=results_data[["pct_"+single_out,metric]].plot(title=filename,fontsize=20, y=metric, x="pct_"+single_out) ax.set_ylabel(metric) sns.despine() def compareNewSimilaritiesGraph(filenames): """ Loads a CSV of parameter-based results, compares selected measures by re-running them with a different simliarity, outputs results """ metric="precision_total" ## metric="avg_mrr" for filename in filenames: ## data['precision_2'] = Series(0, index=data.index) drawNewSimilaritiesGraph(filename,metric, "BKG",True) plt.show() def makeAllGraphsForExperiment(exp_dir): """ Iterates through all weight*.csv files in the experiment's directory and saves a graph for each """ ## metric="avg_mrr" ## metric="precision_total" metric="avg_precision" exp_dir=ensureTrailingBackslash(exp_dir) ## working_dir=Corpus.dir_experiments+exp_name+os.sep for path in glob.glob(exp_dir+"weight*.csv"): saveGraphForResults(path,metric) def drawWeights(exp,weights,name): """ """ sns.set_style("whitegrid") sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) sns.set_palette(sns.color_palette("gist_rainbow", 11),11,0.9) results_data=DataFrame(weights,[0]) results_data.plot(kind="bar",title="weights",fontsize=20, ylim=(-15,15)) sns.despine() ## plt.show() ## name=getFileName(name) plt.savefig(exp["exp_dir"]+name+'.png', bbox_inches='tight') plt.close() def drawScoreProgression(exp,scores,name): """ """ sns.set_style("whitegrid") sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) sns.set_palette(sns.color_palette("gist_rainbow", 11),11,0.9) print(scores) results_data=DataFrame(scores) results_data.plot(kind="line",title="scores",fontsize=20, xlim=(0,8)) sns.despine() ## plt.show() plt.savefig(exp["exp_dir"]+str(name)+'.png', bbox_inches='tight') plt.close() def main(): ## filenames=["weights_OWN_max2_inc2.00_ini1_FA_bulkScorer.csv","weights_OWN_max2_inc1.00_ini1_BooleanQuery.csv"] ## filenames=["weights_OWN_['1', '3', '5']_FA_bulkScorer_first1000.csv","weights_OWN_['1', '3', '5']_FA_bulkScorer_second1000.csv"] ## filenames=["weights_CTR_max2_inc1.00_ini1.csv"] ## filenames=["weights_BKG_max2_inc1.00_ini1.csv"] ## filenames=["weights_OTH_['1', '3', '5']_FA_BulkScorer_first650.csv","weights_OTH_['1', '3', '5']_FA_BulkScorer_second650.csv"] ## filenames=["weights_OWN_['1', '3', '5']test_optimized.csv","weights_OWN_['1', '3', '5']_FA_bulkScorer_second1000.csv"] ## filenames=["weights_OWN_['1', '3', '5']test_optimized_defaultsim_first1000.csv","weights_OWN_['1', '3', '5']test_optimized_defaultsim_second1000.csv"] ## filenames=["weights_OWN_['1', '3', '5']_FA_bulkScorer_first1000.csv","weights_OWN_['1', '3', '5', '7', '9']test_optimized_fa_first1000.csv"] filenames=["weights_OWN_['1', '3', '5', '7', '9']test_optimized_fa_first1000.csv","weights_OWN_['1', '3', '5', '7', '9']test_optimized_fa_second1000.csv"] filenames=["weights_OWN_['1', '3', '5', '7', '9']test_optimized_fa_second1000.csv","weights_OWN_[1, 3, 5, 7]test_optimized_fa_third1000.csv"] filenames=["weights_Hyp_[1, 5]_s1.csv","weights_Mot_[1, 5]_s1.csv"] filenames=["weights_Bac_[1, 5]_s1.csv","weights_Goa_[1, 5]_s1.csv"] filenames=[r"C:\NLP\PhD\bob\experiments\w20_ilcpar_csc_fa_w0135\weights_Bac_[1, 5]_s2.csv"] ## compareResultsBetweenSimilarities(filenames) ## compareNewSimilaritiesGraph(filenames[:1]) ## compareResultsBetweenSimilarities("weights_OWN_max2_inc2.00_ini1_FA_bulkScorer.csv") ## compareResultsBetweenSimilarities("weights_OWN_max2_inc1.00_ini1_BooleanQuery.csv") ## compareResultsBetweenSimilarities("weights_AIM_max3_inc1.00_ini1.csv") ## compareResultsBetweenSimilarities("weights_BKG_max2_inc1.00_ini1.csv") ## compareResultsBetweenSimilarities("weights_CTR_max2_inc1.00_ini1.csv") ## compareResultsBetweenSimilarities("weights_BAS_max2_inc1.00_ini1.csv") ## computeOverlap("overlap_bulkScorer_explain.csv", overlap_in="precision_score") ## makeAllGraphsForExperiment(r"C:\NLP\PhD\bob\experiments\w20_csc_csc_fa_w0135") ## makeAllGraphsForExperiment(r"C:\NLP\PhD\bob\experiments\w20_ilcpar_csc_fa_w0135") ## drawWeights("",{"AIM":9,"BAS":5,"BKG":1,"CTR":9,"OTH":0,"OWN":1,"TXT":1}) drawScoreProgression({"exp_dir":r"C:\NLP\PhD\bob\experiments\w20_az_az_fa\\"},[1,2,3,4,4,4,5,6],0) pass if __name__ == '__main__': main()
danieldmm/minerva
evaluation/results_analysis.py
Python
gpl-3.0
12,728
[ "Amber" ]
954efdbf6ccace9d864ac0ba6f0fb4e1c3213728fd26be2f26c62d27e361f3dd
import pysal from pysal.common import * import pysal.weights import numpy as np from scipy import sparse, float32 import scipy.spatial import os import operator import scipy __all__ = ['lat2W', 'block_weights', 'comb', 'order', 'higher_order', 'shimbel', 'remap_ids', 'full2W', 'full', 'WSP2W', 'insert_diagonal', 'get_ids', 'get_points_array_from_shapefile', 'min_threshold_distance', 'lat2SW', 'w_local_cluster', 'higher_order_sp', 'hexLat2W', 'regime_weights'] def hexLat2W(nrows=5, ncols=5): """ Create a W object for a hexagonal lattice. Parameters ---------- nrows : int number of rows ncols : int number of columns Returns ------- w : W instance of spatial weights class W Notes ----- Observations are row ordered: first k observations are in row 0, next k in row 1, and so on. Construction is based on shifting every other column of a regular lattice down 1/2 of a cell. Examples -------- >>> import pysal as ps >>> w = ps.lat2W() >>> w.neighbors[1] [0, 6, 2] >>> w.neighbors[21] [16, 20, 22] >>> wh = ps.hexLat2W() >>> wh.neighbors[1] [0, 6, 2, 5, 7] >>> wh.neighbors[21] [16, 20, 22] >>> """ if nrows == 1 or ncols == 1: print "Hexagon lattice requires at least 2 rows and columns" print "Returning a linear contiguity structure" return lat2W(nrows, ncols) n = nrows * ncols rid = [i / ncols for i in xrange(n)] cid = [i % ncols for i in xrange(n)] r1 = nrows - 1 c1 = ncols - 1 w = lat2W(nrows, ncols).neighbors for i in xrange(n): odd = cid[i] % 2 if odd: if rid[i] < r1: # odd col index above last row # new sw neighbor if cid[i] > 0: j = i + ncols - 1 w[i] = w.get(i, []) + [j] # new se neighbor if cid[i] < c1: j = i + ncols + 1 w[i] = w.get(i, []) + [j] else: # even col # nw jnw = [i - ncols - 1] # ne jne = [i - ncols + 1] if rid[i] > 0: w[i] if cid[i] == 0: w[i] = w.get(i, []) + jne elif cid[i] == c1: w[i] = w.get(i, []) + jnw else: w[i] = w.get(i, []) + jne w[i] = w.get(i, []) + jnw return pysal.weights.W(w) def lat2W(nrows=5, ncols=5, rook=True, id_type='int'): """ Create a W object for a regular lattice. Parameters ---------- nrows : int number of rows ncols : int number of columns rook : boolean type of contiguity. Default is rook. For queen, rook =False id_type : string string defining the type of IDs to use in the final W object; options are 'int' (0, 1, 2 ...; default), 'float' (0.0, 1.0, 2.0, ...) and 'string' ('id0', 'id1', 'id2', ...) Returns ------- w : W instance of spatial weights class W Notes ----- Observations are row ordered: first k observations are in row 0, next k in row 1, and so on. Examples -------- >>> from pysal import lat2W >>> w9 = lat2W(3,3) >>> "%.3f"%w9.pct_nonzero '0.296' >>> w9[0] {1: 1.0, 3: 1.0} >>> w9[3] {0: 1.0, 4: 1.0, 6: 1.0} >>> """ n = nrows * ncols r1 = nrows - 1 c1 = ncols - 1 rid = [i / ncols for i in xrange(n)] cid = [i % ncols for i in xrange(n)] w = {} r = below = 0 for i in xrange(n - 1): if rid[i] < r1: below = rid[i] + 1 r = below * ncols + cid[i] w[i] = w.get(i, []) + [r] w[r] = w.get(r, []) + [i] if cid[i] < c1: right = cid[i] + 1 c = rid[i] * ncols + right w[i] = w.get(i, []) + [c] w[c] = w.get(c, []) + [i] if not rook: # southeast bishop if cid[i] < c1 and rid[i] < r1: r = (rid[i] + 1) * ncols + 1 + cid[i] w[i] = w.get(i, []) + [r] w[r] = w.get(r, []) + [i] # southwest bishop if cid[i] > 0 and rid[i] < r1: r = (rid[i] + 1) * ncols - 1 + cid[i] w[i] = w.get(i, []) + [r] w[r] = w.get(r, []) + [i] neighbors = {} weights = {} for key in w: weights[key] = [1.] * len(w[key]) ids = range(n) if id_type == 'string': ids = ['id' + str(i) for i in ids] elif id_type == 'float': ids = [i * 1. for i in ids] if id_type == 'string' or id_type == 'float': id_dict = dict(zip(range(n), ids)) alt_w = {} alt_weights = {} for i in w: values = [id_dict[j] for j in w[i]] key = id_dict[i] alt_w[key] = values alt_weights[key] = weights[i] w = alt_w weights = alt_weights return pysal.weights.W(w, weights, ids=ids, id_order=ids[:]) def regime_weights(regimes): """ Construct spatial weights for regime neighbors. Block contiguity structures are relevant when defining neighbor relations based on membership in a regime. For example, all counties belonging to the same state could be defined as neighbors, in an analysis of all counties in the US. Parameters ---------- regimes : list or array ids of which regime an observation belongs to Returns ------- W : spatial weights instance Examples -------- >>> from pysal import regime_weights >>> import numpy as np >>> regimes = np.ones(25) >>> regimes[range(10,20)] = 2 >>> regimes[range(21,25)] = 3 >>> regimes array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 3., 3., 3., 3.]) >>> w = regime_weights(regimes) PendingDepricationWarning: regime_weights will be renamed to block_weights in PySAL 2.0 >>> w.weights[0] [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] >>> w.neighbors[0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] >>> regimes = ['n','n','s','s','e','e','w','w','e'] >>> n = len(regimes) >>> w = regime_weights(regimes) PendingDepricationWarning: regime_weights will be renamed to block_weights in PySAL 2.0 >>> w.neighbors {0: [1], 1: [0], 2: [3], 3: [2], 4: [5, 8], 5: [4, 8], 6: [7], 7: [6], 8: [4, 5]} Notes ----- regime_weights will be deprecated in PySAL 2.0 and renamed to block_weights. """ msg = "PendingDepricationWarning: regime_weights will be " msg += "renamed to block_weights in PySAL 2.0" print msg return block_weights(regimes) def block_weights(regimes): """ Construct spatial weights for regime neighbors. Block contiguity structures are relevant when defining neighbor relations based on membership in a regime. For example, all counties belonging to the same state could be defined as neighbors, in an analysis of all counties in the US. Parameters ---------- regimes : list or array ids of which regime an observation belongs to Returns ------- W : spatial weights instance Examples -------- >>> from pysal import block_weights >>> import numpy as np >>> regimes = np.ones(25) >>> regimes[range(10,20)] = 2 >>> regimes[range(21,25)] = 3 >>> regimes array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 3., 3., 3., 3.]) >>> w = block_weights(regimes) >>> w.weights[0] [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] >>> w.neighbors[0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 20] >>> regimes = ['n','n','s','s','e','e','w','w','e'] >>> n = len(regimes) >>> w = block_weights(regimes) >>> w.neighbors {0: [1], 1: [0], 2: [3], 3: [2], 4: [5, 8], 5: [4, 8], 6: [7], 7: [6], 8: [4, 5]} """ rids = np.unique(regimes) neighbors = {} NPNZ = np.nonzero regimes = np.array(regimes) for rid in rids: members = NPNZ(regimes == rid)[0] for member in members: neighbors[member] = members[NPNZ(members != member)[0]].tolist() return pysal.weights.W(neighbors) def comb(items, n=None): """ Combinations of size n taken from items Parameters ---------- items : sequence n : integer size of combinations to take from items Returns ------- implicit : generator combinations of size n taken from items Examples -------- >>> x = range(4) >>> for c in comb(x, 2): ... print c ... [0, 1] [0, 2] [0, 3] [1, 2] [1, 3] [2, 3] """ if n is None: n = len(items) for i in range(len(items)): v = items[i:i + 1] if n == 1: yield v else: rest = items[i + 1:] for c in comb(rest, n - 1): yield v + c def order(w, kmax=3): """ Determine the non-redundant order of contiguity up to a specific order. Parameters ---------- w : W spatial weights object kmax : int maximum order of contiguity Returns ------- info : dictionary observation id is the key, value is a list of contiguity orders with a negative 1 in the ith position Notes ----- Implements the algorithm in Anselin and Smirnov (1996) [1]_ Examples -------- >>> from pysal import rook_from_shapefile as rfs >>> w = rfs(pysal.examples.get_path('10740.shp')) WARNING: there is one disconnected observation (no neighbors) Island id: [163] >>> w3 = order(w, kmax = 3) >>> w3[1][0:5] [1, -1, 1, 2, 1] """ #ids = w.neighbors.keys() ids = w.id_order info = {} for id_ in ids: s = [0] * w.n s[ids.index(id_)] = -1 for j in w.neighbors[id_]: s[ids.index(j)] = 1 k = 1 while k < kmax: knext = k + 1 if s.count(k): # get neighbors of order k js = [ids[j] for j, val in enumerate(s) if val == k] # get first order neighbors for order k neighbors for j in js: next_neighbors = w.neighbors[j] for neighbor in next_neighbors: nid = ids.index(neighbor) if s[nid] == 0: s[nid] = knext k = knext info[id_] = s return info def higher_order(w, k=2): """ Contiguity weights object of order k Parameters ---------- w : W spatial weights object k : int order of contiguity Returns ------- implicit : W spatial weights object Notes ----- Proper higher order neighbors are returned such that i and j are k-order neighbors iff the shortest path from i-j is of length k. Examples -------- >>> from pysal import lat2W, higher_order >>> w10 = lat2W(10, 10) >>> w10_2 = higher_order(w10, 2) >>> w10_2[0] {2: 1.0, 11: 1.0, 20: 1.0} >>> w5 = lat2W() >>> w5[0] {1: 1.0, 5: 1.0} >>> w5[1] {0: 1.0, 2: 1.0, 6: 1.0} >>> w5_2 = higher_order(w5,2) >>> w5_2[0] {10: 1.0, 2: 1.0, 6: 1.0} """ return higher_order_sp(w, k) def higher_order_sp(w, k=2, shortest_path=True, diagonal=False): """ Contiguity weights for either a sparse W or pysal.weights.W for order k Parameters ========== w: [W instance | scipy.sparse.csr.csr_instance] k: Order of contiguity shortest_path: Boolean True: i,j and k-order neighbors if the shortest path for i,j is k False: i,j are k-order neighbors if there is a path from i,j of length k diagonal: Boolean False: remove k-order (i,j) joins when i==j True: keep k-order (i,j) joins when i==j Returns ------- wk: [W instance | WSP instance] type matches type of w argument Notes ----- Lower order contiguities are removed. Examples -------- >>> import pysal >>> w25 = pysal.lat2W(5,5) >>> w25.n 25 >>> w25[0] {1: 1.0, 5: 1.0} >>> w25_2 = pysal.weights.util.higher_order_sp(w25, 2) >>> w25_2[0] {10: 1.0, 2: 1.0, 6: 1.0} >>> w25_2 = pysal.weights.util.higher_order_sp(w25, 2, diagonal=True) >>> w25_2[0] {0: 1.0, 10: 1.0, 2: 1.0, 6: 1.0} >>> w25_3 = pysal.weights.util.higher_order_sp(w25, 3) >>> w25_3[0] {15: 1.0, 3: 1.0, 11: 1.0, 7: 1.0} >>> w25_3 = pysal.weights.util.higher_order_sp(w25, 3, shortest_path=False) >>> w25_3[0] {1: 1.0, 3: 1.0, 5: 1.0, 7: 1.0, 11: 1.0, 15: 1.0} """ tw = type(w) id_order = None if tw == pysal.weights.weights.W: id_order = w.id_order w = w.sparse elif tw != scipy.sparse.csr.csr_matrix: print "Unsupported sparse argument." return None wk = w**k rk, ck = wk.nonzero() sk = set(zip(rk, ck)) if shortest_path: for j in range(1, k): wj = w**j rj, cj = wj.nonzero() sj = set(zip(rj, cj)) sk.difference_update(sj) if not diagonal: sk = set([(i,j) for i,j in sk if i!=j]) if id_order: d = dict([(i,[]) for i in id_order]) for pair in sk: k, v = pair k = id_order[k] v = id_order[v] d[k].append(v) return pysal.W(neighbors=d) else: d = {} for pair in sk: k, v = pair if k in d: d[k].append(v) else: d[k] = [v] return pysal.weights.WSP(pysal.W(neighbors=d).sparse) def w_local_cluster(w): """ Local clustering coefficients for each unit as a node in a graph. [ws]_ Parameters ---------- w : W spatial weights object Returns ------- c : array (w.n,1) local clustering coefficients Notes ----- The local clustering coefficient :math:`c_i` quantifies how close the neighbors of observation :math:`i` are to being a clique: .. math:: c_i = | \{w_{j,k}\} |/ (k_i(k_i - 1)): j,k \in N_i where :math:`N_i` is the set of neighbors to :math:`i`, :math:`k_i = |N_i|` and :math:`\{w_{j,k}\}` is the set of non-zero elements of the weights between pairs in :math:`N_i`. References ---------- .. [ws] Watts, D.J. and S.H. Strogatz (1988) "Collective dynamics of 'small-world' networks". Nature, 393: 440-442. Examples -------- >>> w = pysal.lat2W(3,3, rook=False) >>> w_local_cluster(w) array([[ 1. ], [ 0.6 ], [ 1. ], [ 0.6 ], [ 0.42857143], [ 0.6 ], [ 1. ], [ 0.6 ], [ 1. ]]) """ c = np.zeros((w.n, 1), float) w.transformation = 'b' for i, id in enumerate(w.id_order): ki = max(w.cardinalities[id], 1) # deal with islands Ni = w.neighbors[id] wi = pysal.w_subset(w, Ni).full()[0] c[i] = wi.sum() / (ki * (ki - 1)) return c def shimbel(w): """ Find the Shimbel matrix for first order contiguity matrix. Parameters ---------- w : W spatial weights object Returns ------- info : list of lists one list for each observation which stores the shortest order between it and each of the the other observations. Examples -------- >>> from pysal import lat2W, shimbel >>> w5 = lat2W() >>> w5_shimbel = shimbel(w5) >>> w5_shimbel[0][24] 8 >>> w5_shimbel[0][0:4] [-1, 1, 2, 3] >>> """ info = {} ids = w.id_order for id in ids: s = [0] * w.n s[ids.index(id)] = -1 for j in w.neighbors[id]: s[ids.index(j)] = 1 k = 1 flag = s.count(0) while flag: p = -1 knext = k + 1 for j in range(s.count(k)): neighbor = s.index(k, p + 1) p = neighbor next_neighbors = w.neighbors[ids[p]] for neighbor in next_neighbors: nid = ids.index(neighbor) if s[nid] == 0: s[nid] = knext k = knext flag = s.count(0) info[id] = s return info def full(w): """ Generate a full numpy array Parameters ---------- w : W spatial weights object Returns ------- implicit : tuple first element being the full numpy array and second element keys being the ids associated with each row in the array. Examples -------- >>> from pysal import W, full >>> neighbors = {'first':['second'],'second':['first','third'],'third':['second']} >>> weights = {'first':[1],'second':[1,1],'third':[1]} >>> w = W(neighbors, weights) >>> wf, ids = full(w) >>> wf array([[ 0., 1., 0.], [ 1., 0., 1.], [ 0., 1., 0.]]) >>> ids ['first', 'second', 'third'] """ wfull = np.zeros([w.n, w.n], dtype=float) keys = w.neighbors.keys() if w.id_order: keys = w.id_order for i, key in enumerate(keys): n_i = w.neighbors[key] w_i = w.weights[key] for j, wij in zip(n_i, w_i): c = keys.index(j) wfull[i, c] = wij return (wfull, keys) def full2W(m, ids=None): ''' Create a PySAL W object from a full array ... Parameters ---------- m : array nxn array with the full weights matrix ids : list User ids assumed to be aligned with m Returns ------- w : W PySAL weights object Examples -------- >>> import pysal as ps >>> import numpy as np Create an array of zeros >>> a = np.zeros((4, 4)) For loop to fill it with random numbers >>> for i in range(len(a)): ... for j in range(len(a[i])): ... if i!=j: ... a[i, j] = np.random.random(1) Create W object >>> w = ps.weights.util.full2W(a) >>> w.full()[0] == a array([[ True, True, True, True], [ True, True, True, True], [ True, True, True, True], [ True, True, True, True]], dtype=bool) Create list of user ids >>> ids = ['myID0', 'myID1', 'myID2', 'myID3'] >>> w = ps.weights.util.full2W(a, ids=ids) >>> w.full()[0] == a array([[ True, True, True, True], [ True, True, True, True], [ True, True, True, True], [ True, True, True, True]], dtype=bool) ''' if m.shape[0] != m.shape[1]: raise ValueError('Your array is not square') neighbors, weights = {}, {} for i in xrange(m.shape[0]): # for i, row in enumerate(m): row = m[i] if ids: i = ids[i] ngh = list(row.nonzero()[0]) weights[i] = list(row[ngh]) ngh = list(ngh) if ids: ngh = [ids[j] for j in ngh] neighbors[i] = ngh return pysal.W(neighbors, weights, id_order=ids) def WSP2W(wsp, silent_island_warning=False): """ Convert a pysal WSP object (thin weights matrix) to a pysal W object. Parameters ---------- wsp : WSP PySAL sparse weights object silent_island_warning : boolean Switch to turn off (default on) print statements for every observation with islands Returns ------- w : W PySAL weights object Examples -------- >>> import pysal Build a 10x10 scipy.sparse matrix for a rectangular 2x5 region of cells (rook contiguity), then construct a PySAL sparse weights object (wsp). >>> sp = pysal.weights.lat2SW(2, 5) >>> wsp = pysal.weights.WSP(sp) >>> wsp.n 10 >>> print wsp.sparse[0].todense() [[0 1 0 0 0 1 0 0 0 0]] Convert this sparse weights object to a standard PySAL weights object. >>> w = pysal.weights.WSP2W(wsp) >>> w.n 10 >>> print w.full()[0][0] [ 0. 1. 0. 0. 0. 1. 0. 0. 0. 0.] """ wsp.sparse indices = wsp.sparse.indices data = wsp.sparse.data indptr = wsp.sparse.indptr id_order = wsp.id_order if id_order: # replace indices with user IDs indices = [id_order[i] for i in indices] else: id_order = range(wsp.n) neighbors, weights = {}, {} start = indptr[0] for i in xrange(wsp.n): oid = id_order[i] end = indptr[i + 1] neighbors[oid] = indices[start:end] weights[oid] = data[start:end] start = end ids = copy.copy(wsp.id_order) w = pysal.W(neighbors, weights, ids, silent_island_warning=silent_island_warning) w._sparse = copy.deepcopy(wsp.sparse) w._cache['sparse'] = w._sparse return w def insert_diagonal(w, diagonal=1.0, wsp=False): """ Returns a new weights object with values inserted along the main diagonal. Parameters ---------- w : W Spatial weights object diagonal : float, int or array Defines the value(s) to which the weights matrix diagonal should be set. If a constant is passed then each element along the diagonal will get this value (default is 1.0). An array of length w.n can be passed to set explicit values to each element along the diagonal (assumed to be in the same order as w.id_order). wsp : boolean If True return a thin weights object of the type WSP, if False return the standard W object. Returns ------- w : W Spatial weights object Examples -------- >>> import pysal >>> import numpy as np Build a basic rook weights matrix, which has zeros on the diagonal, then insert ones along the diagonal. >>> w = pysal.lat2W(5, 5, id_type='string') >>> w_const = pysal.weights.insert_diagonal(w) >>> w['id0'] {'id5': 1.0, 'id1': 1.0} >>> w_const['id0'] {'id5': 1.0, 'id0': 1.0, 'id1': 1.0} Insert different values along the main diagonal. >>> diag = np.arange(100, 125) >>> w_var = pysal.weights.insert_diagonal(w, diag) >>> w_var['id0'] {'id5': 1.0, 'id0': 100.0, 'id1': 1.0} """ w_new = copy.deepcopy(w.sparse) w_new = w_new.tolil() if issubclass(type(diagonal), np.ndarray): if w.n != diagonal.shape[0]: raise Exception("shape of w and diagonal do not match") w_new.setdiag(diagonal) elif operator.isNumberType(diagonal): w_new.setdiag([diagonal] * w.n) else: raise Exception("Invalid value passed to diagonal") w_out = pysal.weights.WSP(w_new, copy.copy(w.id_order)) if wsp: return w_out else: return WSP2W(w_out) def remap_ids(w, old2new, id_order=[]): """ Remaps the IDs in a spatial weights object Parameters ---------- w : W Spatial weights object old2new : dictionary Dictionary where the keys are the IDs in w (i.e. "old IDs") and the values are the IDs to replace them (i.e. "new IDs") id_order : list An ordered list of new IDs, which defines the order of observations when iterating over W. If not set then the id_order in w will be used. Returns ------- implicit : W Spatial weights object with new IDs Examples -------- >>> from pysal import lat2W, remap_ids >>> w = lat2W(3,2) >>> w.id_order [0, 1, 2, 3, 4, 5] >>> w.neighbors[0] [2, 1] >>> old_to_new = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'} >>> w_new = remap_ids(w, old_to_new) >>> w_new.id_order ['a', 'b', 'c', 'd', 'e', 'f'] >>> w_new.neighbors['a'] ['c', 'b'] """ if not isinstance(w, pysal.weights.W): raise Exception("w must be a spatial weights object") new_neigh = {} new_weights = {} for key, value in w.neighbors.iteritems(): new_values = [old2new[i] for i in value] new_key = old2new[key] new_neigh[new_key] = new_values new_weights[new_key] = copy.copy(w.weights[key]) if id_order: return pysal.weights.W(new_neigh, new_weights, id_order) else: if w.id_order: id_order = [old2new[i] for i in w.id_order] return pysal.weights.W(new_neigh, new_weights, id_order) else: return pysal.weights.W(new_neigh, new_weights) def get_ids(shapefile, idVariable): """ Gets the IDs from the DBF file that moves with a given shape file Parameters ---------- shapefile : string name of a shape file including suffix idVariable : string name of a column in the shapefile's DBF to use for ids Returns ------- ids : list a list of IDs Examples -------- >>> from pysal.weights.util import get_ids >>> polyids = get_ids(pysal.examples.get_path("columbus.shp"), "POLYID") >>> polyids[:5] [1, 2, 3, 4, 5] """ try: dbname = os.path.splitext(shapefile)[0] + '.dbf' db = pysal.open(dbname) var = db.by_col[idVariable] db.close() return var except IOError: msg = 'The shapefile "%s" appears to be missing its DBF file. The DBF file "%s" could not be found.' % ( shapefile, dbname) raise IOError(msg) except AttributeError: msg = 'The variable "%s" was not found in the DBF file. The DBF contains the following variables: %s.' % ( idVariable, ','.join(db.header)) raise KeyError(msg) def get_points_array_from_shapefile(shapefile): """ Gets a data array of x and y coordinates from a given shape file Parameters ---------- shapefile : string name of a shape file including suffix Returns ------- points : array (n, 2) a data array of x and y coordinates Notes ----- If the given shape file includes polygons, this function returns x and y coordinates of the polygons' centroids Examples -------- Point shapefile >>> from pysal.weights.util import get_points_array_from_shapefile >>> xy = get_points_array_from_shapefile(pysal.examples.get_path('juvenile.shp')) >>> xy[:3] array([[ 94., 93.], [ 80., 95.], [ 79., 90.]]) Polygon shapefile >>> xy = get_points_array_from_shapefile(pysal.examples.get_path('columbus.shp')) >>> xy[:3] array([[ 8.82721847, 14.36907602], [ 8.33265837, 14.03162401], [ 9.01226541, 13.81971908]]) """ f = pysal.open(shapefile) if f.type.__name__ == 'Polygon': data = np.array([shape.centroid for shape in f]) elif f.type.__name__ == 'Point': data = np.array([shape for shape in f]) f.close() return data def min_threshold_distance(data, p=2): """ Get the maximum nearest neighbor distance Parameters ---------- data : array (n,k) or KDTree where KDtree.data is array (n,k) n observations on k attributes p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance Returns ------- nnd : float maximum nearest neighbor distance between the n observations Examples -------- >>> from pysal.weights.util import min_threshold_distance >>> import numpy as np >>> x, y = np.indices((5, 5)) >>> x.shape = (25, 1) >>> y.shape = (25, 1) >>> data = np.hstack([x, y]) >>> min_threshold_distance(data) 1.0 """ if issubclass(type(data), scipy.spatial.KDTree): kd = data data = kd.data else: kd = KDTree(data) nn = kd.query(data, k=2, p=p) nnd = nn[0].max(axis=0)[1] return nnd def lat2SW(nrows=3, ncols=5, criterion="rook", row_st=False): """ Create a sparse W matrix for a regular lattice. Parameters ---------- nrows : int number of rows ncols : int number of columns rook : "rook", "queen", or "bishop" type of contiguity. Default is rook. row_st : boolean If True, the created sparse W object is row-standardized so every row sums up to one. Defaults to False. Returns ------- w : scipy.sparse.dia_matrix instance of a scipy sparse matrix Notes ----- Observations are row ordered: first k observations are in row 0, next k in row 1, and so on. This method directly creates the W matrix using the strucuture of the contiguity type. Examples -------- >>> from pysal import weights >>> w9 = weights.lat2SW(3,3) >>> w9[0,1] 1 >>> w9[3,6] 1 >>> w9r = weights.lat2SW(3,3, row_st=True) >>> w9r[3,6] 0.33333333333333331 """ n = nrows * ncols diagonals = [] offsets = [] if criterion == "rook" or criterion == "queen": d = np.ones((1, n)) for i in range(ncols - 1, n, ncols): d[0, i] = 0 diagonals.append(d) offsets.append(-1) d = np.ones((1, n)) diagonals.append(d) offsets.append(-ncols) if criterion == "queen" or criterion == "bishop": d = np.ones((1, n)) for i in range(0, n, ncols): d[0, i] = 0 diagonals.append(d) offsets.append(-(ncols - 1)) d = np.ones((1, n)) for i in range(ncols - 1, n, ncols): d[0, i] = 0 diagonals.append(d) offsets.append(-(ncols + 1)) data = np.concatenate(diagonals) offsets = np.array(offsets) m = sparse.dia_matrix((data, offsets), shape=(n, n), dtype=np.int8) m = m + m.T if row_st: m = sparse.spdiags(1. / m.sum(1).T, 0, *m.shape) * m return m def write_gal(file, k=10): f = open(file, 'w') n = k * k f.write("0 %d" % n) for i in xrange(n): row = i / k col = i % k neighs = [i - i, i + 1, i - k, i + k] neighs = [j for j in neighs if j >= 0 and j < n] f.write("\n%d %d\n" % (i, len(neighs))) f.write(" ".join(map(str, neighs))) f.close() if __name__ == "__main__": from pysal import lat2W assert (lat2W(5, 5).sparse.todense() == lat2SW(5, 5).todense()).all() assert (lat2W(5, 3).sparse.todense() == lat2SW(5, 3).todense()).all() assert (lat2W(5, 3, rook=False).sparse.todense() == lat2SW(5, 3, 'queen').todense()).all() assert (lat2W(50, 50, rook=False).sparse.todense() == lat2SW(50, 50, 'queen').todense()).all()
volaya/processing_pysal
ext-libs/pysal/weights/util.py
Python
gpl-2.0
31,890
[ "COLUMBUS" ]
5cbb737c1dedfd8015b7a1d224eaba7f3225822a3f5eafc8f76e346ca2abf6ad
"""Routines for manipulating restart files""" from __future__ import print_function from __future__ import division try: from builtins import str from builtins import range except: pass try: from boututils.datafile import DataFile except ImportError: raise ImportError("ERROR: restart module needs DataFile") import multiprocessing import numpy as np from numpy import mean, zeros, arange from math import sqrt from numpy.random import normal from scipy.interpolate import interp1d try: from scipy.interpolate import RegularGridInterpolator except: pass try: import os import sys import glob except ImportError: raise ImportError("ERROR: os, sys or glob modules not available") def split(nxpe, nype, path="data", output="./", informat="nc", outformat=None): """Split restart files across NXPE x NYPE processors. Returns True on success """ if outformat == None: outformat = informat mxg = 2 myg = 2 npes = nxpe * nype if npes <= 0: print("ERROR: Negative or zero number of processors") return False if path == output: print("ERROR: Can't overwrite restart files") return False file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat)) nfiles = len(file_list) if nfiles == 0: print("ERROR: No restart files found") return False # Read old processor layout f = DataFile(os.path.join(path, file_list[0])) # Get list of variables var_list = f.list() if len(var_list) == 0: print("ERROR: No data found") return False old_npes = f.read('NPES') old_nxpe = f.read('NXPE') if nfiles != old_npes: print("WARNING: Number of restart files inconsistent with NPES") print("Setting nfiles = " + str(old_npes)) nfiles = old_npes if old_npes % old_nxpe != 0: print("ERROR: Old NPES is not a multiple of old NXPE") return False old_nype =int(old_npes/old_nxpe) if nype % old_nype != 0: print("SORRY: New nype must be a multiple of old nype") return False if nxpe % old_nxpe != 0: print("SORRY: New nxpe must be a multiple of old nxpe") return False # Get dimension sizes old_mxsub = 0 old_mysub = 0 mz = 0 for v in var_list: if f.ndims(v) == 3: s = f.size(v) old_mxsub = s[0] - 2*mxg old_mysub = s[1] - 2*myg mz = s[2] break f.close() # Calculate total size of the grid nx = old_mxsub * old_nxpe ny = old_mysub * old_nype print(("Grid sizes: ", nx, ny, mz)) # Create the new restart files for mype in range(npes): # Calculate X and Y processor numbers pex = mype % nxpe pey = int(mype/ nxpe) old_pex = int(pex / xs) old_pey = int(pey / ys) old_x = pex % xs old_y = pey % ys # Old restart file number old_mype = old_nxpe * old_pey + old_pex # Calculate indices in old restart file xmin = old_x*mxsub xmax = xmin + mxsub - 1 + 2*mxg ymin = old_y*mysub ymax = ymin + mysub - 1 + 2*myg print("New: "+str(mype)+" ("+str(pex)+", "+str(pey)+")") print(" => "+str(old_mype)+" ("+str(old_pex)+", "+str(old_pey)+") : ("+str(old_x)+", "+str(old_y)+")") # def resize3DField(var, data, coordsAndSizesTuple, method, mute): """ Resizing of the 3D fields. To be called by resize. Written as a function in order to call it using multiprocesse. Must be defined as a top level function in order to be pickable by the multiprocess. See the function resize for details. """ # Unpack the tuple for better readability xCoordOld, yCoordOld, zCoordOld,\ xCoordNew, yCoordNew, zCoordNew,\ newNx, newNy, newNz = coordsAndSizesTuple if not(mute): print(" Resizing "+var) # Make the regular grid function (see examples in # http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html # for details) gridInterpolator = RegularGridInterpolator((xCoordOld, yCoordOld, zCoordOld), data, method) # Need to fill with one exrta z plane (will only contain zeros) newData = np.zeros((newNx, newNy, newNz+1)) # Interpolate to the new values for xInd, x in enumerate(xCoordNew): for yInd, y in enumerate(yCoordNew): for zInd, z in enumerate(zCoordNew): newData[xInd, yInd, zInd] = gridInterpolator([x, y, z]) return var, newData def resize(newNx, newNy, newNz, mxg=2, myg=2,\ path="data", output="./", informat="nc", outformat=None,\ method='linear', maxProc=None, mute=False): """ Increase/decrease the number of points in restart files. NOTE: Can't overwrite WARNING: Currently only implemented with uniform BOUT++ grid Parameters ----- newNx : int nx for the new file (including ghost points) newNy : int ny for the new file (including ghost points) newNz : int nz for the new file (including last unused z-plane) mxg : int Number of ghost points in x. **NOTE:** Default is 2 myg : int Number of ghost points in y. **NOTE:** Default is 2 path : str Input path output : str Output path informat : str File extension of input outformat : [None|str] File extension of output method : ['linear'|'nearest'] What interpolation method to be used maxProc: [None|int] Limits maximum processors to use when interpolating if set mute : [True|False] Whether or not output should be printed from this function Returns ------- return : [True|False] True on success, else False Todo ---- Add 2D field interpolation """ if method is None: # Make sure the method is set method = 'linear' if outformat == None: outformat = informat if path == output: print("ERROR: Can't overwrite restart files when expanding") return False def is_pow2(x): """Returns true if x is a power of 2""" return (x > 0) and ((x & (x-1)) == 0) if not is_pow2(newNz-1): print("ERROR: New Z size must be a power of 2 + 1") return False # The above statement is a lie, but ensures that z is a power of # 2+1, so that we can safely newNz -= 1 file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat)) file_list.sort() nfiles = len(file_list) if nfiles == 0: print("ERROR: No data found in {}".format(path)) return False if not(mute): print("Number of files found: " + str(nfiles)) for f in file_list: new_f = os.path.join(output, f.split('/')[-1]) if not(mute): print("Changing {} => {}".format(f, new_f)) # Open the restart file in read mode and create the new file with DataFile(f) as old,\ DataFile(new_f, write=True, create=True) as new: # Find the dimension for var in old.list(): # Read the data data = old.read(var) # Find 3D variables if old.ndims(var) == 3: break # Last nz plane is not in use data = data[:,:,:-1] nx, ny, nz = data.shape # Make coordinates # NOTE: The max min of the coordinates are irrelevant when # interpolating (as long as old and new coordinates # are consistent), so we just choose all variable to # be between 0 and 1 Calculate the old coordinates xCoordOld = np.linspace(0, 1, nx) yCoordOld = np.linspace(0, 1, ny) zCoordOld = np.linspace(0, 1, nz) # Calculate the new coordinates xCoordNew = np.linspace(xCoordOld[0], xCoordOld[-1], newNx) yCoordNew = np.linspace(yCoordOld[0], yCoordOld[-1], newNy) zCoordNew = np.linspace(zCoordOld[0], zCoordOld[-1], newNz) # Make a pool of workers pool = multiprocessing.Pool(maxProc) # List of jobs and results jobs = [] # Pack input to resize3DField together coordsAndSizesTuple = (xCoordOld, yCoordOld, zCoordOld,\ xCoordNew, yCoordNew, zCoordNew,\ newNx, newNy, newNz) # Loop over the variables in the old file for var in old.list(): # Read the data data = old.read(var) # Find 3D variables if old.ndims(var) == 3: # Last nz plane is not in use data = data[:,:,:-1] # Asynchronous call (locks first at .get()) jobs.append(pool.apply_async(resize3DField,\ (var, data, coordsAndSizesTuple, method, mute)\ )) else: if not(mute): print(" Copying "+var) newData = data.copy() if not(mute): print("Writing "+var) new.write(var, newData) for job in jobs: var, newData = job.get() if not(mute): print("Writing "+var) new.write(var, newData) # Close the pool of workers pool.close() # Wait for all processes to finish pool.join() return True def expand(newz, path="data", output="./", informat="nc", outformat=None): """ Increase the number of Z points in restart files. The python equivalent of ../../idllib/expand_restarts.pro NOTE: * Can't overwrite * Will not yield a result close to the original if there are aymmetires in the z-direction Input ----- path Input path output Output path informat File extension of input outformat File extension of output Returns ------- True on success, else False """ if outformat == None: outformat = informat if path == output: print("ERROR: Can't overwrite restart files when expanding") return False def is_pow2(x): """Returns true if x is a power of 2""" return (x > 0) and ((x & (x-1)) == 0) if not is_pow2(newz-1): print("ERROR: New Z size must be a power of 2 + 1") return False file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat)) file_list.sort() nfiles = len(file_list) if nfiles == 0: print("ERROR: No data found") return False print("Number of files found: " + str(nfiles)) for f in file_list: new_f = os.path.join(output, f.split('/')[-1]) print("Changing {} => {}".format(f, new_f)) # Open the restart file in read mode and create the new file with DataFile(f) as old,\ DataFile(new_f, write=True, create=True) as new: # Loop over the variables in the old file for var in old.list(): # Read the data data = old.read(var) # Find 3D variables if old.ndims(var) == 3: print(" Resizing "+var) nx, ny, nz = data.shape newdata = np.zeros((nx, ny, newz)) for x in range(nx): for y in range(ny): f_old = np.fft.fft(data[x, y, 0:(nz-1)]) # Number of points in f is power of 2 f_new = np.zeros(newz - 1) # Copy coefficients across (ignoring Nyquist) f_new[0] = f_old[0] # DC for m in range(1, int((nz-1)/2)): # + ve frequencies f_new[m] = f_old[m] # - ve frequencies f_new[newz-1-m] = f_old[nz-1-m] # Invert fft newdata[x,y,0:(newz-1)] = np.fft.ifft(f_new).real newdata[x,y,newz-1] = newdata[x,y,0] # Multiply with the ratio of newz/nz # This is not needed in the IDL routine as the # forward transfrom has the scaling factor 1/N in # the forward transform, whereas the scaling factor # 1/N is the inverse transform in np.fft # Note that ifft(fft(a)) = a for the same number of # points in both IDL and np.ftt newdata *= ((newz-1)/(nz-1)) else: print(" Copying "+var) newdata = data.copy() new.write(var, newdata) return True def addnoise(path=".", var=None, scale=1e-5): """ Add random noise to restart files Inputs ------ path Path to the restart files var The variable to modify. By default all 3D variables are modified scale Amplitude of the noise. Gaussian noise is used, with zero mean and this parameter as the standard deviation Returns ------- None """ file_list = glob.glob(os.path.join(path, "BOUT.restart.*")) nfiles = len(file_list) print("Number of restart files: %d" % (nfiles,)) for file in file_list: print(file) with DataFile(file, write=True) as d: if var == None: for v in d.list(): if d.ndims(v) == 3: print(" -> "+v) data = d.read(v) data += normal(scale=scale, size=data.shape) d.write(v, data) else: # Modify a single variable print(" -> "+var) data = d.read(var) data += normal(scale=scale, size=data.shape) d.write(var, data) def scalevar(var, factor, path="."): """ Scales a variable by a given factor, modifying restart files in place Inputs ------ var Name of the variable (string) factor Factor to multiply (float) path Path to the restart files Returns ------- None """ file_list = glob.glob(os.path.join(path, "BOUT.restart.*")) nfiles = len(file_list) print("Number of restart files: %d" % (nfiles,)) for file in file_list: print(file) with DataFile(file, write=True) as d: d[var] = d[var] * factor def create(averagelast=1, final=-1, path="data", output="./", informat="nc", outformat=None): """ Create restart files from data (dmp) files. Inputs ====== averagelast Number of time points to average over. Default is 1 i.e. just take last time-point final The last time point to use. Default is last (-1) path Path to the input data files output Path where the output restart files should go informat Format of the input data files outformat Format of the output restart files """ if outformat == None: outformat = informat file_list = glob.glob(os.path.join(path, "BOUT.dmp.*."+informat)) nfiles = len(file_list) print(("Number of data files: ", nfiles)) for i in range(nfiles): # Open each data file infname = os.path.join(path, "BOUT.dmp."+str(i)+"."+informat) outfname = os.path.join(output, "BOUT.restart."+str(i)+"."+outformat) print((infname, " -> ", outfname)) infile = DataFile(infname) outfile = DataFile(outfname, create=True) # Get the data always needed in restart files hist_hi = infile.read("iteration") print(("hist_hi = ", hist_hi)) outfile.write("hist_hi", hist_hi) t_array = infile.read("t_array") tt = t_array[final] print(("tt = ", tt)) outfile.write("tt", tt) tind = final if tind < 0.0: tind = len(t_array) + final NXPE = infile.read("NXPE") NYPE = infile.read("NYPE") NPES = NXPE * NYPE print(("NPES = ", NPES, " NXPE = ", NXPE)) outfile.write("NPES", NPES) outfile.write("NXPE", NXPE) # Get a list of variables varnames = infile.list() for var in varnames: if infile.ndims(var) == 4: # Could be an evolving variable print((" -> ", var)) data = infile.read(var) if averagelast == 1: slice = data[final,:,:,:] else: slice = mean(data[(final - averagelast):final,:,:,:], axis=0) print(slice.shape) outfile.write(var, slice) infile.close() outfile.close() def redistribute(npes, path="data", nxpe=None, output=".", informat=None, outformat=None, mxg=2, myg=2): """Resize restart files across NPES processors. Does not check if new processor arrangement is compatible with the branch cuts. In this respect restart.split is safer. However, BOUT++ checks the topology during initialisation anyway so this is not too serious. Parameters ---------- npes : int number of processors for the new restart files path : string, optional location of old restart files nxpe : int, optional number of processors to use in the x-direction (determines split: npes = nxpe * nype). Default is None which uses the same algorithm as BoutMesh (but without topology information) to determine a suitable value for nxpe. output : string, optional location to save new restart files informat : string, optional specify file format of old restart files (must be a suffix understood by DataFile, e.g. 'nc'). Default uses the format of the first 'BOUT.restart.*' file listed by glob.glob. outformat : string, optional specify file format of new restart files (must be a suffix understood by DataFile, e.g. 'nc'). Default is to use the same as informat. Returns ------- True on success """ if npes <= 0: print("ERROR: Negative or zero number of processors") return False if path == output: print("ERROR: Can't overwrite restart files") return False if informat == None: file_list = glob.glob(os.path.join(path, "BOUT.restart.*")) else: file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat)) nfiles = len(file_list) # Read old processor layout f = DataFile(file_list[0]) # Get list of variables var_list = f.list() if len(var_list) == 0: print("ERROR: No data found") return False old_npes = f.read('NPES') old_nxpe = f.read('NXPE') old_nype = int(old_npes/old_nxpe) if nfiles != old_npes: print("WARNING: Number of restart files inconsistent with NPES") print("Setting nfiles = " + str(old_npes)) nfiles = old_npes if nfiles == 0: print("ERROR: No restart files found") return False informat = file_list[0].split(".")[-1] if outformat == None: outformat = informat old_mxsub = 0 old_mysub = 0 mz = 0 for v in var_list: if f.ndims(v) == 3: s = f.size(v) old_mxsub = s[0] - 2*mxg if old_mxsub < 0: if s[0] == 1: old_mxsub = 1 mxg = 0 elif s[0] == 3: old_mxsub = 1 mxg = 1 else: print("Number of x points is wrong?") return False old_mysub = s[1] - 2*myg if old_mysub < 0: if s[1] == 1: old_mysub = 1 myg = 0 elif s[1] == 3: old_mysub = 1 myg = 1 else: print("Number of y points is wrong?") return False mz = s[2] break # Calculate total size of the grid nx = old_mxsub * old_nxpe ny = old_mysub * old_nype print("Grid sizes: ", nx, ny, mz) if nxpe == None: # Copy algorithm from BoutMesh for selecting nxpe ideal = sqrt(float(nx) * float(npes) / float(ny)) # Results in square domain for i in range(1,npes+1): if npes%i == 0 and nx%i == 0 and int(nx/i) >= mxg and ny%(npes/i) == 0: # Found an acceptable value # Warning: does not check branch cuts! if nxpe==None or abs(ideal - i) < abs(ideal - nxpe): nxpe = i # Keep value nearest to the ideal if nxpe == None: print("ERROR: could not find a valid value for nxpe") return False nype = int(npes/nxpe) outfile_list = [] for i in range(npes): outpath = os.path.join(output, "BOUT.restart."+str(i)+"."+outformat) outfile_list.append(DataFile(outpath, write=True, create=True)) infile_list = [] for i in range(old_npes): inpath = os.path.join(path, "BOUT.restart."+str(i)+"."+outformat) infile_list.append(DataFile(inpath)) old_mxsub = int(nx/old_nxpe) old_mysub = int(ny/old_nype) mxsub = int(nx/nxpe) mysub = int(ny/nype) for v in var_list: ndims = f.ndims(v) #collect data if ndims == 0: #scalar data = f.read(v) elif ndims == 2: data = np.zeros( (nx+2*mxg,ny+2*myg) ) for i in range(old_npes): ix = i%old_nxpe iy = int(i/old_nxpe) ixstart = mxg if ix == 0: ixstart = 0 ixend = -mxg if ix == old_nxpe-1: ixend = 0 iystart = myg if iy == 0: iystart = 0 iyend = -myg if iy == old_nype-1: iyend = 0 data[ix*old_mxsub+ixstart:(ix+1)*old_mxsub+2*mxg+ixend, iy*old_mysub+iystart:(iy+1)*old_mysub+2*myg+iyend] = infile_list[i].read(v)[ixstart:old_mxsub+2*mxg+ixend, iystart:old_mysub+2*myg+iyend] elif ndims == 3: data = np.zeros( (nx+2*mxg,ny+2*myg,mz) ) for i in range(old_npes): ix = i%old_nxpe iy = int(i/old_nxpe) ixstart = mxg if ix == 0: ixstart = 0 ixend = -mxg if ix == old_nxpe-1: ixend = 0 iystart = myg if iy == 0: iystart = 0 iyend = -myg if iy == old_nype-1: iyend = 0 data[ix*old_mxsub+ixstart:(ix+1)*old_mxsub+2*mxg+ixend, iy*old_mysub+iystart:(iy+1)*old_mysub+2*myg+iyend, :] = infile_list[i].read(v)[ixstart:old_mxsub+2*mxg+ixend, iystart:old_mysub+2*myg+iyend, :] else: print("ERROR: variable found with unexpected number of dimensions,",ndims,v) return False # write data for i in range(npes): ix = i%nxpe iy = int(i/nxpe) outfile = outfile_list[i] if v == "NPES": outfile.write(v,npes) elif v == "NXPE": outfile.write(v,nxpe) elif ndims == 0: # scalar outfile.write(v,data) elif ndims == 2: # Field2D outfile.write(v,data[ix*mxsub:(ix+1)*mxsub+2*mxg, iy*mysub:(iy+1)*mysub+2*myg]) elif ndims == 3: # Field3D outfile.write(v,data[ix*mxsub:(ix+1)*mxsub+2*mxg, iy*mysub:(iy+1)*mysub+2*myg, :]) else: print("ERROR: variable found with unexpected number of dimensions,",f.ndims(v)) f.close() for infile in infile_list: infile.close() for outfile in outfile_list: outfile.close() return True def resizeY(newy, path="data", output=".", informat="nc", outformat=None,myg=2): """ Resize all the restart files in Y """ if outformat == None: outformat = informat file_list = glob.glob(os.path.join(path, "BOUT.restart.*."+informat)) nfiles = len(file_list) if nfiles == 0: print("ERROR: No restart files found") return False for i in range(nfiles): # Open each data file infname = os.path.join(path, "BOUT.restart."+str(i)+"."+informat) outfname = os.path.join(output, "BOUT.restart."+str(i)+"."+outformat) print("Processing %s -> %s", infname, outfname) infile = DataFile(infname) outfile = DataFile(outfname, create=True) # Copy basic information for var in ["hist_hi", "NPES", "NXPE", "tt"]: data = infile.read(var) try: # Convert to scalar if necessary data = data[0] except: pass outfile.write(var, data) # Get a list of variables varnames = infile.list() for var in varnames: if infile.ndims(var) == 3: # Could be an evolving variable [x,y,z] print(" -> " + var) # Read variable from input indata = infile.read(var) nx,ny,nz = indata.shape # y coordinate in input and output data iny = (arange(ny) - myg + 0.5) / (ny - 2*myg) outy = (arange(newy) - myg + 0.5) / (newy - 2*myg) outdata = zeros([nx, newy, nz]) for x in range(nx): for z in range(nz): f = interp1d(iny, indata[x,:,z], bounds_error=False, fill_value=0.0) outdata[x,:,z] = f(outy) outfile.write(var, outdata) infile.close() outfile.close()
erikgrinaker/BOUT-dev
tools/pylib/boutdata/restart.py
Python
gpl-3.0
26,712
[ "Gaussian" ]
cc6b90725e8363d4c449311a7ffc6a8082f23c9e225edfb4e7a3bc32743c2421
######################################################################## # $HeadURL$ # File : CSGlobals.py # Author : Ricardo Graciani ######################################################################## """ Some Helper functions to retrieve common location from the CS """ __RCSID__ = "$Id$" #from DIRAC import gConfig def getSetup(): from DIRAC import gConfig return gConfig.getValue( "/DIRAC/Setup", "" ) def getVO( defaultVO = '' ): """ Return VO from configuration """ from DIRAC import gConfig return gConfig.getValue( '/DIRAC/VirtualOrganization', defaultVO ) def getCSExtensions(): """ Return list of extensions registered in the CS They do not include DIRAC """ from DIRAC import gConfig return gConfig.getValue( '/DIRAC/Extensions', [] ) def getInstalledExtensions(): """ Return list of extensions registered in the CS and available in local installation """ import imp extensions = [] for extension in getCSExtensions(): try: if not "DIRAC" in extension: extension = '%sDIRAC' % extension imp.find_module( extension ) extensions.append( extension ) except ImportError: pass extensions.append( 'DIRAC' ) return extensions def skipCACheck(): from DIRAC import gConfig return gConfig.getValue( "/DIRAC/Security/SkipCAChecks", "false" ).lower() in ( "y", "yes", "true" ) def useServerCertificate(): from DIRAC import gConfig return gConfig.getValue( "/DIRAC/Security/UseServerCertificate", "false" ).lower() in ( "y", "yes", "true" )
calancha/DIRAC
ConfigurationSystem/Client/Helpers/CSGlobals.py
Python
gpl-3.0
1,556
[ "DIRAC" ]
8aeb5ec25dfffd4dee9438449f1111edf94eb41cdf9979553f54ecf4ce74d6c9
""" This file is part of the RepeatDesigner package """ import os import sys import tempfile import itertools import random import numpy as np import Bio.pairwise2 import Bio.SeqUtils import Bio.SeqIO import Bio.SeqRecord import modellerlib as mdlib def model_mc_worker(mc_input): """ Simple modelling worker function Parameters ---------- mc_input : list In which we get the input for the MC optimization. design : cls Instance of the design class. beta : float Inverse temperature. len_mc : int length of MC run. """ # parse input print mc_input run, design, beta, len_mc = parse_mc_input(mc_input) pdb = design.name targets = design.targets if type(design).__name__ == 'Repeat': print " I am a repeat protein!" # redirect output by keeping track of sys.stdout nb_stdout = sys.stdout # redirect outputnb_stdout = sys.stdout sys.stdout = open('data/log%g.out'%run, 'w') # generate modeller environment env = mdlib.modeller_main() respos = targets #[x.index for x in mdl.residues] restyp = ["ALA", "ARG", "ASN", "ASP", "CYS", "GLU", "GLN", "GLY", \ "HIS", "ILE", "LEU", "LYS", "MET", "PHE", "PRO", "SER", \ "THR", "TRP", "TYR", "VAL"] # generate initial model from PDB file mdl = mdlib.complete(env, file=pdb) s = mdlib.get_selection(mdl) seq_prev = design.seq ener0 = mdlib.get_energy(s) # calculate initial energy #print ener0 contribs = [ener0] #, ener_mut, ener_ab, ener_ba] ener_prev = ener0 n = 0 ener_mc = [contribs] while True: print " Step %g"%n rp = random.choice(respos) # randomly select position rt = random.choice(restyp) # randomly select residue print rp,rt # build model for actual mutation seq, ener = gen_all_models(env, design=design, \ seq_prev=seq_prev, rp=rp, rt=rt) print "seq: %s"%seq print "ener: %g"%ener # standard acceptance rejection criterion seq_prev, ener_prev = boltzmann(ener, \ ener_prev, seq, seq_prev, beta) contribs = [ener_prev] ener_mc.append(contribs) n +=1 if n >= len_mc: # wrap up # write mutant sequence to file Bio.SeqIO.write(Bio.SeqRecord.SeqRecord(seq_prev, id="data/final%g.fasta"%run), \ open("data/final%g.fasta"%run, "w"), "fasta") # align sequence and template align = mdlib.gen_align(env, pdb=pdb, mut="data/final%g.fasta"%run, \ out="data/align%g.fasta"%run) # generate model mdl = mdlib.get_automodel(env, "data/align%g.fasta"%run, "data/final%g.fasta"%run, pdb) ali_tf = tempfile.NamedTemporaryFile(prefix='ali_', suffix='.fasta', \ delete=False) #mdl = mdlib.get_model(env, file=current) mdlib.write_model(mdl, file="data/final_run%s"%run + ".pdb") #os.remove('data/mutant%g.pdb'%run) sys.stdout = nb_stdout # redirect output return seq_prev, ener_mc def parse_mc_input(mc_input): """ Parses multiprocessing input. Parameters ---------- Returns ------- run : int Index for number of run. design : object Design class instance. beta : float Inverse temperature. len_mc : int Length of each run. """ run = mc_input[0] design = mc_input[1][0] beta = mc_input[1][1] len_mc = mc_input[1][2] return run, design, beta, len_mc def gen_models(env, seq_mut=None, pdb=None): """ Generate models based on sequence Parameters ---------- env : object Modeller environment. seq_mut : object Instance of Seq class. pdb : str PDB filename for template. Returns ------- mdl : object Instance of Modeller's model class. """ # write mutant sequence to temporary file mut_tf = tempfile.NamedTemporaryFile(prefix='mut_', suffix='.fasta', \ delete=False) Bio.SeqIO.write(Bio.SeqRecord.SeqRecord(seq_mut, id=mut_tf.name), \ mut_tf.name, "fasta") mut_tf.close() # align sequence and template ali_tf = tempfile.NamedTemporaryFile(prefix='ali_', suffix='.fasta', \ delete=False) align = mdlib.gen_align(env, pdb=pdb, mut=mut_tf.name, out=ali_tf.name) # generate model mdl = mdlib.get_automodel(env, ali_tf.name, mut_tf.name, pdb) os.remove(mut_tf.name) os.remove(ali_tf.name) return mdl def gen_all_models(env, design=None, seq_prev=None, rp=None, rt=None, \ weights=[1. ,1.]): """ Generate mutated and competing models based on sequence Includes modelling the mutant for a given sequence and possible competing selections Parameters ---------- env : object Modeller environment. design: object Instance of the Design class. seq_prev : rp : rt : Returns ------- seq_mut : object MutableSeq with the mutated sequence. ener : float The energy of the mutated model. """ seq_mut, ener_mut = gen_mutated_models(env, design=design, seq_prev=seq_prev, rp=rp, rt=rt) #if type(design).__name__ == 'Repeat': # ener_comp = gen_interfaces(env, design=design, seq_mut=seq_mut, seq_prev=seq_prev, rp=rp, rt=rt) return seq_mut.toseq(), ener_mut #weights[0]*ener_mut + weights[1]*ener_comp def gen_mutated_models(env, design=None, seq_prev=None, rp=None, rt=None): """ Generate mutated model based on sequence Includes modelling the mutant for a given sequence and possible competing selections Parameters ---------- env : design: seq_prev : rp : rt : Returns ------- seq_mut : object MutableSeq """ # generate mutation seq_mut = mutator(seq_prev, rp, rt) print seq_mut # generate model for mutant mdl = gen_models(env, seq_mut=seq_mut, pdb=design.name) #mdl_tf = tempfile.NamedTemporaryFile(prefix='mdl_', suffix='.pdb', \ # delete=False) #mdlib.write_model(mdl, file=mdl_tf) #mdl_tf.close() # calculate energy for whole mutant #mdl = mdlib.complete(env, file=mdl_tf.name) s = mdlib.get_selection(mdl) print s try: ener = mdlib.get_energy(s) except: ener = 1e10 print ener #os.remove(mdl_tf.name) return seq_mut, ener def gen_interfaces(env, design=None, seq_mut=None, seq_prev=None, rp=None, rt=None): """ Generate competing interfaces """ print " Initial repeat:" print [seq_prev[x[0]:x[1]+1] for x in design.repeats] # check if mutated residue is in repeat try: # find position in repeat print "Finding mutated residue in repeat" mut_rep = [x for x in design.repeats if rp in range(x[0],x[1])][0] except IndexError: print " IndexError : residue not in repeat" return 0. ind_mut = design.repeats.index(mut_rep) index = rp - mut_rep[0] print " Mutated repeat:", ind_mut, mut_rep print [seq_mut[x[0]:x[1]+1] for x in design.repeats] print " residue:", index # Which interfaces to build ireps = range(len(design.repeats)) interfaces = [y for y in itertools.product(ireps,ireps) if \ ((y[0]!=y[1]) and (y[1]!=y[0]+1) and ind_mut in y)] # build competing interfaces ener_interfaces = 0. for inter in interfaces: # Interfaces are built by threading the repeat sequences into the 1st and 2nd repeat structure print " Building competing models", inter rep0 = design.repeats[inter[0]] rep1 = design.repeats[inter[1]] rep_prev = design.repeats[0] rep_next = design.repeats[1] seq_comp = seq_prev.tomutable() # replace original sequence by mutated sequence seq_comp[rep_prev[0]:rep_prev[1]+1] = seq_mut[rep0[0]:rep0[1]+1] seq_comp[rep_next[0]:rep_next[1]+1] = seq_mut[rep1[0]:rep1[1]+1] env.edat.nonbonded_sel_atoms = 2 mdl = gen_models(env, seq_mut=seq_comp, pdb=design.pdb) s0 = mdlib.get_selection(mdl, sel=mdl.residue_range(str(rep_prev[0]), str(rep_prev[1]+1))) s1 = mdlib.get_selection(mdl, sel=mdl.residue_range(str(rep_next[0]), str(rep_next[1]+1))) s0s1 =mdlib.get_selection(mdl, sel=(mdl.residue_range(str(rep_prev[0]), str(rep_prev[1]+1)), \ mdl.residue_range(str(rep_next[0]), str(rep_next[1]+1)))) mdlib.get_energy(s0) mdlib.get_energy(s1) mdlib.get_energy(s0s1) #ener_interfaces -= mdlib.get_energy(s0) print [seq_comp[x[0]:x[1]+1] for x in design.repeats] print ener_interfaces = 0. return ener_interfaces def mutator(seq, rp, rt): """ Generates mutation in Seq space Parameters ---------- seq : object BioPython Seq object to mutate. rp : int Index indicating position to mutate. rt : str 1 letter code with amino acid type to introduce. Returns ------- object BioPython Seq object with mutated sequence. """ try: mutable_seq = seq.tomutable() except AttributeError: mutable_seq = seq mutable_seq[rp] = Bio.SeqUtils.seq1(rt) return mutable_seq def boltzmann(ener, ener_prev, seq, seq_prev, beta): """ Boltzmann acceptance - rejection Parameters ---------- ener : float New energy. ener_prev : float Old energy. seq : object BioPython Seq object with new sequence. seq_prev : object BioPython Seq object with old sequence. beta : float Inverse temperature. """ if ener < ener_prev: seq_prev = seq ener_prev = ener else: dener = ener - ener_prev if np.exp(-beta*dener) > np.random.random(): seq_prev = seq ener_prev = ener return seq_prev, ener_prev
daviddesancho/RepeatDesigner
repeatdesigner/designlib.py
Python
lgpl-3.0
10,228
[ "Biopython" ]
354fe6ba0461edba6879f1c558ff33db08ddf580b908358828fe897230e0a820
# -*- coding: utf-8 -*- """ This file contains the general Qudi trace analysis logic. Qudi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Qudi 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 Qudi. If not, see <http://www.gnu.org/licenses/>. Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/> """ from qtpy import QtCore import numpy as np from scipy.signal import gaussian from scipy.ndimage import filters from scipy.interpolate import InterpolatedUnivariateSpline from collections import OrderedDict from logic.generic_logic import GenericLogic class TraceAnalysisLogic(GenericLogic): """ Perform a gated counting measurement with the hardware. """ _modclass = 'TraceAnalysisLogic' _modtype = 'logic' # declare connectors _in = {'counterlogic1': 'CounterLogic', 'savelogic': 'SaveLogic', 'fitlogic': 'FitLogic', } _out = {'traceanalysislogic1': 'TraceAnalysisLogic'} sigHistogramUpdated = QtCore.Signal() def __init__(self, config, **kwargs): """ Create CounterLogic object with connectors. @param dict config: module configuration @param dict kwargs: optional parameters """ super().__init__(config=config, **kwargs) self.log.info('The following configuration was found.') # checking for the right configuration for key in config.keys(): self.log.info('{0}: {1}'.format(key, config[key])) self.hist_data = None self._hist_num_bins = None def on_activate(self, e): """ Initialisation performed during activation of the module. @param object e: Event class object from Fysom. An object created by the state machine module Fysom, which is connected to a specific event (have a look in the Base Class). This object contains the passed event, the state before the event happened and the destination of the state which should be reached after the event had happened. """ self._counter_logic = self.get_in_connector('counterlogic1') self._save_logic = self.get_in_connector('savelogic') self._fit_logic = self.get_in_connector('fitlogic') self._counter_logic.sigGatedCounterFinished.connect(self.do_calculate_histogram) self.current_fit_function = 'No Fit' def on_deactivate(self, e): """ Deinitialisation performed during deactivation of the module. @param object e: Event class object from Fysom. A more detailed explanation can be found in method activation. """ return def set_num_bins_histogram(self, num_bins, update=True): """ Set the number of bins @param int num_bins: number of bins for the histogram @param bool update: if the change of bins should evoke a recalculation of the histogram. """ self._hist_num_bins = num_bins if update: self.do_calculate_histogram() def do_calculate_histogram(self): """ Passes all the needed parameters to the appropriated methods. @return: """ self.hist_data = self.calculate_histogram(self._counter_logic.countdata, self._hist_num_bins) self.sigHistogramUpdated.emit() def calculate_histogram(self, trace, num_bins=None, custom_bin_arr=None): """ Calculate the histogram of a given trace. @param np.array trace: a 1D trace @param int num_bins: number of bins between the minimal and maximal value of the trace. That must be an integer greater than or equal to 1. @param np.array custom_bin_arr: optional, 1D array. If a specific, non-uniform binning array is desired then it can be passed to the numpy routine. Then the parameter num_bins is ignored. Otherwise a uniform binning is applied by default. @return: np.array: a 2D array, where first entry are the x_values and second entry are the count values. The length of the array is normally determined by the num_bins parameter. Usually the bins for the histogram are taken to be equally spaced, ranging from the minimal to the maximal value of the input trace array. """ if custom_bin_arr is not None: hist_y_val, hist_x_val = np.histogram(trace, custom_bin_arr, density=False) else: # analyze the trace, and check whether all values are the same difference = trace.max() - trace.min() # if all values are the same, run at least the method with an zero # array. That will ensure at least an output: if np.isclose(0, difference) and num_bins is None: # numpy can handle an array of zeros num_bins = 50 hist_y_val, hist_x_val = np.histogram(trace, num_bins) # if no number of bins are passed, then take the integer difference # between the counts, that will prevent strange histogram artifacts: elif not np.isclose(0, difference) and num_bins is None: hist_y_val, hist_x_val = np.histogram(trace, int(difference)) # a histogram with self defined number of bins else: hist_y_val, hist_x_val = np.histogram(trace, num_bins) return hist_x_val, hist_y_val def analyze_flip_prob(self, trace, num_bins=None, threshold=None): """General method, which analysis how often a value was changed from one data point to another in relation to a certain threshold. @param np.array trace: 1D trace of data @param int num_bins: optional, if a specific size for the histogram is desired, which is used to calculate the threshold. @param float threshold: optional, if a specific threshold is going to be used, otherwise the threshold is calculated from the data. @return tuple(flip_prop, param): float flip_prop: the actual flip probability int num_of_flips: the total number of flips float fidelity: the fidelity float threshold: the calculated or passed threshold float lifetime_dark: the lifetime in the dark state in s float lifetime_bright: lifetime in the bright state in s """ hist_data = self.calculate_histogram(trace=trace, num_bins=num_bins) threshold_fit, fidelity, fit_param = self.calculate_threshold(hist_data) bin_trace = self.calculate_binary_trace(trace, threshold_fit) # here the index_arr contain all indices where the state is above # threshold, indicating the bright state. index_arr, filtered_arr = self.extract_filtered_values(trace, threshold_fit, below=False) # by shifting the index_arr one value further, one will investigate # basically the next state, where a change has happened. next_index_arr = index_arr+1 # Just for safety neglect the last value in the index_arr so that one # will not go beyond the array. next_filtered_bin_arr = bin_trace[next_index_arr[:-1]] # calculate how many darkstates are present in the array, remember # filtered_arr contains all the bright states. num_dark_state = len(trace) - len(filtered_arr) num_bright_state = len(filtered_arr) # extract the number of state, which has been flipped to dark state # (True) started in the bright state (=False) num_flip_to_dark = len(np.where(next_filtered_bin_arr == True)[0]) # flip probability: # In the array filtered_bin_arr all states are in bright state meaning # that if you would perform for # filtered_bin_arr = bin_trace[index_arr] # the mean value with filtered_bin_arr.mean() then you should get 0.0 # since every entry in that array is False. By looking at the next index # it might be that some entries turn to True, i.e. a flip from bright to # dark occurred. Then you get a different mean value, which would # indicate how many states are flipped from bright (False) to dark (True). # If all the next states would be dark (True), then you would perform a # perfect flip into the dark state, meaning a flip probability of 1. flip_prob = next_filtered_bin_arr.mean() # put all the calculated parameters in a proper dict: param = OrderedDict() param['num_dark_state'] = num_dark_state # Number of Dark States param['num_bright_state'] = num_bright_state # Number of Bright States param['num_flip_to_dark'] = num_flip_to_dark # Number of flips from bright to dark param['fidelity'] = fidelity # Fidelity of Double Poissonian Fit param['threshold'] = threshold_fit # Threshold # add the fit parameter to the output parameter: param.update(fit_param) return flip_prob, param def analyze_lifetime(self, trace, dt, estimated_lifetime=None): """ Perform an lifetime analysis of a 1D time trace. The analysis is based on the Hidden-Markov-Model @return: """ pass def analyze_flip_prob_postselect(self): """ Post select the data trace so that the flip probability is only calculated from a jump from below a threshold value to an value above threshold. @return: """ pass def get_fit_functions(self): """ Return all fit functions, which are currently implemented for that module. @return list: with string entries denoting the name of the fit. """ return ['No Fit', 'Gaussian', 'Double Gaussian', 'Poisson', 'Double Poisson'] def do_fit(self, fit_function=None): """ Makes the a fit of the current fit function. @param str fit_function: name of the chosen fit function. @return tuple(x_val, y_val, fit_results): x_val: a 1D numpy array containing the x values y_val: a 1D numpy array containing the y values fit_results: a string containing the information of the fit results. You can obtain with get_fit_methods all implemented fit methods. """ if self.hist_data is None: hist_fit_x = [] hist_fit_y = [] param_dict = OrderedDict() fit_result = None return hist_fit_x, hist_fit_y, param_dict, fit_result else: # self.log.debug((self.calculate_threshold(self.hist_data))) # shift x axis to middle of bin axis = self.hist_data[0][:-1]+(self.hist_data[0][1]-self.hist_data[0][0])/2. data = self.hist_data[1] if fit_function == 'No Fit': hist_fit_x, hist_fit_y, fit_param_dict, fit_result = self.do_no_fit() return hist_fit_x, hist_fit_y, fit_param_dict, fit_result elif fit_function == 'Gaussian': hist_fit_x, hist_fit_y, fit_param_dict, fit_result = self.do_gaussian_fit(axis, data) return hist_fit_x, hist_fit_y, fit_param_dict, fit_result elif fit_function == 'Double Gaussian': hist_fit_x, hist_fit_y, fit_param_dict, fit_result = self.do_doublegaussian_fit(axis, data) return hist_fit_x, hist_fit_y, fit_param_dict, fit_result elif fit_function == 'Poisson': hist_fit_x, hist_fit_y, fit_param_dict, fit_result = self.do_possonian_fit(axis, data) return hist_fit_x, hist_fit_y, fit_param_dict, fit_result elif fit_function == 'Double Poisson': hist_fit_x, hist_fit_y, fit_param_dict, fit_result = self.do_doublepossonian_fit(axis, data) return hist_fit_x, hist_fit_y, fit_param_dict, fit_result def do_no_fit(self): """ Perform no fit, basically return an empty array. @return tuple(x_val, y_val, fit_results): x_val: a 1D numpy array containing the x values y_val: a 1D numpy array containing the y values fit_results: a string containing the information of the fit results. """ hist_fit_x = [] hist_fit_y = [] param_dict = {} fit_result = None return hist_fit_x, hist_fit_y, param_dict, fit_result def do_gaussian_fit(self, axis, data): """ Perform a gaussian fit. @param axis: @param data: @return: """ model, params = self._fit_logic.make_gaussian_model() if len(axis) < len(params): self.log.warning('Fit could not be performed because number of ' 'parameters is smaller than data points.') return self.do_no_fit() else: parameters_to_substitute = dict() update_dict=dict() #TODO: move this to "gated counter" estimator in fitlogic # make the filter an extra function shared and usable for other # functions gauss = gaussian(10, 10) data_smooth = filters.convolve1d(data, gauss/gauss.sum(), mode='mirror') # integral of data corresponds to sqrt(2) * Amplitude * Sigma function = InterpolatedUnivariateSpline(axis, data_smooth, k=1) Integral = function.integral(axis[0], axis[-1]) amp = data_smooth.max() sigma = Integral / amp / np.sqrt(2 * np.pi) amplitude = amp * sigma * np.sqrt(2 * np.pi) update_dict['c'] = {'min': 0, 'max': data.max(), 'value': 0, 'vary': False} update_dict['center'] = {'min': axis.min(), 'max': axis.max(), 'value': axis[np.argmax(data)]} update_dict['sigma'] = {'min': -np.inf, 'max': np.inf, 'value': sigma} update_dict['amplitude'] = {'min': 0, 'max': np.inf, 'value': amplitude} result = self._fit_logic.make_gaussian_fit(axis=axis, data=data, add_parameters=update_dict) # 1000 points in x axis for smooth fit data hist_fit_x = np.linspace(axis[0], axis[-1], 1000) hist_fit_y = model.eval(x=hist_fit_x, params=result.params) param_dict = OrderedDict() # create the proper param_dict with the values: param_dict['sigma_0'] = {'value': result.params['amplitude'].value, 'error': result.params['amplitude'].stderr, 'unit' : 'Occurrences'} param_dict['FWHM'] = {'value': result.params['fwhm'].value, 'error': result.params['fwhm'].stderr, 'unit' : 'Counts/s'} param_dict['Center'] = {'value': result.params['center'].value, 'error': result.params['center'].stderr, 'unit' : 'Counts/s'} param_dict['Amplitude'] = {'value': result.params['amplitude'].value, 'error': result.params['amplitude'].stderr, 'unit' : 'Occurrences'} param_dict['chi_sqr'] = {'value': result.chisqr, 'unit': ''} return hist_fit_x, hist_fit_y, param_dict, result def do_doublegaussian_fit(self, axis, data): model, params = self._fit_logic.make_multiplegaussian_model(no_of_gauss=2) if len(axis) < len(params): self.log.warning('Fit could not be performed because number of ' 'parameters is smaller than data points') return self.do_no_fit() else: result = self._fit_logic.make_doublegaussian_fit(axis=axis, data=data, estimator='gated_counter', add_parameters=None) # 1000 points in x axis for smooth fit data hist_fit_x = np.linspace(axis[0], axis[-1], 1000) hist_fit_y = model.eval(x=hist_fit_x, params=result.params) # this dict will be passed to the formatting method param_dict = OrderedDict() # create the proper param_dict with the values: param_dict['sigma_0'] = {'value': result.params['gaussian0_sigma'].value, 'error': result.params['gaussian0_sigma'].stderr, 'unit' : 'Counts/s'} param_dict['FWHM_0'] = {'value': result.params['gaussian0_fwhm'].value, 'error': result.params['gaussian0_fwhm'].stderr, 'unit' : 'Counts/s'} param_dict['Center_0'] = {'value': result.params['gaussian0_center'].value, 'error': result.params['gaussian0_center'].stderr, 'unit' : 'Counts/s'} param_dict['Amplitude_0'] = {'value': result.params['gaussian0_amplitude'].value, 'error': result.params['gaussian0_amplitude'].stderr, 'unit' : 'Occurrences'} param_dict['sigma_1'] = {'value': result.params['gaussian1_sigma'].value, 'error': result.params['gaussian1_sigma'].stderr, 'unit' : 'Counts/s'} param_dict['FWHM_1'] = {'value': result.params['gaussian1_fwhm'].value, 'error': result.params['gaussian1_fwhm'].stderr, 'unit' : 'Counts/s'} param_dict['Center_1'] = {'value': result.params['gaussian1_center'].value, 'error': result.params['gaussian1_center'].stderr, 'unit' : 'Counts/s'} param_dict['Amplitude_1'] = {'value': result.params['gaussian1_amplitude'].value, 'error': result.params['gaussian1_amplitude'].stderr, 'unit' : 'Occurrences'} param_dict['chi_sqr'] = {'value': result.chisqr, 'unit': ''} return hist_fit_x, hist_fit_y, param_dict, result def do_doublepossonian_fit(self, axis, data): model, params = self._fit_logic.make_poissonian_model(no_of_functions=2) if len(axis) < len(params): self.log.warning('Fit could not be performed because number of ' 'parameters is smaller than data points') return self.do_no_fit() else: result = self._fit_logic.make_doublepoissonian_fit(axis=axis, data=data, add_parameters=None) # 1000 points in x axis for smooth fit data hist_fit_x = np.linspace(axis[0], axis[-1], 1000) hist_fit_y = model.eval(x=hist_fit_x, params=result.params) # this dict will be passed to the formatting method param_dict = OrderedDict() # create the proper param_dict with the values: param_dict['lambda_0'] = {'value': result.params['poissonian0_mu'].value, 'error': result.params['poissonian0_mu'].stderr, 'unit' : 'Counts/s'} param_dict['Amplitude_0'] = {'value': result.params['poissonian0_amplitude'].value, 'error': result.params['poissonian0_amplitude'].stderr, 'unit' : 'Occurrences'} param_dict['lambda_1'] = {'value': result.params['poissonian1_mu'].value, 'error': result.params['poissonian1_mu'].stderr, 'unit' : 'Counts/s'} param_dict['Amplitude_1'] = {'value': result.params['poissonian1_amplitude'].value, 'error': result.params['poissonian1_amplitude'].stderr, 'unit' : 'Occurrences'} param_dict['chi_sqr'] = {'value': result.chisqr, 'unit': ''} return hist_fit_x, hist_fit_y, param_dict, result def do_possonian_fit(self, axis, data): model, params = self._fit_logic.make_poissonian_model() if len(axis) < len(params): self.log.error('Fit could not be performed because number of ' 'parameters is smaller than data points') return self.do_no_fit() else: result = self._fit_logic.make_poissonian_fit(axis=axis, data=data, add_parameters=None) # 1000 points in x axis for smooth fit data hist_fit_x = np.linspace(axis[0], axis[-1], 1000) hist_fit_y = model.eval(x=hist_fit_x, params=result.params) # this dict will be passed to the formatting method param_dict = OrderedDict() # create the proper param_dict with the values: param_dict['lambda'] = {'value': result.params['poissonian_mu'].value, 'error': result.params['poissonian_mu'].stderr, 'unit' : 'Counts/s'} param_dict['chi_sqr'] = {'value': result.chisqr, 'unit': ''} return hist_fit_x, hist_fit_y, param_dict, result def get_poissonian(self, x_val, mu, amplitude): """ Calculate, bases on the passed values a poisson distribution. @param float mu: expected value of poisson distribution @param float amplitude: Amplitude to which is multiplied on distribution @param int,float or np.array x_val: x values for poisson distribution, also works for numbers (int or float) @return np.array: a 1D array with the calculated poisson distribution, corresponding to given parameters/ x values Calculate a Poisson distribution according to: P(k) = mu^k * exp(-mu) / k! """ model, params = self._fit_logic.make_poissonian_model() return model.eval(x=np.array(x_val), poissonian_mu=mu, poissonian_amplitude=amplitude) def guess_threshold(self, hist_val=None, trace=None, max_ratio_value=0.1): """ Assume a distribution between two values and try to guess the threshold. @param np.array hist_val: 1D array whitch represent the y values of a histogram of a trace. Optional, if None is passed here, the passed trace will be used for calculations. @param np.array trace: optional, 1D array containing the y values of a meausured counter trace. If None is passed to hist_y_val then the threshold will be calculated from the trace. @param float max_ration_value: the ratio how strong the lower y values will be cut off. For max_ratio_value=0.1 all the data which are 10% or less in amptitude compared to the maximal value are neglected. The guess procedure tries to find all values, which are max_ratio_value * maximum value of the histogram of the trace and selects those by indices. Then taking the first an the last might and assuming that the threshold is in the middle, gives a first estimate of the threshold value. FIXME: That guessing procedure can be improved! @return float: a guessed threshold """ if hist_val is None and trace is not None: hist_val = self.calculate_histogram(trace) hist_val = np.array(hist_val) # just to be sure to have a np.array indices_arr = np.where(hist_val[1] > hist_val[1].max() * max_ratio_value)[0] guessed_threshold = hist_val[0][int((indices_arr[-1] + indices_arr[0])/2)] return guessed_threshold def calculate_threshold(self, hist_data=None): """ Calculate the threshold by minimizing its overlap with the poissonian fits. @param np.array hist_data: 2D array whitch represent the x and y values of a histogram of a trace. @return tuple(float, float): threshold: the calculated threshold between two overlapping poissonian distributed peaks. fidelity: the measure how good the two peaks are resolved according to the calculated threshold The calculation of the threshold relies on fitting two poissonian distributions to the count histogram and minimize a threshold with respect to the overlap area: """ # perform the fit x_axis = hist_data[0][:-1]+(hist_data[0][1]-hist_data[0][0])/2. y_data = hist_data[1] hist_fit_x, hist_fit_y, param_dict = self.do_doublepossonian_fit(x_axis, y_data) if param_dict.get('lambda_0') is None: self.log.error('The double poissonian fit does not work! Take at ' 'least a dummy value, in order not to break the ' 'routine.') amp0 = 1 amp1 = 1 param_dict['Amplitude_0'] = {'value': amp0, 'unit': 'occurences'} param_dict['Amplitude_1'] = {'value': amp0, 'unit': 'occurences'} # make them a bit different so that fit works. mu0 = hist_data[0][:].mean()-0.1 mu1 = hist_data[0][:].mean()+0.1 param_dict['lambda_0'] = {'value': mu0, 'unit': 'counts'} param_dict['lambda_1'] = {'value': mu1, 'unit': 'counts'} else: mu0 = param_dict['lambda_0']['value'] mu1 = param_dict['lambda_1']['value'] amp0 = param_dict['Amplitude_0']['value'] amp1 = param_dict['Amplitude_1']['value'] if mu0 < mu1: first_dist = self.get_poissonian(x_val=hist_data[0], mu=mu0, amplitude=amp0) sec_dist = self.get_poissonian(x_val=hist_data[0], mu=mu1, amplitude=amp1) else: first_dist = self.get_poissonian(x_val=hist_data[0], mu=mu1, amplitude=amp1) sec_dist = self.get_poissonian(x_val=hist_data[0], mu=mu0, amplitude=amp0) # create a two poissonian array, where the second poissonian # distribution is add as negative values. Now the transition from # positive to negative values will get the threshold: difference_poissonian = first_dist - sec_dist trans_index = 0 for i in range(len(difference_poissonian)-1): # go through the combined histogram array and the point which # changes the sign. The transition from positive to negative values # will get the threshold: if difference_poissonian[i] < 0 and difference_poissonian[i+1] >= 0: trans_index = i break elif difference_poissonian[i] > 0 and difference_poissonian[i+1] <= 0: trans_index = i break threshold_fit = hist_data[0][trans_index] # Calculate also the readout fidelity, i.e. sum the area under the # first peak before the threshold of the first and second distribution # and take the ratio of that area. Do the same thing after the threshold # (of course with a reversed choice of the distribution). If the overlap # in both cases is very small, then the fidelity is good, if the overlap # is identical, then fidelity indicates a poor separation of the peaks. if mu0 < mu1: area0_low = self.get_poissonian(hist_data[0][0:trans_index], mu0, 1).sum() area0_high = self.get_poissonian(hist_data[0][trans_index:], mu0, 1).sum() area1_low = self.get_poissonian(hist_data[0][0:trans_index], mu1, 1).sum() area1_high = self.get_poissonian(hist_data[0][trans_index:], mu1, 1).sum() area0_low_amp = self.get_poissonian(hist_data[0][0:trans_index], mu0, amp0).sum() area0_high_amp = self.get_poissonian(hist_data[0][trans_index:], mu0, amp0).sum() area1_low_amp = self.get_poissonian(hist_data[0][0:trans_index], mu1, amp1).sum() area1_high_amp = self.get_poissonian(hist_data[0][trans_index:], mu1, amp1).sum() else: area1_low = self.get_poissonian(hist_data[0][0:trans_index], mu0, 1).sum() area1_high = self.get_poissonian(hist_data[0][trans_index:], mu0, 1).sum() area0_low = self.get_poissonian(hist_data[0][0:trans_index], mu1, 1).sum() area0_high = self.get_poissonian(hist_data[0][trans_index:], mu1, 1).sum() area1_low_amp = self.get_poissonian(hist_data[0][0:trans_index], mu0, amp0).sum() area1_high_amp = self.get_poissonian(hist_data[0][trans_index:], mu0, amp0).sum() area0_low_amp = self.get_poissonian(hist_data[0][0:trans_index], mu1, amp1).sum() area0_high_amp = self.get_poissonian(hist_data[0][trans_index:], mu1, amp1).sum() # Now calculate how big is the overlap relative to the sum of the other # part of the area, that will give the normalized fidelity: fidelity = 1 - (area1_low / area0_low + area0_high / area1_high) / 2 area0 = self.get_poissonian(hist_data[0][:], mu0, amp0).sum() area1 = self.get_poissonian(hist_data[0][:], mu1, amp1).sum() # try this new measure for the fidelity fidelity2 = 1 - ((area1_low_amp/area1) / (area0_low_amp/area0) + (area0_high_amp/area0) / (area1_high_amp/area1) ) / 2 param_dict['normalized_fidelity'] = fidelity2 return threshold_fit, fidelity, param_dict def calculate_binary_trace(self, trace, threshold): """ Calculate for a given threshold all the trace values und output a binary array, where True = Below or equal Threshold False = Above Threshold. @param np.array trace: a 1D array containing the y data, e.g. ccunts @param float threshold: value to decide whether a point in the trace is below/equal (True) or above threshold (False). @return np.array: 1D trace of the length(trace) but now with boolean entries """ return trace <= threshold def extract_filtered_values(self, trace, threshold, below=True): """ Extract only those values, which are below or equal a certain Threshold. @param np.array trace: @param float threshold: @return tuple(index_array, filtered_array): np.array index_array: 1D integer array containing the indices of the passed trace array which are equal or below the threshold np.array filtered_array: the actual values of the trace, which are equal or below threshold """ if below: index_array = np.where(trace <= threshold)[0] else: index_array = np.where(trace > threshold)[0] filtered_array = trace[index_array] return index_array, filtered_array
drogenlied/qudi
logic/trace_analysis_logic.py
Python
gpl-3.0
33,335
[ "Gaussian" ]
b8a6e7e871214a6f0f20757082d059d295207f42cdfcf4056ee736177c3f4608
"""Tests for algorithms for partial fraction decomposition of rational functions. """ from sympy.polys.partfrac import ( apart_undetermined_coeffs, apart, apart_list, assemble_partfrac_list ) from sympy import (S, Poly, E, pi, I, Matrix, Eq, RootSum, Lambda, Symbol, Dummy, factor, together, sqrt, Expr) from sympy.utilities.pytest import raises from sympy.abc import x, y, a, b, c def test_apart(): assert apart(1) == 1 assert apart(1, x) == 1 f, g = (x**2 + 1)/(x + 1), 2/(x + 1) + x - 1 assert apart(f, full=False) == g assert apart(f, full=True) == g f, g = 1/(x + 2)/(x + 1), 1/(1 + x) - 1/(2 + x) assert apart(f, full=False) == g assert apart(f, full=True) == g f, g = 1/(x + 1)/(x + 5), -1/(5 + x)/4 + 1/(1 + x)/4 assert apart(f, full=False) == g assert apart(f, full=True) == g assert apart((E*x + 2)/(x - pi)*(x - 1), x) == \ 2 - E + E*pi + E*x + (E*pi + 2)*(pi - 1)/(x - pi) assert apart(Eq((x**2 + 1)/(x + 1), x), x) == Eq(x - 1 + 2/(x + 1), x) raises(NotImplementedError, lambda: apart(1/(x + 1)/(y + 2))) def test_apart_matrix(): M = Matrix(2, 2, lambda i, j: 1/(x + i + 1)/(x + j)) assert apart(M) == Matrix([ [1/x - 1/(x + 1), (x + 1)**(-2)], [1/(2*x) - (S(1)/2)/(x + 2), 1/(x + 1) - 1/(x + 2)], ]) def test_apart_symbolic(): f = a*x**4 + (2*b + 2*a*c)*x**3 + (4*b*c - a**2 + a*c**2)*x**2 + \ (-2*a*b + 2*b*c**2)*x - b**2 g = a**2*x**4 + (2*a*b + 2*c*a**2)*x**3 + (4*a*b*c + b**2 + a**2*c**2)*x**2 + (2*c*b**2 + 2*a*b*c**2)*x + b**2*c**2 assert apart(f/g, x) == 1/a - 1/(x + c)**2 - b**2/(a*(a*x + b)**2) assert apart(1/((x + a)*(x + b)*(x + c)), x) == \ 1/((a - c)*(b - c)*(c + x)) - 1/((a - b)*(b - c)*(b + x)) + \ 1/((a - b)*(a - c)*(a + x)) def test_apart_extension(): f = 2/(x**2 + 1) g = I/(x + I) - I/(x - I) assert apart(f, extension=I) == g assert apart(f, gaussian=True) == g f = x/((x - 2)*(x + I)) assert factor(together(apart(f))) == f def test_apart_full(): f = 1/(x**2 + 1) assert apart(f, full=False) == f assert apart(f, full=True) == \ -RootSum(x**2 + 1, Lambda(a, a/(x - a)), auto=False)/2 f = 1/(x**3 + x + 1) assert apart(f, full=False) == f assert apart(f, full=True) == \ RootSum(x**3 + x + 1, Lambda(a, (6*a**2/31 - 9*a/31 + S(4)/31)/(x - a)), auto=False) f = 1/(x**5 + 1) assert apart(f, full=False) == \ (-S(1)/5)*((x**3 - 2*x**2 + 3*x - 4)/(x**4 - x**3 + x**2 - x + 1)) + (S(1)/5)/(x + 1) assert apart(f, full=True) == \ -RootSum(x**4 - x**3 + x**2 - x + 1, Lambda(a, a/(x - a)), auto=False)/5 + (S(1)/5)/(x + 1) def test_apart_undetermined_coeffs(): p = Poly(2*x - 3) q = Poly(x**9 - x**8 - x**6 + x**5 - 2*x**2 + 3*x - 1) r = (-x**7 - x**6 - x**5 + 4)/(x**8 - x**5 - 2*x + 1) + 1/(x - 1) assert apart_undetermined_coeffs(p, q) == r p = Poly(1, x, domain='ZZ[a,b]') q = Poly((x + a)*(x + b), x, domain='ZZ[a,b]') r = 1/((a - b)*(b + x)) - 1/((a - b)*(a + x)) assert apart_undetermined_coeffs(p, q) == r def test_apart_list(): from sympy.utilities.iterables import numbered_symbols w0, w1, w2 = Symbol("w0"), Symbol("w1"), Symbol("w2") _a = Dummy("a") f = (-2*x - 2*x**2) / (3*x**2 - 6*x) assert apart_list(f, x, dummies=numbered_symbols("w")) == (-1, Poly(S(2)/3, x, domain='QQ'), [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)]) assert apart_list(2/(x**2-2), x, dummies=numbered_symbols("w")) == (1, Poly(0, x, domain='ZZ'), [(Poly(w0**2 - 2, w0, domain='ZZ'), Lambda(_a, _a/2), Lambda(_a, -_a + x), 1)]) f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) assert apart_list(f, x, dummies=numbered_symbols("w")) == (1, Poly(0, x, domain='ZZ'), [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1), (Poly(w1**2 - 1, w1, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2), (Poly(w2 + 1, w2, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)]) def test_assemble_partfrac_list(): f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) pfd = apart_list(f) assert assemble_partfrac_list(pfd) == -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2) a = Dummy("a") pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)]) assert assemble_partfrac_list(pfd) == -1/(sqrt(2)*(x + sqrt(2))) + 1/(sqrt(2)*(x - sqrt(2))) def test_noncommutative_pseudomultivariate(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/(1 + y) assert apart(e + foo(e)) == c + foo(c) assert apart(e*foo(e)) == c*foo(c) def test_issue_5798(): assert apart( 2*x/(x**2 + 1) - (x - 1)/(2*(x**2 + 1)) + 1/(2*(x + 1)) - 2/x) == \ (3*x + 1)/(x**2 + 1)/2 + 1/(x + 1)/2 - 2/x
grevutiu-gabriel/sympy
sympy/polys/tests/test_partfrac.py
Python
bsd-3-clause
5,244
[ "Gaussian" ]
721eacd3b6b6e36cdee6d143d817366abb523f1bd4f7ac607ed8866a8cf60a77
from os import getenv import json import requests import responses from behave import * from app import server from compare import expect, ensure from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions BASE_URL = getenv('BASE_URL', 'http://localhost:5000/') WAIT_SECONDS = 30 @given(u'the following wishlists') def step_impl(context): """ Delete all Wishlists and load new ones """ headers = {'Content-Type': 'application/json'} #context.resp = requests.delete(context.base_url + '/wishlist/reset', headers=headers) #assert context.resp.status_code == 204 create_url = context.base_url + '/wishlists/1' for row in context.table: data = { "id": row['id'], "name": row['name'], } payload = json.dumps(data) context.resp = requests.post(create_url, data=payload, headers=headers) assert context.resp.status_code == 201 @when(u'I visit the "home page"') def step_impl(context): """ Get the home page URL""" context.driver.get(context.base_url) @then(u'I should see "{message}" in the title') def step_impl(context, message): """ Check the document title for a message """ assert message in context.driver.title @then(u'I should not see "{message}"') #maybe don't need this 'then' test def step_impl(context, message): error_msg = "I should not see '$s' in '%s' " % (message,context.resp.text) ensure(message in context.resp.text,False,error_msg) #@when(u'I see the "{element_name} to {text_string}" ') #def step_impl(context,element_name,text_string): # element_id = 'wishlist_' + element_name.lower() # element = context.driver.find_element_by_id(element_id) # element.clear() # element.send_keys(text_string) ################################################### # The following involve the button id in index.html ################################################### @when(u'I press the "{button}" button') def step_impl(context,button): button_id = button.lower() + '-btn' context.driver.find_element_by_id(button_id).click() @then(u'I should see "{name}" in the results') def step_impl(context,name): # found = WebDriverWait(context.driver,WAIT_SECONDS).until(expected_conditions.text_to_be_present_in_element((By.ID,'search_results'),name)) # expect(found).to_be(True) expect(True).to_be(True) @then(u'I should not see "{name}" in the results') def step_impl(context, name): element = context.driver.find_element_by_id('search_results') error_msg = "I should not see '%s' in '%s'" % (name, element.text) ensure(name in element.text, False, error_msg) @then(u'I should see the message "{message}"') def step_impl(context,message): # found = WebDriverWait(context.driver,WAIT_SECONDS).until(expected_conditions.text_to_be_present_in_element((By.ID,'flash_message'),message)) # expect(found).to_be(True) expect(True).to_be(True) @when(u'I change "{element_name}" to "{text_string}"') def step_impl(context,element_name,text_string): element_id = 'wishlist_' + element_name.lower() element = context.driver.find_element_by_id(element_id) element.clear() # element.send_keys(text_string) # element = WebDriverWait(context.driver,WAIT_SECONDS).until(expected_conditions.presence_of_element_located((By.ID, element_id))) # element.clear() element.send_keys(text_string) # expect(True).to_be(True) @when (u'I set the "{element_name}" to "{text_string}"') def step_impl(context, element_name, text_string): element_id = 'wishlist_' + element_name.lower() element = context.driver.find_element_by_id(element_id) element.clear() element.send_keys(text_string) #@when(u'I set the "name" to "wishlist1"') #def step_impl(context): # expect(True).to_be(True) # # raise NotImplementedError(u'STEP: When I set the "name" to "wishlist1"') #@when(u'I set the "id" to "1"') #def step_impl(context): # expect(True).to_be(True) # # raise NotImplementedError(u'STEP: When I set the "id" to "1"') #@when(u'I change the "name" to "wishlisttest"') #def step_impl(context): # expect(True).to_be(True) # # raise NotImplementedError(u'STEP: When I change the "name" to "test_change"') #@when(u'I set the "id" to "2"') #def step_impl(context): # expect(True).to_be(True) # # raise NotImplementedError(u'STEP: When I set the "id" to "2"')
nyu-devops-golf-team/wishlist
features/steps/wishlist_steps.py
Python
mit
4,484
[ "VisIt" ]
d92129862e014cddd13f92412ff05e51ca015873837d6ce451559c03c4c63203
# Copyright (c) 2013, GlaxoSmithKline Research & Development Ltd. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of GlaxoSmithKline Research & Development Ltd. # nor the names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Created by Jameed Hussain, October 2013 import sys import re from optparse import OptionParser from rdkit import Chem from rdkit import DataStructs parser = OptionParser( description="Program to Tversky search results as part of Fraggle", epilog="Format of input file: whole mol smiles,ID,fraggle split smiles\t\t" "Output: query_frag_smiles,query_smiles,query_id,retrieved_smi,retrieved_id,tversky_sim") parser.add_option('-f', '--frags', dest='f_file', type='string', help="File containing the query fragmentations from Fraggle") parser.add_option( '-c', '--cutoff', dest='cutoff', type='float', default=0.8, help="Cutoff for Tversy similarity. Only Tversky results with similarity greater than the cutoff will be output. DEFAULT = 0.8") #parse the command line options (options, args) = parser.parse_args() if (options.f_file is None): print("Please specify the file containing the Fraggle fragmentations") sys.exit(1) if ((options.cutoff < 0) or (options.cutoff > 1)): print("Please specify a Tversky cut-off between 0-1") sys.exit(1) #sys.exit(1) queries = [] query_info = [] q_split_input = open(options.f_file, "r") for line in q_split_input: info = line.rstrip().split(",") qmol = Chem.MolFromSmiles(info[2]) #print info[2] if qmol is None: sys.stderr.write("Can't generate mol for: %s\n" % (info[2])) continue #generate fp of query_substructs qfp = Chem.RDKFingerprint(qmol, maxPath=5, fpSize=1024, nBitsPerHash=2) queries.append(qfp) query_info.append((info[0], info[1], info[2])) fragments = len(query_info) for line in sys.stdin: line = line.rstrip() smi, id = re.split(r'\s|,', line) #print smi,id mol = Chem.MolFromSmiles(smi) if mol is None: sys.stderr.write("Can't generate mol for: %s\n" % (smi)) continue mfp = Chem.RDKFingerprint(mol, maxPath=5, fpSize=1024, nBitsPerHash=2) #print smi res = DataStructs.BulkTverskySimilarity(mfp, queries, 0, 1, False) #query_frag_smiles,query_smiles,query_id,retrieved_smi,retrieved_id,tversky_sim for i in range(fragments): if (res[i] >= options.cutoff): print("%s,%s,%s,%s,%s,%s" % (query_info[i][2], query_info[i][0], query_info[i][1], smi, id, res[i]))
rdkit/rdkit
Contrib/fraggle/rdkit_tversky.py
Python
bsd-3-clause
3,883
[ "RDKit" ]
fa90a32d388099fcc5bb06616a1fc8e8092d9e90c7c1a51f23fbcf27800ce9a8
r""" Nearly incompressible linear elasticity in mixed displacement-pressure formulation with comments. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{\Omega} p\ \nabla \cdot \ul{v} = 0 \;, \quad \forall \ul{v} \;, - \int_{\Omega} q\ \nabla \cdot \ul{u} - \int_{\Omega} \gamma q p = 0 \;, \quad \forall q \;. """ #! #! Linear Elasticity #! ================= #$ \centerline{Example input file, \today} #! This file models a cylinder that is fixed at one end while the #! second end has a specified displacement of 0.02 in the x direction #! (this boundary condition is named PerturbedSurface). #! The output is the displacement for each node, saved by default to #! simple_out.vtk. The material is linear elastic. from sfepy import data_dir from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson_mixed, bulk_from_youngpoisson #! Mesh #! ---- dim = 3 approx_u = '3_4_P1' approx_p = '3_4_P0' order = 2 filename_mesh = data_dir + '/meshes/3d/cylinder.mesh' #! Regions #! ------- #! Whole domain 'Omega', left and right ends. regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < 0.001)', 'facet'), 'Right' : ('vertices in (x > 0.099)', 'facet'), } #! Materials #! --------- #! The linear elastic material model is used. materials = { 'solid' : ({'D' : stiffness_from_youngpoisson_mixed(dim, 0.7e9, 0.4), 'gamma' : 1.0/bulk_from_youngpoisson(0.7e9, 0.4)},), } #! Fields #! ------ #! A field is used to define the approximation on a (sub)domain fields = { 'displacement': ('real', 'vector', 'Omega', 1), 'pressure' : ('real', 'scalar', 'Omega', 0), } #! Integrals #! --------- #! Define the integral type Volume/Surface and quadrature rule. integrals = { 'i' : order, } #! Variables #! --------- #! Define displacement and pressure fields and corresponding fields #! for test variables. variables = { 'u' : ('unknown field', 'displacement'), 'v' : ('test field', 'displacement', 'u'), 'p' : ('unknown field', 'pressure'), 'q' : ('test field', 'pressure', 'p'), } #! Boundary Conditions #! ------------------- #! The left end of the cylinder is fixed (all DOFs are zero) and #! the 'right' end has non-zero displacements only in the x direction. ebcs = { 'Fixed' : ('Left', {'u.all' : 0.0}), 'PerturbedSurface' : ('Right', {'u.0' : 0.02, 'u.1' : 0.0}), } #! Equations #! --------- #! The weak formulation of the linear elastic problem. equations = { 'balance_of_forces' : """ dw_lin_elastic.i.Omega( solid.D, v, u ) - dw_stokes.i.Omega( v, p ) = 0 """, 'pressure constraint' : """- dw_stokes.i.Omega( u, q ) - dw_volume_dot.i.Omega( solid.gamma, q, p ) = 0""", } #! Solvers #! ------- #! Define linear and nonlinear solver. #! Even linear problems are solved by a nonlinear solver - only one #! iteration is needed and the final rezidual is obtained for free. solvers = { 'ls' : ('ls.schur_complement', { 'keep': ['p'], 'eliminate': ['u'], }), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-2, 'eps_r' : 1e-10, }), } #! Options #! ------- #! Various problem-specific options. options = { 'output_dir' : './output', 'absolute_mesh_path' : True, }
RexFuzzle/sfepy
examples/linear_elasticity/linear_elastic_up.py
Python
bsd-3-clause
3,356
[ "VTK" ]
271383b65a8b623b4a4d3dc39e418c508ab299f939aff61809ecdb0e3669cae6
#!/usr/bin/env python """Setup configuration for the python grr modules.""" # pylint: disable=unused-variable # pylint: disable=g-multiple-import # pylint: disable=g-import-not-at-top import ConfigParser import os import subprocess from setuptools import find_packages, setup, Extension from setuptools.command.develop import develop from setuptools.command.install import install from setuptools.command.sdist import sdist IGNORE_GUI_DIRS = ["node_modules", "bower_components", "tmp"] def find_data_files(source, ignore_dirs=None): ignore_dirs = ignore_dirs or [] result = [] for directory, dirnames, files in os.walk(source): dirnames[:] = [d for d in dirnames if d not in ignore_dirs] files = [os.path.join(directory, x) for x in files] result.append((directory, files)) return result def run_make_files(make_docs=False, make_ui_files=True, force_compile_protos=False, sync_artifacts=True): """Builds necessary assets from sources.""" if force_compile_protos: # Clean and recompile the protobufs. subprocess.check_call(["python", "makefile.py", "--clean"]) else: subprocess.check_call(["python", "makefile.py"]) if sync_artifacts: # Sync the artifact repo with upstream for distribution. subprocess.check_call(["python", "makefile.py"], cwd="grr/artifacts") if make_docs: # Download the docs so they are available offline. subprocess.check_call(["python", "makefile.py"], cwd="docs") if make_ui_files: subprocess.check_call(["npm", "install"], cwd="grr/gui/static") subprocess.check_call( ["npm", "install", "-g", "bower", "gulp"], cwd="grr/gui/static") subprocess.check_call(["bower", "update"], cwd="grr/gui/static") subprocess.check_call(["gulp", "compile"], cwd="grr/gui/static") def get_version(): config = ConfigParser.SafeConfigParser() config.read( os.path.join(os.path.dirname(os.path.realpath(__file__)), "version.ini")) return config.get("Version", "packageversion") class Develop(develop): def run(self): run_make_files() develop.run(self) class Sdist(sdist): """Build sdist.""" user_options = sdist.user_options + [ ("no-make-docs", None, "Don't build ascii docs when building the sdist."), ("no-make-ui-files", None, "Don't build UI JS/CSS bundles (AdminUI " "won't work without them)."), ("no-compile-protos", None, "Don't clean protos, use existing _pb2's."), ("no-sync-artifacts", None, "Don't sync the artifact repo. This is unnecessary for " "clients and old client build OSes can't make the SSL connection."), ] def initialize_options(self): self.no_make_docs = None self.no_sync_artifacts = None self.no_make_ui_files = None self.no_compile_protos = None sdist.initialize_options(self) def run(self): run_make_files( make_docs=not self.no_make_docs, make_ui_files=not self.no_make_ui_files, force_compile_protos=not self.no_compile_protos, sync_artifacts=not self.no_sync_artifacts) sdist.run(self) class Install(install): """Allow some installation options.""" DEFAULT_TEMPLATE = """ # Autogenerated file. Do not edit. Written by setup.py. CONFIG_FILE = "%(CONFIG_FILE)s" """ user_options = install.user_options + [ ("config-file=", None, "Specify the default location of the GRR config file."), ] def initialize_options(self): self.config_file = None install.initialize_options(self) def finalize_options(self): if (self.config_file is not None and not os.access(self.config_file, os.R_OK)): raise RuntimeError("Default config file %s is not readable." % self.config_file) install.finalize_options(self) def run(self): # Update the defaults if needed. if self.config_file: with open("grr/defaults.py", "wb") as fd: fd.write(self.DEFAULT_TEMPLATE % dict(CONFIG_FILE=self.config_file)) install.run(self) data_files = ( find_data_files("docs") + find_data_files("executables") + find_data_files("install_data") + find_data_files("scripts") + find_data_files("grr/artifacts") + find_data_files("grr/checks") + find_data_files("grr/gui/static", ignore_dirs=IGNORE_GUI_DIRS) + find_data_files("grr/gui/local/static", ignore_dirs=IGNORE_GUI_DIRS) + ["version.ini"]) if "VIRTUAL_ENV" not in os.environ: print "*****************************************************" print " WARNING: You are not installing in a virtual" print " environment. This configuration is not supported!!!" print " Expect breakage." print "*****************************************************" setup_args = dict( name="grr-response-core", version=get_version(), description="GRR Rapid Response", license="Apache License, Version 2.0", url="https://github.com/google/grr", packages=find_packages(), zip_safe=False, include_package_data=True, ext_modules=[Extension( "grr._semantic", ["accelerated/accelerated.c"],)], cmdclass={ "develop": Develop, "install": Install, "sdist": Sdist, }, install_requires=[ "cryptography==1.5.2", "PyYAML==3.11", "binplist==0.1.4", "ipaddr==2.1.11", "ipython==5.0.0", "pip>=8.1.1", "psutil==4.3.0", "pyaml==15.8.2", "pycrypto==2.6.1", "python-dateutil==2.5.3", "pytsk3==20160721", "pytz==2016.4", "requests==2.9.1", "protobuf==3.2.0", "Werkzeug==0.11.3", "wheel==0.29", "virtualenv==15.0.3", ], extras_require={ # The following requirements are needed in Windows. ':sys_platform=="win32"': [ "WMI==1.4.9", "pypiwin32==219", ], }, # Data files used by GRR. Access these via the config_lib "resource" filter. data_files=data_files) setup(**setup_args)
pidydx/grr
setup.py
Python
apache-2.0
6,041
[ "GULP" ]
dcda6baf41dc70058b80d5686b6f42bf583923eaa8b123388cda85c75b80072e
# Orca # # Copyright 2004-2008 Sun Microsystems Inc. # Copyright 2010 Joanmarie Diggs # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. """Custom script for pidgin.""" __id__ = "$Id$" __version__ = "$Revision$" __date__ = "$Date$" __copyright__ = "Copyright (c) 2010 Joanmarie Diggs." __license__ = "LGPL" import pyatspi import orca.debug as debug import orca.messages as messages import orca.scripts.toolkits.GAIL as GAIL import orca.settings as settings from .chat import Chat from .script_utilities import Utilities from .speech_generator import SpeechGenerator ######################################################################## # # # The Pidgin script class. # # # ######################################################################## class Script(GAIL.Script): def __init__(self, app): """Creates a new script for the given application. Arguments: - app: the application to create a script for. """ # So we can take an educated guess at identifying the buddy list. # self._buddyListAncestries = [[pyatspi.ROLE_TREE_TABLE, pyatspi.ROLE_SCROLL_PANE, pyatspi.ROLE_FILLER, pyatspi.ROLE_PAGE_TAB, pyatspi.ROLE_PAGE_TAB_LIST, pyatspi.ROLE_FILLER, pyatspi.ROLE_FRAME]] GAIL.Script.__init__(self, app) def getChat(self): """Returns the 'chat' class for this script.""" return Chat(self, self._buddyListAncestries) def getSpeechGenerator(self): """Returns the speech generator for this script. """ return SpeechGenerator(self) def getUtilities(self): """Returns the utilites for this script.""" return Utilities(self) def setupInputEventHandlers(self): """Defines InputEventHandler fields for this script that can be called by the key and braille bindings. Here we need to add the handlers for chat functionality. """ GAIL.Script.setupInputEventHandlers(self) self.inputEventHandlers.update(self.chat.inputEventHandlers) def getAppKeyBindings(self): """Returns the application-specific keybindings for this script.""" return self.chat.keyBindings def getAppPreferencesGUI(self): """Return a GtkGrid containing the application unique configuration GUI items for the current application. The chat-related options get created by the chat module.""" return self.chat.getAppPreferencesGUI() def getPreferencesFromGUI(self): """Returns a dictionary with the app-specific preferences.""" return self.chat.getPreferencesFromGUI() def onChildrenAdded(self, event): """Callback for object:children-changed:add accessibility events.""" # Check to see if a new chat room tab has been created and if it # has, then announce its name. See bug #469098 for more details. # if event.type.startswith("object:children-changed:add"): rolesList = [pyatspi.ROLE_PAGE_TAB_LIST, pyatspi.ROLE_FILLER, pyatspi.ROLE_FRAME] if self.utilities.hasMatchingHierarchy(event.source, rolesList): # As it's possible to get this component hierarchy in other # places than the chat room (i.e. the Preferences dialog), # we check to see if the name of the frame is the same as one # of its children. If it is, then it's a chat room tab event. # For a final check, we only announce the new chat tab if the # last child has a name. # nameFound = False frameName = event.source.parent.parent.name for child in event.source: if frameName and (frameName == child.name): nameFound = True if nameFound: child = event.source[-1] if child.name: line = messages.CHAT_NEW_TAB % child.name voice = self.speechGenerator.voice(obj=child, string=line) self.speakMessage(line, voice=voice) def onNameChanged(self, event): """Called whenever a property on an object changes. Arguments: - event: the Event """ if self.chat.isInBuddyList(event.source): return else: GAIL.Script.onNameChanged(self, event) def onTextDeleted(self, event): """Called whenever text is deleted from an object. Arguments: - event: the Event """ if self.chat.isInBuddyList(event.source): return else: GAIL.Script.onTextDeleted(self, event) def onTextInserted(self, event): """Called whenever text is added to an object.""" if self.chat.presentInsertedText(event): return GAIL.Script.onTextInserted(self, event) def onValueChanged(self, event): """Called whenever an object's value changes. Currently, the value changes for non-focused objects are ignored. Arguments: - event: the Event """ if self.chat.isInBuddyList(event.source): return else: GAIL.Script.onValueChanged(self, event) def onWindowActivated(self, event): """Called whenever a toplevel window is activated.""" if not settings.enableSadPidginHack: msg = "PIDGIN: Hack for missing events disabled" debug.println(debug.LEVEL_INFO, msg, True) GAIL.Script.onWindowActivated(self, event) return msg = "PIDGIN: Starting hack for missing events" debug.println(debug.LEVEL_INFO, msg, True) # Hack to "tickle" the accessible hierarchy. Otherwise, the # events we need to present text added to the chatroom are # missing. hasRole = lambda x: x and x.getRole() == pyatspi.ROLE_PAGE_TAB allPageTabs = pyatspi.findAllDescendants(event.source, hasRole) msg = "PIDGIN: Hack to work around missing events complete" debug.println(debug.LEVEL_INFO, msg, True) GAIL.Script.onWindowActivated(self, event) def onExpandedChanged(self, event): """Callback for object:state-changed:expanded accessibility events.""" # Overridden here because the event.source is in a hidden column. obj = event.source if self.chat.isInBuddyList(obj): obj = obj.parent[obj.getIndexInParent() + 1] self.presentObject(obj, alreadyFocused=True) return GAIL.Script.onExpandedChanged(self, event)
GNOME/orca
src/orca/scripts/apps/pidgin/script.py
Python
lgpl-2.1
7,810
[ "ORCA" ]
ede48fceaf2e3bdfb088adbbe1a7796d8a2983f07fab97ecdb2f9ff98ff6e4a8
import os import logging import stat import collections import uuid import urlparse from functools import partial from typing import Any, Callable, Set, Text, Tuple, Union import schema_salad.validate as validate _logger = logging.getLogger("cwltool") MapperEnt = collections.namedtuple("MapperEnt", ["resolved", "target", "type"]) def adjustFiles(rec, op): # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None """Apply a mapping function to each File path in the object `rec`.""" if isinstance(rec, dict): if rec.get("class") == "File": rec["path"] = op(rec["path"]) for d in rec: adjustFiles(rec[d], op) if isinstance(rec, list): for d in rec: adjustFiles(d, op) def adjustFileObjs(rec, op): # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None """Apply an update function to each File object in the object `rec`.""" if isinstance(rec, dict): if rec.get("class") == "File": op(rec) for d in rec: adjustFileObjs(rec[d], op) if isinstance(rec, list): for d in rec: adjustFileObjs(d, op) def adjustDirObjs(rec, op): # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None """Apply an update function to each Directory object in the object `rec`.""" if isinstance(rec, dict): if rec.get("class") == "Directory": op(rec) for key in rec: adjustDirObjs(rec[key], op) if isinstance(rec, list): for d in rec: adjustDirObjs(d, op) def normalizeFilesDirs(job): # type: (Union[List[Dict[Text, Any]], Dict[Text, Any]]) -> None def addLocation(d): if "location" not in d: if d["class"] == "File" and ("contents" not in d): raise validate.ValidationException("Anonymous file object must have 'contents' and 'basename' fields.") if d["class"] == "Directory" and ("listing" not in d or "basename" not in d): raise validate.ValidationException("Anonymous directory object must have 'listing' and 'basename' fields.") d["location"] = "_:" + Text(uuid.uuid4()) if "basename" not in d: d["basename"] = Text(uuid.uuid4()) if "basename" not in d: parse = urlparse.urlparse(d["location"]) d["basename"] = os.path.basename(parse.path) adjustFileObjs(job, addLocation) adjustDirObjs(job, addLocation) def abspath(src, basedir): # type: (Text, Text) -> Text if src.startswith(u"file://"): ab = src[7:] else: ab = src if os.path.isabs(src) else os.path.join(basedir, src) return ab def dedup(listing): # type: (List[Any]) -> List[Any] marksub = set() def mark(d): marksub.add(d["location"]) for l in listing: if l["class"] == "Directory": for e in l.get("listing", []): adjustFileObjs(e, mark) adjustDirObjs(e, mark) dd = [] markdup = set() # type: Set[Text] for r in listing: if r["location"] not in marksub and r["location"] not in markdup: dd.append(r) markdup.add(r["location"]) return dd class PathMapper(object): """Mapping of files from relative path provided in the file to a tuple of (absolute local path, absolute container path) The tao of PathMapper: The initializer takes a list of File and Directory objects, a base directory (for resolving relative references) and a staging directory (where the files are mapped to). The purpose of the setup method is to determine where each File or Directory should be placed on the target file system (relative to stagedir). If separatedirs=True, unrelated files will be isolated in their own directories under stagedir. If separatedirs=False, files and directories will all be placed in stagedir (with the possibility for name collisions...) The path map maps the "location" of the input Files and Directory objects to a tuple (resolved, target, type). The "resolved" field is the "real" path on the local file system (after resolving relative paths and traversing symlinks). The "target" is the path on the target file system (under stagedir). The type is the object type (one of File, Directory, CreateFile, WritableFile). The latter two (CreateFile, WritableFile) are used by InitialWorkDirRequirement to indicate files that are generated on the fly (CreateFile, in this case "resolved" holds the file contents instead of the path because they file doesn't exist) or copied into the output directory so they can be opened for update ("r+" or "a") (WritableFile). """ def __init__(self, referenced_files, basedir, stagedir, separateDirs=True): # type: (List[Any], Text, Text, bool) -> None self._pathmap = {} # type: Dict[Text, MapperEnt] self.stagedir = stagedir self.separateDirs = separateDirs self.setup(dedup(referenced_files), basedir) def visitlisting(self, listing, stagedir, basedir): # type: (List[Dict[Text, Any]], Text, Text) -> None for ld in listing: tgt = os.path.join(stagedir, ld["basename"]) if ld["class"] == "Directory": self.visit(ld, tgt, basedir, copy=ld.get("writable", False)) else: self.visit(ld, stagedir, basedir, copy=ld.get("writable", False)) def visit(self, obj, stagedir, basedir, copy=False): # type: (Dict[Text, Any], Text, Text, bool) -> None if obj["class"] == "Directory": self._pathmap[obj["location"]] = MapperEnt(obj["location"], stagedir, "Directory") self.visitlisting(obj.get("listing", []), stagedir, basedir) elif obj["class"] == "File": path = obj["location"] if path in self._pathmap: return ab = abspath(path, basedir) tgt = os.path.join(stagedir, obj["basename"]) if "contents" in obj and obj["location"].startswith("_:"): self._pathmap[obj["location"]] = MapperEnt(obj["contents"], tgt, "CreateFile") else: if copy: self._pathmap[path] = MapperEnt(ab, tgt, "WritableFile") else: self._pathmap[path] = MapperEnt(ab, tgt, "File") self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir) def setup(self, referenced_files, basedir): # type: (List[Any], Text) -> None # Go through each file and set the target to its own directory along # with any secondary files. stagedir = self.stagedir for fob in referenced_files: if self.separateDirs: stagedir = os.path.join(self.stagedir, "stg%s" % uuid.uuid4()) self.visit(fob, stagedir, basedir) # Dereference symbolic links for path, (ab, tgt, type) in self._pathmap.items(): if type != "File": # or not os.path.exists(ab): continue deref = ab st = os.lstat(deref) while stat.S_ISLNK(st.st_mode): rl = os.readlink(deref) deref = rl if os.path.isabs(rl) else os.path.join( os.path.dirname(deref), rl) st = os.lstat(deref) self._pathmap[path] = MapperEnt(deref, tgt, "File") def mapper(self, src): # type: (Text) -> MapperEnt if u"#" in src: i = src.index(u"#") p = self._pathmap[src[:i]] return MapperEnt(p.resolved, p.target + src[i:], None) else: return self._pathmap[src] def files(self): # type: () -> List[Text] return self._pathmap.keys() def items(self): # type: () -> List[Tuple[Text, MapperEnt]] return self._pathmap.items() def reversemap(self, target): # type: (Text) -> Tuple[Text, Text] for k, v in self._pathmap.items(): if v[1] == target: return (k, v[0]) return None
jeremiahsavage/cwltool
cwltool/pathmapper.py
Python
apache-2.0
8,169
[ "VisIt" ]
205728ec623f2353195dd6d428c5d59bc4bf9a38939194971eeeb9b42d135ebb
# beam_search.py - progressive widening beam search # # Copyright 2016-2018 NetworkX developers. """ =========== Beam Search =========== Beam search with dynamic beam width. The progressive widening beam search repeatedly executes a beam search with increasing beam width until the target node is found. """ import math import networkx as nx def progressive_widening_search(G, source, value, condition, initial_width=1): """Progressive widening beam search to find a node. The progressive widening beam search involves a repeated beam search, starting with a small beam width then extending to progressively larger beam widths if the target node is not found. This implementation simply returns the first node found that matches the termination condition. `G` is a NetworkX graph. `source` is a node in the graph. The search for the node of interest begins here and extends only to those nodes in the (weakly) connected component of this node. `value` is a function that returns a real number indicating how good a potential neighbor node is when deciding which neighbor nodes to enqueue in the breadth-first search. Only the best nodes within the current beam width will be enqueued at each step. `condition` is the termination condition for the search. This is a function that takes a node as input and return a Boolean indicating whether the node is the target. If no node matches the termination condition, this function raises :exc:`NodeNotFound`. `initial_width` is the starting beam width for the beam search (the default is one). If no node matching the `condition` is found with this beam width, the beam search is restarted from the `source` node with a beam width that is twice as large (so the beam width increases exponentially). The search terminates after the beam width exceeds the number of nodes in the graph. """ # Check for the special case in which the source node satisfies the # termination condition. if condition(source): return source # The largest possible value of `i` in this range yields a width at # least the number of nodes in the graph, so the final invocation of # `bfs_beam_edges` is equivalent to a plain old breadth-first # search. Therefore, all nodes will eventually be visited. # # TODO In Python 3.3+, this should be `math.log2(len(G))`. log_m = math.ceil(math.log(len(G), 2)) for i in range(log_m): width = initial_width * pow(2, i) # Since we are always starting from the same source node, this # search may visit the same nodes many times (depending on the # implementation of the `value` function). for u, v in nx.bfs_beam_edges(G, source, value, width): if condition(v): return v # At this point, since all nodes have been visited, we know that # none of the nodes satisfied the termination condition. raise nx.NodeNotFound('no node satisfied the termination condition') def main(): """Search for a node with high centrality. In this example, we generate a random graph, compute the centrality of each node, then perform the progressive widening search in order to find a node of high centrality. """ G = nx.gnp_random_graph(100, 0.5) centrality = nx.eigenvector_centrality(G) avg_centrality = sum(centrality.values()) / len(G) def has_high_centrality(v): return centrality[v] >= avg_centrality source = 0 value = centrality.get condition = has_high_centrality found_node = progressive_widening_search(G, source, value, condition) c = centrality[found_node] print('found node {0} with centrality {1}'.format(found_node, c)) if __name__ == '__main__': main()
kenshay/ImageScript
ProgramData/SystemFiles/Python/share/doc/networkx-2.2/examples/algorithms/beam_search.py
Python
gpl-3.0
3,830
[ "VisIt" ]
6f3318cfa74336095408a8e121d66f92803f5ef38e2d6e9c53d0b20ccc51d478
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys import warnings from pyspark import since, keyword_only from pyspark.ml.util import * from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, JavaWrapper from pyspark.ml.param.shared import * from pyspark.ml.common import inherit_doc, _java2py from pyspark.ml.stat import MultivariateGaussian from pyspark.sql import DataFrame __all__ = ['BisectingKMeans', 'BisectingKMeansModel', 'BisectingKMeansSummary', 'KMeans', 'KMeansModel', 'GaussianMixture', 'GaussianMixtureModel', 'GaussianMixtureSummary', 'LDA', 'LDAModel', 'LocalLDAModel', 'DistributedLDAModel', 'PowerIterationClustering'] class ClusteringSummary(JavaWrapper): """ Clustering results for a given model. .. versionadded:: 2.1.0 """ @property @since("2.1.0") def predictionCol(self): """ Name for column of predicted clusters in `predictions`. """ return self._call_java("predictionCol") @property @since("2.1.0") def predictions(self): """ DataFrame produced by the model's `transform` method. """ return self._call_java("predictions") @property @since("2.1.0") def featuresCol(self): """ Name for column of features in `predictions`. """ return self._call_java("featuresCol") @property @since("2.1.0") def k(self): """ The number of clusters the model was trained with. """ return self._call_java("k") @property @since("2.1.0") def cluster(self): """ DataFrame of predicted cluster centers for each training data point. """ return self._call_java("cluster") @property @since("2.1.0") def clusterSizes(self): """ Size of (number of data points in) each cluster. """ return self._call_java("clusterSizes") @property @since("2.4.0") def numIter(self): """ Number of iterations. """ return self._call_java("numIter") @inherit_doc class _GaussianMixtureParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasProbabilityCol, HasTol, HasAggregationDepth, HasWeightCol): """ Params for :py:class:`GaussianMixture` and :py:class:`GaussianMixtureModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "Number of independent Gaussians in the mixture model. " + "Must be > 1.", typeConverter=TypeConverters.toInt) @since("2.0.0") def getK(self): """ Gets the value of `k` """ return self.getOrDefault(self.k) class GaussianMixtureModel(JavaModel, _GaussianMixtureParams, JavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by GaussianMixture. .. versionadded:: 2.0.0 """ @since("3.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("3.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("3.0.0") def setProbabilityCol(self, value): """ Sets the value of :py:attr:`probabilityCol`. """ return self._set(probabilityCol=value) @property @since("2.0.0") def weights(self): """ Weight for each Gaussian distribution in the mixture. This is a multinomial probability distribution over the k Gaussians, where weights[i] is the weight for Gaussian i, and weights sum to 1. """ return self._call_java("weights") @property @since("3.0.0") def gaussians(self): """ Array of :py:class:`MultivariateGaussian` where gaussians[i] represents the Multivariate Gaussian (Normal) Distribution for Gaussian i """ sc = SparkContext._active_spark_context jgaussians = self._java_obj.gaussians() return [ MultivariateGaussian(_java2py(sc, jgaussian.mean()), _java2py(sc, jgaussian.cov())) for jgaussian in jgaussians] @property @since("2.0.0") def gaussiansDF(self): """ Retrieve Gaussian distributions as a DataFrame. Each row represents a Gaussian Distribution. The DataFrame has two columns: mean (Vector) and cov (Matrix). """ return self._call_java("gaussiansDF") @property @since("2.1.0") def summary(self): """ Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists. """ if self.hasSummary: return GaussianMixtureSummary(super(GaussianMixtureModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("3.0.0") def predict(self, value): """ Predict label for the given features. """ return self._call_java("predict", value) @since("3.0.0") def predictProbability(self, value): """ Predict probability for the given features. """ return self._call_java("predictProbability", value) @inherit_doc class GaussianMixture(JavaEstimator, _GaussianMixtureParams, JavaMLWritable, JavaMLReadable): """ GaussianMixture clustering. This class performs expectation maximization for multivariate Gaussian Mixture Models (GMMs). A GMM represents a composite distribution of independent Gaussian distributions with associated "mixing" weights specifying each's contribution to the composite. Given a set of sample points, this class will maximize the log-likelihood for a mixture of k Gaussians, iterating until the log-likelihood changes by less than convergenceTol, or until it has reached the max number of iterations. While this process is generally guaranteed to converge, it is not guaranteed to find a global optimum. .. note:: For high-dimensional data (with many features), this algorithm may perform poorly. This is due to high-dimensional data (a) making it difficult to cluster at all (based on statistical/theoretical arguments) and (b) numerical issues with Gaussian distributions. >>> from pyspark.ml.linalg import Vectors >>> data = [(Vectors.dense([-0.1, -0.05 ]),), ... (Vectors.dense([-0.01, -0.1]),), ... (Vectors.dense([0.9, 0.8]),), ... (Vectors.dense([0.75, 0.935]),), ... (Vectors.dense([-0.83, -0.68]),), ... (Vectors.dense([-0.91, -0.76]),)] >>> df = spark.createDataFrame(data, ["features"]) >>> gm = GaussianMixture(k=3, tol=0.0001, seed=10) >>> gm.getMaxIter() 100 >>> gm.setMaxIter(10) GaussianMixture... >>> gm.getMaxIter() 10 >>> model = gm.fit(df) >>> model.getAggregationDepth() 2 >>> model.getFeaturesCol() 'features' >>> model.setPredictionCol("newPrediction") GaussianMixtureModel... >>> model.predict(df.head().features) 2 >>> model.predictProbability(df.head().features) DenseVector([0.0, 0.4736, 0.5264]) >>> model.hasSummary True >>> summary = model.summary >>> summary.k 3 >>> summary.clusterSizes [2, 2, 2] >>> summary.logLikelihood 8.14636... >>> weights = model.weights >>> len(weights) 3 >>> gaussians = model.gaussians >>> len(gaussians) 3 >>> gaussians[0].mean DenseVector([0.825, 0.8675]) >>> gaussians[0].cov.toArray() array([[ 0.005625 , -0.0050625 ], [-0.0050625 , 0.00455625]]) >>> gaussians[1].mean DenseVector([-0.4777, -0.4096]) >>> gaussians[1].cov.toArray() array([[ 0.1679695 , 0.13181786], [ 0.13181786, 0.10524592]]) >>> gaussians[2].mean DenseVector([-0.4473, -0.3853]) >>> gaussians[2].cov.toArray() array([[ 0.16730412, 0.13112435], [ 0.13112435, 0.10469614]]) >>> model.gaussiansDF.select("mean").head() Row(mean=DenseVector([0.825, 0.8675])) >>> model.gaussiansDF.select("cov").head() Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False)) >>> transformed = model.transform(df).select("features", "newPrediction") >>> rows = transformed.collect() >>> rows[4].newPrediction == rows[5].newPrediction True >>> rows[2].newPrediction == rows[3].newPrediction True >>> gmm_path = temp_path + "/gmm" >>> gm.save(gmm_path) >>> gm2 = GaussianMixture.load(gmm_path) >>> gm2.getK() 3 >>> model_path = temp_path + "/gmm_model" >>> model.save(model_path) >>> model2 = GaussianMixtureModel.load(model_path) >>> model2.hasSummary False >>> model2.weights == model.weights True >>> model2.gaussians[0].mean == model.gaussians[0].mean True >>> model2.gaussians[0].cov == model.gaussians[0].cov True >>> model2.gaussians[1].mean == model.gaussians[1].mean True >>> model2.gaussians[1].cov == model.gaussians[1].cov True >>> model2.gaussians[2].mean == model.gaussians[2].mean True >>> model2.gaussians[2].cov == model.gaussians[2].cov True >>> model2.gaussiansDF.select("mean").head() Row(mean=DenseVector([0.825, 0.8675])) >>> model2.gaussiansDF.select("cov").head() Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False)) >>> gm2.setWeightCol("weight") GaussianMixture... .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, featuresCol="features", predictionCol="prediction", k=2, probabilityCol="probability", tol=0.01, maxIter=100, seed=None, aggregationDepth=2, weightCol=None): """ __init__(self, featuresCol="features", predictionCol="prediction", k=2, \ probabilityCol="probability", tol=0.01, maxIter=100, seed=None, \ aggregationDepth=2, weightCol=None) """ super(GaussianMixture, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.GaussianMixture", self.uid) self._setDefault(k=2, tol=0.01, maxIter=100, aggregationDepth=2) kwargs = self._input_kwargs self.setParams(**kwargs) def _create_model(self, java_model): return GaussianMixtureModel(java_model) @keyword_only @since("2.0.0") def setParams(self, featuresCol="features", predictionCol="prediction", k=2, probabilityCol="probability", tol=0.01, maxIter=100, seed=None, aggregationDepth=2, weightCol=None): """ setParams(self, featuresCol="features", predictionCol="prediction", k=2, \ probabilityCol="probability", tol=0.01, maxIter=100, seed=None, \ aggregationDepth=2, weightCol=None) Sets params for GaussianMixture. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.0.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("2.0.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("2.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("2.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("2.0.0") def setProbabilityCol(self, value): """ Sets the value of :py:attr:`probabilityCol`. """ return self._set(probabilityCol=value) @since("3.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @since("2.0.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("2.0.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("3.0.0") def setAggregationDepth(self, value): """ Sets the value of :py:attr:`aggregationDepth`. """ return self._set(aggregationDepth=value) class GaussianMixtureSummary(ClusteringSummary): """ Gaussian mixture clustering results for a given model. .. versionadded:: 2.1.0 """ @property @since("2.1.0") def probabilityCol(self): """ Name for column of predicted probability of each cluster in `predictions`. """ return self._call_java("probabilityCol") @property @since("2.1.0") def probability(self): """ DataFrame of probabilities of each cluster for each training data point. """ return self._call_java("probability") @property @since("2.2.0") def logLikelihood(self): """ Total log-likelihood for this model on the given data. """ return self._call_java("logLikelihood") class KMeansSummary(ClusteringSummary): """ Summary of KMeans. .. versionadded:: 2.1.0 """ @property @since("2.4.0") def trainingCost(self): """ K-means cost (sum of squared distances to the nearest centroid for all points in the training dataset). This is equivalent to sklearn's inertia. """ return self._call_java("trainingCost") @inherit_doc class _KMeansParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasTol, HasDistanceMeasure, HasWeightCol): """ Params for :py:class:`KMeans` and :py:class:`KMeansModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The number of clusters to create. Must be > 1.", typeConverter=TypeConverters.toInt) initMode = Param(Params._dummy(), "initMode", "The initialization algorithm. This can be either \"random\" to " + "choose random points as initial cluster centers, or \"k-means||\" " + "to use a parallel variant of k-means++", typeConverter=TypeConverters.toString) initSteps = Param(Params._dummy(), "initSteps", "The number of steps for k-means|| " + "initialization mode. Must be > 0.", typeConverter=TypeConverters.toInt) @since("1.5.0") def getK(self): """ Gets the value of `k` """ return self.getOrDefault(self.k) @since("1.5.0") def getInitMode(self): """ Gets the value of `initMode` """ return self.getOrDefault(self.initMode) @since("1.5.0") def getInitSteps(self): """ Gets the value of `initSteps` """ return self.getOrDefault(self.initSteps) class KMeansModel(JavaModel, _KMeansParams, GeneralJavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by KMeans. .. versionadded:: 1.5.0 """ @since("3.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("3.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("1.5.0") def clusterCenters(self): """Get the cluster centers, represented as a list of NumPy arrays.""" return [c.toArray() for c in self._call_java("clusterCenters")] @property @since("2.1.0") def summary(self): """ Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists. """ if self.hasSummary: return KMeansSummary(super(KMeansModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("3.0.0") def predict(self, value): """ Predict label for the given features. """ return self._call_java("predict", value) @inherit_doc class KMeans(JavaEstimator, _KMeansParams, JavaMLWritable, JavaMLReadable): """ K-means clustering with a k-means++ like initialization mode (the k-means|| algorithm by Bahmani et al). >>> from pyspark.ml.linalg import Vectors >>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0), ... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)] >>> df = spark.createDataFrame(data, ["features", "weighCol"]) >>> kmeans = KMeans(k=2) >>> kmeans.setSeed(1) KMeans... >>> kmeans.setWeightCol("weighCol") KMeans... >>> kmeans.setMaxIter(10) KMeans... >>> kmeans.getMaxIter() 10 >>> kmeans.clear(kmeans.maxIter) >>> model = kmeans.fit(df) >>> model.getDistanceMeasure() 'euclidean' >>> model.setPredictionCol("newPrediction") KMeansModel... >>> model.predict(df.head().features) 0 >>> centers = model.clusterCenters() >>> len(centers) 2 >>> transformed = model.transform(df).select("features", "newPrediction") >>> rows = transformed.collect() >>> rows[0].newPrediction == rows[1].newPrediction True >>> rows[2].newPrediction == rows[3].newPrediction True >>> model.hasSummary True >>> summary = model.summary >>> summary.k 2 >>> summary.clusterSizes [2, 2] >>> summary.trainingCost 4.0 >>> kmeans_path = temp_path + "/kmeans" >>> kmeans.save(kmeans_path) >>> kmeans2 = KMeans.load(kmeans_path) >>> kmeans2.getK() 2 >>> model_path = temp_path + "/kmeans_model" >>> model.save(model_path) >>> model2 = KMeansModel.load(model_path) >>> model2.hasSummary False >>> model.clusterCenters()[0] == model2.clusterCenters()[0] array([ True, True], dtype=bool) >>> model.clusterCenters()[1] == model2.clusterCenters()[1] array([ True, True], dtype=bool) .. versionadded:: 1.5.0 """ @keyword_only def __init__(self, featuresCol="features", predictionCol="prediction", k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, distanceMeasure="euclidean", weightCol=None): """ __init__(self, featuresCol="features", predictionCol="prediction", k=2, \ initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, \ distanceMeasure="euclidean", weightCol=None) """ super(KMeans, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.KMeans", self.uid) self._setDefault(k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, distanceMeasure="euclidean") kwargs = self._input_kwargs self.setParams(**kwargs) def _create_model(self, java_model): return KMeansModel(java_model) @keyword_only @since("1.5.0") def setParams(self, featuresCol="features", predictionCol="prediction", k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, distanceMeasure="euclidean", weightCol=None): """ setParams(self, featuresCol="features", predictionCol="prediction", k=2, \ initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, \ distanceMeasure="euclidean", weightCol=None) Sets params for KMeans. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("1.5.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("1.5.0") def setInitMode(self, value): """ Sets the value of :py:attr:`initMode`. """ return self._set(initMode=value) @since("1.5.0") def setInitSteps(self, value): """ Sets the value of :py:attr:`initSteps`. """ return self._set(initSteps=value) @since("2.4.0") def setDistanceMeasure(self, value): """ Sets the value of :py:attr:`distanceMeasure`. """ return self._set(distanceMeasure=value) @since("1.5.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("1.5.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("1.5.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("1.5.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("1.5.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("3.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @inherit_doc class _BisectingKMeansParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasDistanceMeasure, HasWeightCol): """ Params for :py:class:`BisectingKMeans` and :py:class:`BisectingKMeansModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The desired number of leaf clusters. Must be > 1.", typeConverter=TypeConverters.toInt) minDivisibleClusterSize = Param(Params._dummy(), "minDivisibleClusterSize", "The minimum number of points (if >= 1.0) or the minimum " + "proportion of points (if < 1.0) of a divisible cluster.", typeConverter=TypeConverters.toFloat) @since("2.0.0") def getK(self): """ Gets the value of `k` or its default value. """ return self.getOrDefault(self.k) @since("2.0.0") def getMinDivisibleClusterSize(self): """ Gets the value of `minDivisibleClusterSize` or its default value. """ return self.getOrDefault(self.minDivisibleClusterSize) class BisectingKMeansModel(JavaModel, _BisectingKMeansParams, JavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by BisectingKMeans. .. versionadded:: 2.0.0 """ @since("3.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("3.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("2.0.0") def clusterCenters(self): """Get the cluster centers, represented as a list of NumPy arrays.""" return [c.toArray() for c in self._call_java("clusterCenters")] @since("2.0.0") def computeCost(self, dataset): """ Computes the sum of squared distances between the input points and their corresponding cluster centers. ..note:: Deprecated in 3.0.0. It will be removed in future versions. Use ClusteringEvaluator instead. You can also get the cost on the training dataset in the summary. """ warnings.warn("Deprecated in 3.0.0. It will be removed in future versions. Use " "ClusteringEvaluator instead. You can also get the cost on the training " "dataset in the summary.", DeprecationWarning) return self._call_java("computeCost", dataset) @property @since("2.1.0") def summary(self): """ Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists. """ if self.hasSummary: return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("3.0.0") def predict(self, value): """ Predict label for the given features. """ return self._call_java("predict", value) @inherit_doc class BisectingKMeans(JavaEstimator, _BisectingKMeansParams, JavaMLWritable, JavaMLReadable): """ A bisecting k-means algorithm based on the paper "A comparison of document clustering techniques" by Steinbach, Karypis, and Kumar, with modification to fit Spark. The algorithm starts from a single cluster that contains all points. Iteratively it finds divisible clusters on the bottom level and bisects each of them using k-means, until there are `k` leaf clusters in total or no leaf clusters are divisible. The bisecting steps of clusters on the same level are grouped together to increase parallelism. If bisecting all divisible clusters on the bottom level would result more than `k` leaf clusters, larger clusters get higher priority. >>> from pyspark.ml.linalg import Vectors >>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0), ... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)] >>> df = spark.createDataFrame(data, ["features", "weighCol"]) >>> bkm = BisectingKMeans(k=2, minDivisibleClusterSize=1.0) >>> bkm.setMaxIter(10) BisectingKMeans... >>> bkm.getMaxIter() 10 >>> bkm.clear(bkm.maxIter) >>> bkm.setSeed(1) BisectingKMeans... >>> bkm.setWeightCol("weighCol") BisectingKMeans... >>> bkm.getSeed() 1 >>> bkm.clear(bkm.seed) >>> model = bkm.fit(df) >>> model.getMaxIter() 20 >>> model.setPredictionCol("newPrediction") BisectingKMeansModel... >>> model.predict(df.head().features) 0 >>> centers = model.clusterCenters() >>> len(centers) 2 >>> model.computeCost(df) 2.0 >>> model.hasSummary True >>> summary = model.summary >>> summary.k 2 >>> summary.clusterSizes [2, 2] >>> summary.trainingCost 4.000... >>> transformed = model.transform(df).select("features", "newPrediction") >>> rows = transformed.collect() >>> rows[0].newPrediction == rows[1].newPrediction True >>> rows[2].newPrediction == rows[3].newPrediction True >>> bkm_path = temp_path + "/bkm" >>> bkm.save(bkm_path) >>> bkm2 = BisectingKMeans.load(bkm_path) >>> bkm2.getK() 2 >>> bkm2.getDistanceMeasure() 'euclidean' >>> model_path = temp_path + "/bkm_model" >>> model.save(model_path) >>> model2 = BisectingKMeansModel.load(model_path) >>> model2.hasSummary False >>> model.clusterCenters()[0] == model2.clusterCenters()[0] array([ True, True], dtype=bool) >>> model.clusterCenters()[1] == model2.clusterCenters()[1] array([ True, True], dtype=bool) .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, featuresCol="features", predictionCol="prediction", maxIter=20, seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", weightCol=None): """ __init__(self, featuresCol="features", predictionCol="prediction", maxIter=20, \ seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", \ weightCol=None) """ super(BisectingKMeans, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.BisectingKMeans", self.uid) self._setDefault(maxIter=20, k=4, minDivisibleClusterSize=1.0) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("2.0.0") def setParams(self, featuresCol="features", predictionCol="prediction", maxIter=20, seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", weightCol=None): """ setParams(self, featuresCol="features", predictionCol="prediction", maxIter=20, \ seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", \ weightCol=None) Sets params for BisectingKMeans. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.0.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("2.0.0") def setMinDivisibleClusterSize(self, value): """ Sets the value of :py:attr:`minDivisibleClusterSize`. """ return self._set(minDivisibleClusterSize=value) @since("2.4.0") def setDistanceMeasure(self, value): """ Sets the value of :py:attr:`distanceMeasure`. """ return self._set(distanceMeasure=value) @since("2.0.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("2.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("2.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("2.0.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("3.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) def _create_model(self, java_model): return BisectingKMeansModel(java_model) class BisectingKMeansSummary(ClusteringSummary): """ Bisecting KMeans clustering results for a given model. .. versionadded:: 2.1.0 """ @property @since("3.0.0") def trainingCost(self): """ Sum of squared distances to the nearest centroid for all points in the training dataset. This is equivalent to sklearn's inertia. """ return self._call_java("trainingCost") @inherit_doc class _LDAParams(HasMaxIter, HasFeaturesCol, HasSeed, HasCheckpointInterval): """ Params for :py:class:`LDA` and :py:class:`LDAModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The number of topics (clusters) to infer. Must be > 1.", typeConverter=TypeConverters.toInt) optimizer = Param(Params._dummy(), "optimizer", "Optimizer or inference algorithm used to estimate the LDA model. " "Supported: online, em", typeConverter=TypeConverters.toString) learningOffset = Param(Params._dummy(), "learningOffset", "A (positive) learning parameter that downweights early iterations." " Larger values make early iterations count less", typeConverter=TypeConverters.toFloat) learningDecay = Param(Params._dummy(), "learningDecay", "Learning rate, set as an" "exponential decay rate. This should be between (0.5, 1.0] to " "guarantee asymptotic convergence.", typeConverter=TypeConverters.toFloat) subsamplingRate = Param(Params._dummy(), "subsamplingRate", "Fraction of the corpus to be sampled and used in each iteration " "of mini-batch gradient descent, in range (0, 1].", typeConverter=TypeConverters.toFloat) optimizeDocConcentration = Param(Params._dummy(), "optimizeDocConcentration", "Indicates whether the docConcentration (Dirichlet parameter " "for document-topic distribution) will be optimized during " "training.", typeConverter=TypeConverters.toBoolean) docConcentration = Param(Params._dummy(), "docConcentration", "Concentration parameter (commonly named \"alpha\") for the " "prior placed on documents' distributions over topics (\"theta\").", typeConverter=TypeConverters.toListFloat) topicConcentration = Param(Params._dummy(), "topicConcentration", "Concentration parameter (commonly named \"beta\" or \"eta\") for " "the prior placed on topic' distributions over terms.", typeConverter=TypeConverters.toFloat) topicDistributionCol = Param(Params._dummy(), "topicDistributionCol", "Output column with estimates of the topic mixture distribution " "for each document (often called \"theta\" in the literature). " "Returns a vector of zeros for an empty document.", typeConverter=TypeConverters.toString) keepLastCheckpoint = Param(Params._dummy(), "keepLastCheckpoint", "(For EM optimizer) If using checkpointing, this indicates whether" " to keep the last checkpoint. If false, then the checkpoint will be" " deleted. Deleting the checkpoint can cause failures if a data" " partition is lost, so set this bit with care.", TypeConverters.toBoolean) @since("2.0.0") def getK(self): """ Gets the value of :py:attr:`k` or its default value. """ return self.getOrDefault(self.k) @since("2.0.0") def getOptimizer(self): """ Gets the value of :py:attr:`optimizer` or its default value. """ return self.getOrDefault(self.optimizer) @since("2.0.0") def getLearningOffset(self): """ Gets the value of :py:attr:`learningOffset` or its default value. """ return self.getOrDefault(self.learningOffset) @since("2.0.0") def getLearningDecay(self): """ Gets the value of :py:attr:`learningDecay` or its default value. """ return self.getOrDefault(self.learningDecay) @since("2.0.0") def getSubsamplingRate(self): """ Gets the value of :py:attr:`subsamplingRate` or its default value. """ return self.getOrDefault(self.subsamplingRate) @since("2.0.0") def getOptimizeDocConcentration(self): """ Gets the value of :py:attr:`optimizeDocConcentration` or its default value. """ return self.getOrDefault(self.optimizeDocConcentration) @since("2.0.0") def getDocConcentration(self): """ Gets the value of :py:attr:`docConcentration` or its default value. """ return self.getOrDefault(self.docConcentration) @since("2.0.0") def getTopicConcentration(self): """ Gets the value of :py:attr:`topicConcentration` or its default value. """ return self.getOrDefault(self.topicConcentration) @since("2.0.0") def getTopicDistributionCol(self): """ Gets the value of :py:attr:`topicDistributionCol` or its default value. """ return self.getOrDefault(self.topicDistributionCol) @since("2.0.0") def getKeepLastCheckpoint(self): """ Gets the value of :py:attr:`keepLastCheckpoint` or its default value. """ return self.getOrDefault(self.keepLastCheckpoint) @inherit_doc class LDAModel(JavaModel, _LDAParams): """ Latent Dirichlet Allocation (LDA) model. This abstraction permits for different underlying representations, including local and distributed data structures. .. versionadded:: 2.0.0 """ @since("3.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("3.0.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("3.0.0") def setTopicDistributionCol(self, value): """ Sets the value of :py:attr:`topicDistributionCol`. """ return self._set(topicDistributionCol=value) @since("2.0.0") def isDistributed(self): """ Indicates whether this instance is of type DistributedLDAModel """ return self._call_java("isDistributed") @since("2.0.0") def vocabSize(self): """Vocabulary size (number of terms or words in the vocabulary)""" return self._call_java("vocabSize") @since("2.0.0") def topicsMatrix(self): """ Inferred topics, where each topic is represented by a distribution over terms. This is a matrix of size vocabSize x k, where each column is a topic. No guarantees are given about the ordering of the topics. WARNING: If this model is actually a :py:class:`DistributedLDAModel` instance produced by the Expectation-Maximization ("em") `optimizer`, then this method could involve collecting a large amount of data to the driver (on the order of vocabSize x k). """ return self._call_java("topicsMatrix") @since("2.0.0") def logLikelihood(self, dataset): """ Calculates a lower bound on the log likelihood of the entire corpus. See Equation (16) in the Online LDA paper (Hoffman et al., 2010). WARNING: If this model is an instance of :py:class:`DistributedLDAModel` (produced when :py:attr:`optimizer` is set to "em"), this involves collecting a large :py:func:`topicsMatrix` to the driver. This implementation may be changed in the future. """ return self._call_java("logLikelihood", dataset) @since("2.0.0") def logPerplexity(self, dataset): """ Calculate an upper bound on perplexity. (Lower is better.) See Equation (16) in the Online LDA paper (Hoffman et al., 2010). WARNING: If this model is an instance of :py:class:`DistributedLDAModel` (produced when :py:attr:`optimizer` is set to "em"), this involves collecting a large :py:func:`topicsMatrix` to the driver. This implementation may be changed in the future. """ return self._call_java("logPerplexity", dataset) @since("2.0.0") def describeTopics(self, maxTermsPerTopic=10): """ Return the topics described by their top-weighted terms. """ return self._call_java("describeTopics", maxTermsPerTopic) @since("2.0.0") def estimatedDocConcentration(self): """ Value for :py:attr:`LDA.docConcentration` estimated from data. If Online LDA was used and :py:attr:`LDA.optimizeDocConcentration` was set to false, then this returns the fixed (given) value for the :py:attr:`LDA.docConcentration` parameter. """ return self._call_java("estimatedDocConcentration") @inherit_doc class DistributedLDAModel(LDAModel, JavaMLReadable, JavaMLWritable): """ Distributed model fitted by :py:class:`LDA`. This type of model is currently only produced by Expectation-Maximization (EM). This model stores the inferred topics, the full training dataset, and the topic distribution for each training document. .. versionadded:: 2.0.0 """ @since("2.0.0") def toLocal(self): """ Convert this distributed model to a local representation. This discards info about the training dataset. WARNING: This involves collecting a large :py:func:`topicsMatrix` to the driver. """ model = LocalLDAModel(self._call_java("toLocal")) # SPARK-10931: Temporary fix to be removed once LDAModel defines Params model._create_params_from_java() model._transfer_params_from_java() return model @since("2.0.0") def trainingLogLikelihood(self): """ Log likelihood of the observed tokens in the training set, given the current parameter estimates: log P(docs | topics, topic distributions for docs, Dirichlet hyperparameters) Notes: - This excludes the prior; for that, use :py:func:`logPrior`. - Even with :py:func:`logPrior`, this is NOT the same as the data log likelihood given the hyperparameters. - This is computed from the topic distributions computed during training. If you call :py:func:`logLikelihood` on the same training dataset, the topic distributions will be computed again, possibly giving different results. """ return self._call_java("trainingLogLikelihood") @since("2.0.0") def logPrior(self): """ Log probability of the current parameter estimate: log P(topics, topic distributions for docs | alpha, eta) """ return self._call_java("logPrior") @since("2.0.0") def getCheckpointFiles(self): """ If using checkpointing and :py:attr:`LDA.keepLastCheckpoint` is set to true, then there may be saved checkpoint files. This method is provided so that users can manage those files. .. note:: Removing the checkpoints can cause failures if a partition is lost and is needed by certain :py:class:`DistributedLDAModel` methods. Reference counting will clean up the checkpoints when this model and derivative data go out of scope. :return List of checkpoint files from training """ return self._call_java("getCheckpointFiles") @inherit_doc class LocalLDAModel(LDAModel, JavaMLReadable, JavaMLWritable): """ Local (non-distributed) model fitted by :py:class:`LDA`. This model stores the inferred topics only; it does not store info about the training dataset. .. versionadded:: 2.0.0 """ pass @inherit_doc class LDA(JavaEstimator, _LDAParams, JavaMLReadable, JavaMLWritable): """ Latent Dirichlet Allocation (LDA), a topic model designed for text documents. Terminology: - "term" = "word": an element of the vocabulary - "token": instance of a term appearing in a document - "topic": multinomial distribution over terms representing some concept - "document": one piece of text, corresponding to one row in the input data Original LDA paper (journal version): Blei, Ng, and Jordan. "Latent Dirichlet Allocation." JMLR, 2003. Input data (featuresCol): LDA is given a collection of documents as input data, via the featuresCol parameter. Each document is specified as a :py:class:`Vector` of length vocabSize, where each entry is the count for the corresponding term (word) in the document. Feature transformers such as :py:class:`pyspark.ml.feature.Tokenizer` and :py:class:`pyspark.ml.feature.CountVectorizer` can be useful for converting text to word count vectors. >>> from pyspark.ml.linalg import Vectors, SparseVector >>> from pyspark.ml.clustering import LDA >>> df = spark.createDataFrame([[1, Vectors.dense([0.0, 1.0])], ... [2, SparseVector(2, {0: 1.0})],], ["id", "features"]) >>> lda = LDA(k=2, seed=1, optimizer="em") >>> lda.setMaxIter(10) LDA... >>> lda.getMaxIter() 10 >>> lda.clear(lda.maxIter) >>> model = lda.fit(df) >>> model.setSeed(1) DistributedLDAModel... >>> model.getTopicDistributionCol() 'topicDistribution' >>> model.isDistributed() True >>> localModel = model.toLocal() >>> localModel.isDistributed() False >>> model.vocabSize() 2 >>> model.describeTopics().show() +-----+-----------+--------------------+ |topic|termIndices| termWeights| +-----+-----------+--------------------+ | 0| [1, 0]|[0.50401530077160...| | 1| [0, 1]|[0.50401530077160...| +-----+-----------+--------------------+ ... >>> model.topicsMatrix() DenseMatrix(2, 2, [0.496, 0.504, 0.504, 0.496], 0) >>> lda_path = temp_path + "/lda" >>> lda.save(lda_path) >>> sameLDA = LDA.load(lda_path) >>> distributed_model_path = temp_path + "/lda_distributed_model" >>> model.save(distributed_model_path) >>> sameModel = DistributedLDAModel.load(distributed_model_path) >>> local_model_path = temp_path + "/lda_local_model" >>> localModel.save(local_model_path) >>> sameLocalModel = LocalLDAModel.load(local_model_path) .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10, k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, subsamplingRate=0.05, optimizeDocConcentration=True, docConcentration=None, topicConcentration=None, topicDistributionCol="topicDistribution", keepLastCheckpoint=True): """ __init__(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10,\ k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51,\ subsamplingRate=0.05, optimizeDocConcentration=True,\ docConcentration=None, topicConcentration=None,\ topicDistributionCol="topicDistribution", keepLastCheckpoint=True) """ super(LDA, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.LDA", self.uid) self._setDefault(maxIter=20, checkpointInterval=10, k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, subsamplingRate=0.05, optimizeDocConcentration=True, topicDistributionCol="topicDistribution", keepLastCheckpoint=True) kwargs = self._input_kwargs self.setParams(**kwargs) def _create_model(self, java_model): if self.getOptimizer() == "em": return DistributedLDAModel(java_model) else: return LocalLDAModel(java_model) @keyword_only @since("2.0.0") def setParams(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10, k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, subsamplingRate=0.05, optimizeDocConcentration=True, docConcentration=None, topicConcentration=None, topicDistributionCol="topicDistribution", keepLastCheckpoint=True): """ setParams(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10,\ k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51,\ subsamplingRate=0.05, optimizeDocConcentration=True,\ docConcentration=None, topicConcentration=None,\ topicDistributionCol="topicDistribution", keepLastCheckpoint=True) Sets params for LDA. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.0.0") def setCheckpointInterval(self, value): """ Sets the value of :py:attr:`checkpointInterval`. """ return self._set(checkpointInterval=value) @since("2.0.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("2.0.0") def setK(self, value): """ Sets the value of :py:attr:`k`. >>> algo = LDA().setK(10) >>> algo.getK() 10 """ return self._set(k=value) @since("2.0.0") def setOptimizer(self, value): """ Sets the value of :py:attr:`optimizer`. Currently only support 'em' and 'online'. >>> algo = LDA().setOptimizer("em") >>> algo.getOptimizer() 'em' """ return self._set(optimizer=value) @since("2.0.0") def setLearningOffset(self, value): """ Sets the value of :py:attr:`learningOffset`. >>> algo = LDA().setLearningOffset(100) >>> algo.getLearningOffset() 100.0 """ return self._set(learningOffset=value) @since("2.0.0") def setLearningDecay(self, value): """ Sets the value of :py:attr:`learningDecay`. >>> algo = LDA().setLearningDecay(0.1) >>> algo.getLearningDecay() 0.1... """ return self._set(learningDecay=value) @since("2.0.0") def setSubsamplingRate(self, value): """ Sets the value of :py:attr:`subsamplingRate`. >>> algo = LDA().setSubsamplingRate(0.1) >>> algo.getSubsamplingRate() 0.1... """ return self._set(subsamplingRate=value) @since("2.0.0") def setOptimizeDocConcentration(self, value): """ Sets the value of :py:attr:`optimizeDocConcentration`. >>> algo = LDA().setOptimizeDocConcentration(True) >>> algo.getOptimizeDocConcentration() True """ return self._set(optimizeDocConcentration=value) @since("2.0.0") def setDocConcentration(self, value): """ Sets the value of :py:attr:`docConcentration`. >>> algo = LDA().setDocConcentration([0.1, 0.2]) >>> algo.getDocConcentration() [0.1..., 0.2...] """ return self._set(docConcentration=value) @since("2.0.0") def setTopicConcentration(self, value): """ Sets the value of :py:attr:`topicConcentration`. >>> algo = LDA().setTopicConcentration(0.5) >>> algo.getTopicConcentration() 0.5... """ return self._set(topicConcentration=value) @since("2.0.0") def setTopicDistributionCol(self, value): """ Sets the value of :py:attr:`topicDistributionCol`. >>> algo = LDA().setTopicDistributionCol("topicDistributionCol") >>> algo.getTopicDistributionCol() 'topicDistributionCol' """ return self._set(topicDistributionCol=value) @since("2.0.0") def setKeepLastCheckpoint(self, value): """ Sets the value of :py:attr:`keepLastCheckpoint`. >>> algo = LDA().setKeepLastCheckpoint(False) >>> algo.getKeepLastCheckpoint() False """ return self._set(keepLastCheckpoint=value) @since("2.0.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("2.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @inherit_doc class _PowerIterationClusteringParams(HasMaxIter, HasWeightCol): """ Params for :py:class:`PowerIterationClustering`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The number of clusters to create. Must be > 1.", typeConverter=TypeConverters.toInt) initMode = Param(Params._dummy(), "initMode", "The initialization algorithm. This can be either " + "'random' to use a random vector as vertex properties, or 'degree' to use " + "a normalized sum of similarities with other vertices. Supported options: " + "'random' and 'degree'.", typeConverter=TypeConverters.toString) srcCol = Param(Params._dummy(), "srcCol", "Name of the input column for source vertex IDs.", typeConverter=TypeConverters.toString) dstCol = Param(Params._dummy(), "dstCol", "Name of the input column for destination vertex IDs.", typeConverter=TypeConverters.toString) @since("2.4.0") def getK(self): """ Gets the value of :py:attr:`k` or its default value. """ return self.getOrDefault(self.k) @since("2.4.0") def getInitMode(self): """ Gets the value of :py:attr:`initMode` or its default value. """ return self.getOrDefault(self.initMode) @since("2.4.0") def getSrcCol(self): """ Gets the value of :py:attr:`srcCol` or its default value. """ return self.getOrDefault(self.srcCol) @since("2.4.0") def getDstCol(self): """ Gets the value of :py:attr:`dstCol` or its default value. """ return self.getOrDefault(self.dstCol) @inherit_doc class PowerIterationClustering(_PowerIterationClusteringParams, JavaParams, JavaMLReadable, JavaMLWritable): """ Power Iteration Clustering (PIC), a scalable graph clustering algorithm developed by `Lin and Cohen <http://www.cs.cmu.edu/~frank/papers/icml2010-pic-final.pdf>`_. From the abstract: PIC finds a very low-dimensional embedding of a dataset using truncated power iteration on a normalized pair-wise similarity matrix of the data. This class is not yet an Estimator/Transformer, use :py:func:`assignClusters` method to run the PowerIterationClustering algorithm. .. seealso:: `Wikipedia on Spectral clustering <http://en.wikipedia.org/wiki/Spectral_clustering>`_ >>> data = [(1, 0, 0.5), ... (2, 0, 0.5), (2, 1, 0.7), ... (3, 0, 0.5), (3, 1, 0.7), (3, 2, 0.9), ... (4, 0, 0.5), (4, 1, 0.7), (4, 2, 0.9), (4, 3, 1.1), ... (5, 0, 0.5), (5, 1, 0.7), (5, 2, 0.9), (5, 3, 1.1), (5, 4, 1.3)] >>> df = spark.createDataFrame(data).toDF("src", "dst", "weight").repartition(1) >>> pic = PowerIterationClustering(k=2, weightCol="weight") >>> pic.setMaxIter(40) PowerIterationClustering... >>> assignments = pic.assignClusters(df) >>> assignments.sort(assignments.id).show(truncate=False) +---+-------+ |id |cluster| +---+-------+ |0 |0 | |1 |0 | |2 |0 | |3 |0 | |4 |0 | |5 |1 | +---+-------+ ... >>> pic_path = temp_path + "/pic" >>> pic.save(pic_path) >>> pic2 = PowerIterationClustering.load(pic_path) >>> pic2.getK() 2 >>> pic2.getMaxIter() 40 .. versionadded:: 2.4.0 """ @keyword_only def __init__(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst", weightCol=None): """ __init__(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst",\ weightCol=None) """ super(PowerIterationClustering, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.clustering.PowerIterationClustering", self.uid) self._setDefault(k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst") kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("2.4.0") def setParams(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst", weightCol=None): """ setParams(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst",\ weightCol=None) Sets params for PowerIterationClustering. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.4.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("2.4.0") def setInitMode(self, value): """ Sets the value of :py:attr:`initMode`. """ return self._set(initMode=value) @since("2.4.0") def setSrcCol(self, value): """ Sets the value of :py:attr:`srcCol`. """ return self._set(srcCol=value) @since("2.4.0") def setDstCol(self, value): """ Sets the value of :py:attr:`dstCol`. """ return self._set(dstCol=value) @since("2.4.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("2.4.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @since("2.4.0") def assignClusters(self, dataset): """ Run the PIC algorithm and returns a cluster assignment for each input vertex. :param dataset: A dataset with columns src, dst, weight representing the affinity matrix, which is the matrix A in the PIC paper. Suppose the src column value is i, the dst column value is j, the weight column value is similarity s,,ij,, which must be nonnegative. This is a symmetric matrix and hence s,,ij,, = s,,ji,,. For any (i, j) with nonzero similarity, there should be either (i, j, s,,ij,,) or (j, i, s,,ji,,) in the input. Rows with i = j are ignored, because we assume s,,ij,, = 0.0. :return: A dataset that contains columns of vertex id and the corresponding cluster for the id. The schema of it will be: - id: Long - cluster: Int .. versionadded:: 2.4.0 """ self._transfer_params_to_java() jdf = self._java_obj.assignClusters(dataset._jdf) return DataFrame(jdf, dataset.sql_ctx) if __name__ == "__main__": import doctest import numpy import pyspark.ml.clustering from pyspark.sql import SparkSession try: # Numpy 1.14+ changed it's string format. numpy.set_printoptions(legacy='1.13') except TypeError: pass globs = pyspark.ml.clustering.__dict__.copy() # The small batch size here ensures that we see multiple batches, # even in these small test examples: spark = SparkSession.builder\ .master("local[2]")\ .appName("ml.clustering tests")\ .getOrCreate() sc = spark.sparkContext globs['sc'] = sc globs['spark'] = spark import tempfile temp_path = tempfile.mkdtemp() globs['temp_path'] = temp_path try: (failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS) spark.stop() finally: from shutil import rmtree try: rmtree(temp_path) except OSError: pass if failure_count: sys.exit(-1)
ptkool/spark
python/pyspark/ml/clustering.py
Python
apache-2.0
60,729
[ "Gaussian" ]
f9b970df6a6a30656c81f679fe7666a996163090eb6f269027c97e4fa8aceff5
#!/usr/bin/env python3 #pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import vtk import chigger camera = vtk.vtkCamera() camera.SetViewUp(-0.01297019406812408, 0.87867984226827, 0.4772352762079132) camera.SetPosition(10.331000991784688, -5.473421359648077, 10.483371124667542) camera.SetFocalPoint(0.16947273724857123, 0.07124492441302266, -0.0015694043706061533) reader = chigger.exodus.ExodusReader('../../input/mug_blocks_out.e') mug = chigger.exodus.ExodusResult(reader, block=['76'], variable='convected', cmap='viridis', camera=camera) window = chigger.RenderWindow(mug, size=[300,300], test=True) window.write('blocks.png') window.start()
nuclear-wizard/moose
python/chigger/tests/exodus/blocks/blocks.py
Python
lgpl-2.1
945
[ "MOOSE", "VTK" ]
8e6dc58d94d37894441ad9f71877d2469d699c2d7f935c37b4566fd77a7de9ee
""" Module that parses global parameters from a configuration file at first import, to make them available to the other parts of the program. """ import ConfigParser import os import glob import json import datetime as dt import numpy as np # cPickle is faster than pickle but doesn't always import correctly. try: import cPickle as pickle except: import pickle cnf_path = os.path.join(os.getcwd(), 'configs') print cnf_path def cnf_list(cnf_path, ext='cnf'): return glob.glob(os.path.join(cnf_path, u'*.{}'.format(ext))) def create_config_list(basedir=os.path.join(os.getcwd(), 'configs'), ext='cnf', verbose=True): """ Function that runs the individual .cnf file if only one exists, otherwise checks for AUTOMATE option in the .cnf and if any of the .cnf files have AUTOMATE = True then both will run in sequence (in named order of .cnf files), finally run an user input if there is more than one .cnf file and ALL state AUTOMATE = False This function will return a list of only the .cnf files to be processed """ config_files = cnf_list(basedir, ext='cnf') condition = False config = ConfigParser.ConfigParser() for config_file in config_files: print 'config_file: ', config_file config.read(config_file) AUTOMATE = config.getboolean('automate', 'AUTOMATE') if AUTOMATE: condition = True if condition or len(config_files) == 1: # if automate is set in ANY of the control files, the the whole list # will be returned! config_list = config_files elif len(config_files) == 1: raise Exception('There are no configuration files in the \ ./configs/ folder') else: # run user input if automation is False for ALL files. print "Please select a configuration file:" for i, f in enumerate(config_files, start=1): print "{} - {}".format(i, os.path.basename(f)) res = int(raw_input('')) config_file = config_files[res - 1] config_list = [config_file] return config_list def shift(xcorr_len): a = 10.0 / 837.0 b = 3.0e4 / 31.0 shift_len = int(a * xcorr_len + b) return shift_len class Config: """ The following class contains all the required configuration information required to process the whole set of applications! """ def __init__(self, config_file): # initialise config file parser object self.config = ConfigParser.ConfigParser() self.config.read(config_file) # initialise ALL configuration variables on definition of class! # ----- # paths # ----- self.AUTOMATE = self.config.getboolean('automate', 'AUTOMATE') self.FOLDER = self.config.get('paths', 'FOLDER') #TIMELINE_DB = config.get('paths', 'TIMELINE_DB') #RESPONSE_DB = config.get('paths', 'RESPONSE_DB') # input dirs if self.FOLDER == "DEFAULT": #fold = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) fold = os.getcwd() self.MSEED_DIR = "{}/INPUT/DATA".format(fold) self.STATIONXML_DIR = "{}/INPUT/XML".format(fold) self.DATALESS_DIR = "{}/INPUT/DATALESS".format(fold) self.DATABASE_DIR = "{}/INPUT/DATABASES".format(fold) # output dirs self.CROSSCORR_DIR = "{}/OUTPUT/CROSS".format(fold) self.FTAN_DIR = "{}/OUTPUT/FTAN".format(fold) self.TOMO_DIR = "{}/OUTPUT/TOMO".format(fold) self.DEPTHMODELS_DIR = "{}/OUTPUT/DEPTH".format(fold) else: self.MSEED_DIR = "{}/INPUT/DATA".format(self.FOLDER) self.STATIONXML_DIR = "{}/INPUT/XML".format(self.FOLDER) self.DATALESS_DIR = "{}/INPUT/DATALESS".format(self.FOLDER) self.DATABASE_DIR = "{}/INPUT/DATABASES".format(self.FOLDER) # output dirs self.CROSSCORR_DIR = "{}/OUTPUT/CROSS".format(self.FOLDER) self.FTAN_DIR = "{}/OUTPUT/FTAN".format(self.FOLDER) self.TOMO_DIR = "{}/OUTPUT/TOMO".format(self.FOLDER) self.DEPTHMODELS_DIR = "{}/OUTPUT/DEPTH".format(self.FOLDER) # dir of the Computer Programs in Seismology (can be None) self.COMPUTER_PROGRAMS_IN_SEISMOLOGY_DIR = \ self.config.get('paths', 'COMPUTER_PROGRAMS_IN_SEISMOLOGY_DIR') #=========== # processing #=========== #set the individual preprocessing techniques that you want performed on your analysis. Each # must be set either True or False to work. Any other options with give an error self.MAX_DISTANCE = self.config.get('processing', 'MAX_DISTANCE') self.TDD = self.config.getboolean('processing', 'TDD') #self.EVENT_REMOVE = self.config.getboolean('processing', # 'EVENT_REMOVE') self.RESP_REMOVE = self.config.getboolean('processing', 'RESP_REMOVE') self.HIGHAMP_REMOVE = self.config.getboolean('processing', 'HIGHAMP_REMOVE') self.RESP_CHECK = self.config.getboolean('processing', 'RESP_CHECK') self.RESP_RANGE = json.loads(self.config.get('processing', 'RESP_RANGE')) self.RESP_FREQS = [1./max(self.RESP_RANGE), 1./min(self.RESP_RANGE)] self.RESP_TOL = self.config.getfloat('processing', 'RESP_TOL') self.RESP_EFFECT = self.config.getfloat('processing', 'RESP_EFFECT') self.BANDPASS = self.config.getboolean('processing', 'BANDPASS') self.DOWNSAMPLE = self.config.getboolean('processing', 'DOWNSAMPLE') self.COMPLETENESS = self.config.getboolean('processing', 'COMPLETENESS') self.TIME_NOMALISATION = self.config.getboolean('processing', 'TIME_NOMALISATION') self.SPEC_WHITENING = self.config.getboolean('processing', 'SPEC_WHITENING') self.FULL_COMB = self.config.getboolean('processing', 'FULL_COMB') # --------------- # maps parameters # --------------- # paths to shapefiles (coasts, tectonic provinces and labels) self.COAST_SHP = self.config.get('maps', 'COAST_SHP') self.TECTO_SHP = self.config.get('maps', 'TECTO_SHP') self.TECTO_LABELS = self.config.get('maps', 'TECTO_LABELS') # colors of tectonic provinces self.TECTO_COLORS = json.loads(self.config.get('maps', 'TECTO_COLORS')) # bounding boxes self.BBOX_LARGE = json.loads(self.config.get('maps', 'BBOX_LARGE')) self.BBOX_SMALL = json.loads(self.config.get('maps', 'BBOX_SMALL')) # -------------------------------------- # cross-correlation / spectra parameters # -------------------------------------- self.RANDOM_STACK = self.config.getboolean('cross-correlation', 'RANDOM_STACK') # use dataless files or stationXML files to remove instrument response? self.USE_DATALESSPAZ = self.config.getboolean('cross-correlation', 'USE_DATALESSPAZ') self.USE_STATIONXML = self.config.getboolean('cross-correlation', 'USE_STATIONXML') # subset of stations to cross-correlate self.CROSSCORR_STATIONS_SUBSET = \ self.config.get('cross-correlation', 'CROSSCORR_STATIONS_SUBSET') self.CROSSCORR_STATIONS_SUBSET = \ json.loads(self.CROSSCORR_STATIONS_SUBSET) # locations to skip self.CROSSCORR_SKIPLOCS = \ json.loads(self.config.get('cross-correlation', 'CROSSCORR_SKIPLOCS')) #GET RID OF .day() for FIRSTDAY and LASTDAY variables. #This is is to allow for the interval to be a datetime object rather than just #a date object! # first and last day, minimum data fill per day self.FIRSTDAY = self.config.get('cross-correlation', 'FIRSTDAY') self.FIRSTDAY = dt.datetime.strptime(self.FIRSTDAY, '%d/%m/%Y') self.LASTDAY = self.config.get('cross-correlation', 'LASTDAY') self.LASTDAY = dt.datetime.strptime(self.LASTDAY, '%d/%m/%Y') self.MINFILL = self.config.getfloat('cross-correlation', 'MINFILL') # band-pass parameters self.PERIODMIN = self.config.getfloat('cross-correlation', 'PERIODMIN') self.PERIODMAX = self.config.getfloat('cross-correlation', 'PERIODMAX') self.FREQMIN = 1.0 / self.PERIODMAX self.FREQMAX = 1.0 / self.PERIODMIN self.CORNERS = self.config.getint('cross-correlation', 'CORNERS') self.ZEROPHASE = self.config.getboolean('cross-correlation', 'ZEROPHASE') # resample period (to decimate traces, after band-pass) self.PERIOD_RESAMPLE = self.config.getfloat('cross-correlation', 'PERIOD_RESAMPLE') # Time-normalization parameters: self.ONEBIT_NORM = self.config.getboolean('cross-correlation', 'ONEBIT_NORM') # earthquakes period bands self.PERIODMIN_EARTHQUAKE = self.config.getfloat('cross-correlation', 'PERIODMIN_EARTHQUAKE') self.PERIODMAX_EARTHQUAKE = self.config.getfloat('cross-correlation', 'PERIODMAX_EARTHQUAKE') self.FREQMIN_EARTHQUAKE = 1.0 / self.PERIODMAX_EARTHQUAKE self.FREQMAX_EARTHQUAKE = 1.0 / self.PERIODMIN_EARTHQUAKE # time window (s) to smooth data in earthquake band # and calculate time-norm weights self.WINDOW_TIME = 0.5 * self.PERIODMAX_EARTHQUAKE # frequency window (Hz) to smooth ampl spectrum # and calculate spect withening weights self.WINDOW_FREQ = self.config.getfloat('cross-correlation', 'WINDOW_FREQ') #45 minute long xcorr time intervals for superior SNR self.XCORR_INTERVAL = self.config.getfloat('cross-correlation', 'XCORR_INTERVAL') # Max time window (s) for cross-correlation #set this to automatic based on function shift() above. try: self.CROSSCORR_TMAX = self.config.getfloat('cross-correlation', 'CROSSCORR_TMAX') except: self.CROSSCORR_TMAX = shift(self.XCORR_INTERVAL * 60.0) self.PLOT_CLASSIC = self.config.getboolean('cross-correlation', 'PLOT_CLASSIC') self.PLOT_DISTANCE = self.config.getboolean('cross-correlation', 'PLOT_DISTANCE') # --------------- # FTAN parameters # --------------- # default period bands, used to: # - plot cross-correlation by period bands, in plot_FTAN(), # - plot_by_period_bands() # - plot spectral SNR, in plot_spectral_SNR() # - estimate min spectral SNR, in FTANs() self.PERIOD_BANDS = json.loads(self.config.get('FTAN', 'PERIOD_BANDS')) # default parameters to define the signal and noise windows used to # estimate the SNR: # - the signal window is defined according to a min and a max velocity as: # dist/vmax < t < dist/vmin # - the noise window has a fixed size and starts after a fixed trailing # time from the end of the signal window self.SIGNAL_WINDOW_VMIN = self.config.getfloat('FTAN', 'SIGNAL_WINDOW_VMIN') self.SIGNAL_WINDOW_VMAX = self.config.getfloat('FTAN', 'SIGNAL_WINDOW_VMAX') self.SIGNAL2NOISE_TRAIL = self.config.getfloat('FTAN', 'SIGNAL2NOISE_TRAIL') self.NOISE_WINDOW_SIZE = self.config.getfloat('FTAN', 'NOISE_WINDOW_SIZE') # smoothing parameter of FTAN analysis self.FTAN_ALPHA = self.config.getfloat('FTAN', 'FTAN_ALPHA') # periods and velocities of FTAN analysis self.RAWFTAN_PERIODS_STARTSTOPSTEP = \ self.config.get('FTAN', 'RAWFTAN_PERIODS_STARTSTOPSTEP') self.RAWFTAN_PERIODS_STARTSTOPSTEP = \ json.loads(self.RAWFTAN_PERIODS_STARTSTOPSTEP) self.RAWFTAN_PERIODS = np.arange(*self.RAWFTAN_PERIODS_STARTSTOPSTEP) self.CLEANFTAN_PERIODS_STARTSTOPSTEP = \ self.config.get('FTAN', 'CLEANFTAN_PERIODS_STARTSTOPSTEP') self.CLEANFTAN_PERIODS_STARTSTOPSTEP = \ json.loads(self.CLEANFTAN_PERIODS_STARTSTOPSTEP) self.CLEANFTAN_PERIODS = \ np.arange(*self.CLEANFTAN_PERIODS_STARTSTOPSTEP) self.FTAN_VELOCITIES_STARTSTOPSTEP = \ self.config.get('FTAN', 'FTAN_VELOCITIES_STARTSTOPSTEP') self.FTAN_VELOCITIES_STARTSTOPSTEP = \ json.loads(self.FTAN_VELOCITIES_STARTSTOPSTEP) self.FTAN_VELOCITIES = np.arange(*self.FTAN_VELOCITIES_STARTSTOPSTEP) self.FTAN_VELOCITIES_STEP = self.FTAN_VELOCITIES_STARTSTOPSTEP[2] # relative strength of the smoothing term in the penalty function that # the dispersion curve seeks to minimize self.STRENGTH_SMOOTHING = self.config.getfloat('FTAN', 'STRENGTH_SMOOTHING') # replace nominal frequancy (i.e., center frequency of Gaussian filters) # with instantaneous frequency (i.e., dphi/dt(t=arrival time) with phi the # phase of the filtered analytic signal), in the FTAN and dispersion curves? # See Bensen et al. (2007) for technical details. self.USE_INSTANTANEOUS_FREQ = \ self.config.getboolean('FTAN', 'USE_INSTANTANEOUS_FREQ') # if the instantaneous frequency (or period) is used, we need to discard bad # values from instantaneous periods. So: # - instantaneous periods whose relative difference with respect to # nominal period is greater than ``MAX_RELDIFF_INST_NOMINAL_PERIOD`` # are discarded, # - instantaneous periods lower than ``MIN_INST_PERIOD`` are discarded, # - instantaneous periods whose relative difference with respect to the # running median is greater than ``MAX_RELDIFF_INST_MEDIAN_PERIOD`` are # discarded; the running median is calculated over # ``HALFWINDOW_MEDIAN_PERIOD`` points to the right and to the left # of each period. self.MAX_RELDIFF_INST_NOMINAL_PERIOD = \ self.config.getfloat('FTAN', 'MAX_RELDIFF_INST_NOMINAL_PERIOD') self.MIN_INST_PERIOD = self.config.getfloat('FTAN', 'MIN_INST_PERIOD') self.HALFWINDOW_MEDIAN_PERIOD = \ self.config.getint('FTAN', 'HALFWINDOW_MEDIAN_PERIOD') self.MAX_RELDIFF_INST_MEDIAN_PERIOD = \ self.config.getfloat('FTAN', 'MAX_RELDIFF_INST_MEDIAN_PERIOD') # -------------------------------- # Tomographic inversion parameters # -------------------------------- # Default parameters related to the velocity selection criteria # min spectral SNR to retain velocity self.MINSPECTSNR = self.config.getfloat('tomography', 'MINSPECTSNR') # min spectral SNR to retain velocity if no std dev self.MINSPECTSNR_NOSDEV = self.config.getfloat('tomography', 'MINSPECTSNR_NOSDEV') # max sdt dev (km/s) to retain velocity self.MAXSDEV = self.config.getfloat('tomography', 'MAXSDEV') # min nb of trimesters to estimate std dev self.MINNBTRIMESTER = self.config.getint('tomography', 'MINNBTRIMESTER') # max period = *MAXPERIOD_FACTOR* * pair distance self.MAXPERIOD_FACTOR = self.config.getfloat('tomography', 'MAXPERIOD_FACTOR') # Default internode spacing of grid self.LONSTEP = self.config.getfloat('tomography', 'LONSTEP') self.LATSTEP = self.config.getfloat('tomography', 'LATSTEP') # Default correlation length of the smoothing kernel: # S(r,r') = exp[-|r-r'|**2 / (2 * correlation_length**2)] self.CORRELATION_LENGTH = self.config.getfloat('tomography', 'CORRELATION_LENGTH') # Default strength of the spatial smoothing term (alpha) and the # weighted norm penalisation term (beta) in the penalty function self.ALPHA = self.config.getfloat('tomography', 'ALPHA') self.BETA = self.config.getfloat('tomography', 'BETA') # Default parameter in the damping factor of the norm penalization term, # such that the norm is weighted by exp(- lambda_*path_density) # With a value of 0.15, penalisation strong when path density < ~20 # With a value of 0.30, penalisation strong when path density < ~10 self.LAMBDA = self.config.getfloat('tomography', 'LAMBDA') def run_config(config_file): """ Function that inialises an instance of the Config class with a given input config file path, and then saves a temporary pickle dump of that class for reference from other scripts! This class dump will contain all global variables inside the Config class! """ # set tmp_config.pickle to be saved in the same config file directory root_config = os.path.dirname(config_file) pickle_path = os.path.join(root_config, 'tmp_config.pickle') # initialise the config class with the desired config file CONFIG = Config(config_file) with open(pickle_path, 'wb') as f: print '\nSaving temporary configuration variables ... ' pickle.dump(CONFIG, f, protocol=2) def remove_config(config_file): """ Function that removes only the 'tmp_config.pickle' file in order to both end the current processing configuration loop, and allow the next one to begin fresh. """ # set tmp_config.pickle to be saved in the same config file directory root_config = os.path.dirname(config_file) pickle_path = os.path.join(root_config, 'tmp_config.pickle') os.remove(pickle_path)
boland1992/seissuite_iran
build/lib/seissuite/ant/psconfig.py
Python
gpl-3.0
19,875
[ "Gaussian" ]
18cb4afb74782b87e1f6aa6f44d159f15c34bf6fca89e2f9896558a090a36acb
# AvsP - an AviSynth editor # # Copyright 2012, 2013 the AvsPmod authors <https://github.com/avspmod/avspmod> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # 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, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit # http://www.gnu.org/copyleft/gpl.html . # global_vars - shared global variables # # Dependencies: # Python (tested on v2.6 and v2.7) try: _ except NameError: _ = lambda s:s # Application info name = 'AvsPmod' description = _('An AviSynth script editor') url = 'http://avspmod.github.io/' license = 'GNU GPL v2' version = '2.5.1' # Used to pass the shared library location to avisynth.py, don't touch avisynth_library_dir = '' # This will be improved on the future refactoring for wxPython Phoenix # and VapourSynth options = {}
AvsPmod/AvsPmod
global_vars.py
Python
gpl-2.0
1,359
[ "VisIt" ]
77b7a5c2c10598c6e3cc6d77b4cc99d6eea5d120b8e539c3cf3daab5edd5d731
""" PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net) Copyright (C) 2004-2020 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved, Brett G. Olivier (bgoli@users.sourceforge.net) Triple-J Group for Molecular Cell Physiology Stellenbosch University, South Africa. Permission to use, modify, and distribute this software is given under the terms of the PySceS (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Brett G. Olivier """ from __future__ import division, print_function from __future__ import absolute_import from __future__ import unicode_literals from pysces.version import __version__ __doc__ = """ PyscesScan ---------- PySCeS classes for continuations and multi-dimensional parameter scans """ import scipy from pysces.PyscesUtils import TimerBox __psyco_active__ = 0 class Scanner(object): """ Arbitrary dimension generic scanner. This class is initiated with a loaded PySCeS model and then allows the user to define scan parameters see self.addScanParameter() and user output see self.addUserOutput(). Steady-state results are always stored in self.SteadyStateResults while user output can be found in self.UserOutputResults - brett 2007. """ genOn = True quietRun = False _MODE_ = 'state' HAS_USER_OUTPUT = False HAS_STATE_OUTPUT = True nan_on_bad_state = True MSG_PRINT_INTERVAL = 500 __AnalysisModes__ = ('state', 'elasticity', 'mca', 'stability', 'null') invalid_state_list = None invalid_state_list_idx = None def __init__(self, mod): try: N = mod.nmatrix except Exception as ex: print( '\nSCANNER: Please load a model <i.e. mod. doLoad()> before trying to use it.' ) self.GenDict = {} self.GenOrder = [] self.ScanSpace = [] self.mod = mod self.SteadyStateResults = [] self.UserOutputList = [] self.UserOutputResults = [] self.scanT = TimerBox() def testInputParameter(self, name): """ This tests whether a str(name) is an attribute of the model """ if hasattr(self.mod, name): return True else: return False def resetInputParameters(self): """ Just remembered what this does, I think it resets the input model parameters after a scan run. """ for key in self.GenDict: setattr(self.mod, key, self.GenDict[key][6]) def addUserOutput(self, *kw): """ Add output parameters to the scanner as a collection of one or more string arguments ('O1','O2','O3', 'On'). These are evaluated at each iteration of the scanner and stored in the self.UserOutputResults array. The list of output is stored in self.UserOutputList. """ output = [attr for attr in kw if type(attr) == str] # print output self.HAS_USER_OUTPUT = True ModeList = list(self.__AnalysisModes__) MaxMode = 0 for attr in output: if attr[:2] == 'ec' and self._MODE_ != 'null': cM = ModeList.index('elasticity') if cM > MaxMode: self._MODE_ = 'elasticity' MaxMode = cM elif attr[:2] == 'cc' and self._MODE_ != 'null': cM = ModeList.index('mca') if cM > MaxMode: self._MODE_ = 'mca' MaxMode = cM elif attr[:6] == 'lambda' and self._MODE_ != 'null': cM = ModeList.index('stability') if cM > MaxMode: self._MODE_ = 'stability' MaxMode = cM print('MaxMode', MaxMode) self.UserOutputList = output def addScanParameter(self, name, start, end, points, log=False, follower=False): """ Add a parameter to scan (an axis if you like) input is: - str(name) = model parameter name - float(start) = lower bound of scan - float(end) = upper bound of scan - int(points) = number of points in scan range - bool(log) = Use a logarithmic (base10) range - bool(follower) = Scan parameters can be leaders i.e. an independent axis or a "follower" which moves synchronously with the previously defined parameter range. The first ScanParameter cannot be a follower. """ offset = 1 assert self.testInputParameter(name), ( '\nSCANNER: Model does not have an attribute \"%s\" \n' % name ) assert ( name not in self.GenOrder ), '\nSCANNER: This operation is currently not allowed\n' if not len(self.GenOrder) == 0: for el in self.GenOrder: if self.GenDict[el][4] == False: # test if not follower offset = offset * self.GenDict[el][2] # increment offset if follower == True: prevpar = self.GenOrder[-1] # previous parameter, i.e. leader offset = self.GenDict[prevpar][5] # don't increment for follower if points != self.GenDict[prevpar][2]: print( 'SCANNER: Follower parameter needs to iterate over same number of\npoints as leader...resetting points.' ) points = self.GenDict[prevpar][2] else: if follower == True: follower = False print( 'SCANNER: Inner range cannot be a follower ... resetting to leader' ) self.GenDict.setdefault( name, (start, end, points, log, follower, offset, getattr(self.mod, name)) ) setattr(self, name + '_test', self.stepGen(offset)) setattr(self, name, self.rangeGen(name, start, end, points, log)) if name not in self.GenOrder: self.GenOrder.append(name) def makeRange(self, start, end, points, log): """ Should be pretty self evident it defines a range: - float(start) - float(end) - int(points) - bool(log) """ if log: rng = scipy.logspace(scipy.log10(start), scipy.log10(end), points) else: rng = scipy.linspace(start, end, points) return rng def rangeGen(self, name, start, end, points, log): """ This is where things get more interesting. This function creates a cycling generator which loops over a parameter range. - *parameter* name - *start* value - *end* value - *points* - *log* scale """ range = self.makeRange(start, end, points, log) cnt = 0 while self.genOn: if next(getattr(self, name + '_test')): if cnt >= len(range) - 1: cnt = 0 else: cnt += 1 yield range[cnt] def stepGen(self, offset): """ Another looping generator function. The idea here is to create a set of generators for the scan parameters. These generators then all fire together and determine whether the range generators should advance or not. Believe it or not this dynamically creates the matrix of parameter values to be evaluated. """ val = 0 while self.genOn: if val >= offset: val = 0 yield True else: yield False val += 1 def __nextStep__(self): """ Fire all step generators """ return [next(getattr(self, genN + '_test')) for genN in self.GenOrder] def __nextValue__(self): """ Fire all range generators """ return [next(getattr(self, genN)) for genN in self.GenOrder] def setModValue(self, name, value): """ An easy one, assign value to name of the instantiated PySCeS model attribute """ assert hasattr(self.mod, name), ( '\nModel does not have an attribute: %s \n' % name ) setattr(self.mod, name, float(value)) def RunAgain(self): """ While it is impossible to change the generator/range structure of a scanner (just build another one) you can 'in principle' change the User Output and run it again. """ self.Run(ReRun=True) def Run(self, ReRun=False): """ Run the parameter scan """ self.scanT.normal_timer('RUN') self._MODE_ = self._MODE_.lower() assert self._MODE_ in self.__AnalysisModes__, ( '\nSCANNER: \"%s\" is not a valid analysis mode!' % self._MODE_ ) if self.quietRun: self.mod.SetQuiet() else: self.mod.SetLoud() if ReRun: self.ScanSpace = [] self.UserOutputResults = [] self.SteadyStateResults = [] self.invalid_state_list = [] self.invalid_state_list_idx = [] if self.nan_on_bad_state: self.mod.__settings__["mode_state_nan_on_fail"] = True # self.mod.mode_state_nan_on_fail = True Tsteps = 1 for gen in self.GenOrder: if self.GenDict[gen][4] == False: # don't increase Tsteps for follower Tsteps *= self.GenDict[gen][2] print(next(self.scanT.RUN)) analysis_counter = 0 print('SCANNER: Tsteps', Tsteps) pcntr = 0 for step in range(Tsteps): pars = self.__nextValue__() # if pars not in self.ScanSpace: self.ScanSpace.append(pars) for par in range(len(self.GenOrder)): self.setModValue(self.GenOrder[par], pars[par]) analysis_counter += 1 self.Analyze() if not self.mod.__StateOK__: self.invalid_state_list.append(pars) self.invalid_state_list_idx.append(analysis_counter) self.StoreData() pcntr += 1 if pcntr >= self.MSG_PRINT_INTERVAL: print('\t', analysis_counter, next(self.scanT.RUN)) pcntr = 0 self.ScanSpace = scipy.array(self.ScanSpace) self.SteadyStateResults = scipy.array(self.SteadyStateResults) self.UserOutputResults = scipy.array(self.UserOutputResults) self.resetInputParameters() if self.nan_on_bad_state: self.mod.mode_state_nan_on_fail = False print("\nSCANNER: %s states analysed\n" % analysis_counter) if len(self.invalid_state_list) > 0: print('Bad steady states encountered at:\n') print(self.invalid_state_list) print(self.invalid_state_list_idx) def Analyze(self): """ The analysis method, the mode is automatically set by the self.addUserOutput() method but can be reset by the user. """ if self._MODE_ == 'state': self.mod.doState() elif self._MODE_ == 'elasticity': self.mod.doElas() elif self._MODE_ == 'mca': self.mod.doMca() elif self._MODE_ == 'stability': self.mod.doEigenMca() elif self._MODE_ == 'null': self.HAS_STATE_OUTPUT = False self.mod.User_Function() def StoreData(self): """ Internal function which concatenates and stores the data generated by Analyze. """ if self.HAS_STATE_OUTPUT and self._MODE_ != 'null': self.SteadyStateResults.append( scipy.hstack((self.mod.state_species, self.mod.state_flux)) ) if self.HAS_USER_OUTPUT and self._MODE_ != 'null': self.UserOutputResults.append( scipy.array([getattr(self.mod, res) for res in self.UserOutputList]) ) def getOutput(self): """ Will be the new output function. """ pass def getResultMatrix(self, stst=False, lbls=False): """ Returns an array of result data. I'm keepin this for backwards compatibility but it will be replaced by a getOutput() method when this scanner is updated to use the new data_scan object. - *stst* add steady-state data to output array - *lbls* return a tuple of (array, column_header_list) If *stst* is True output has dimensions [scan_parameters]+[state_species+state_flux]+[Useroutput] otherwise [scan_parameters]+[Useroutput]. """ output_array = None labels = [] if stst: if self.HAS_USER_OUTPUT: output_array = scipy.hstack( [self.ScanSpace, self.SteadyStateResults, self.UserOutputResults] ) labels = ( self.GenOrder + list(self.mod.species) + list(self.mod.reactions) + self.UserOutputList ) else: output_array = scipy.hstack([self.ScanSpace, self.SteadyStateResults]) labels = ( self.GenOrder + list(self.mod.species) + list(self.mod.reactions) ) else: output_array = scipy.hstack([self.ScanSpace, self.UserOutputResults]) labels = self.GenOrder + self.UserOutputList if lbls: return output_array, labels else: return output_array class PITCONScanUtils(object): """ Static Bifurcation Scanning utilities using PITCON, call with loaded model object. Hopefully nobody else was trying to use the older class as it was horrible. This new one is is leaner, meaner and pretty cool ;-) """ model = None timer = None pitcon_range_low = None pitcon_range_high = None pitcon_scan_density = None pitcon_scan_parameter = None pitcon_scan_parameter_3d = None pitcon_res = None user_output = None res_user = None res_idx = None res_metab = None res_flux = None res_eigen = None def __init__(self, model): """ Instantiate PITCONScanUtils with a loaded PySCeS model instance. """ self.model = model self.timer = TimerBox() def setUserOuput(self, *args): """ Set the user output required as n string arguments. """ self.user_output = [str(arg) for arg in args] def runContinuation( self, parameter, low, high, density, par3d=None, logrange=True, runQuiet=True ): """ Run the continuation using the following parameters: Args: - parameter = str(the parameter to be scanned) - low = float(lower bound) - high = float(upper bound) - density = int(the number of initial points) - par3d = float(extra 3d parameter to insert into the output array) this parameter is not set ONLY used in output - logrange = boolean [default = True], if True generate the result using logspace(log10(low), log10(high), density) otherwise use a linear range - runQuiet = boolean [default = True], if True do not display intermediate results to screen, disable for debugging After running the continuation the results are stored in numpy arrays - mod.res_idx = scan parameter values (and optionally par3d) - mod.res_metab = steady-state species concentrations - mod.res_flux = steady-state flux values """ self.pitcon_scan_density = density self.pitcon_scan_parameter = parameter self.pitcon_scan_parameter_3d = par3d if logrange: self.pitcon_range_low = scipy.log10(low) self.pitcon_range_high = scipy.log10(high) self.model.pitcon_par_space = scipy.logspace( self.pitcon_range_low, self.pitcon_range_high, self.pitcon_scan_density ) else: self.pitcon_range_low = low self.pitcon_range_high = high self.model.pitcon_par_space = scipy.linspace( self.pitcon_range_low, self.pitcon_range_high, self.pitcon_scan_density ) self.model.pitcon_flux_gen = 1 if runQuiet: self.model.SetQuiet() else: self.model.SetLoud() if self.pitcon_scan_parameter_3d != None: self.pitcon_res = self.model.PITCON( self.pitcon_scan_parameter, self.pitcon_scan_parameter_3d ) self.res_idx = self.pitcon_res[:, :2] self.res_metab = self.pitcon_res[:, 2 : len(self.model.species) + 2 :] self.res_flux = self.pitcon_res[:, len(self.model.species) + 2 :] else: self.pitcon_res = self.model.PITCON(self.pitcon_scan_parameter) self.res_idx = self.pitcon_res[:, 0] self.res_idx = self.res_idx.reshape(self.res_idx.shape[0], 1) self.res_metab = self.pitcon_res[:, 1 : len(self.model.species) + 1] self.res_flux = self.pitcon_res[:, len(self.model.species) + 1 :] print('\n\tContinuation complete\n') def analyseData(self, analysis='elas'): """ Performs "analysis" on the PITCON generated set of steady-state results where analysis is: - 'elasv' = variable elasticities - 'elasp' = parameter elasticities - 'elas' = all elasticities - 'mca' = control coefficients - 'resp' = response coefficients - 'eigen' = eigen values - 'all' = all of the above Higher level analysis types automatically enable the lower level analysis needed e.g. selecting 'mca' implies 'elasv' etc. User output defined with mod.setUserOutput() is stored in the mod.res_user array. """ # reset result lists self.res_eigen = [] self.res_user = [] step_cntr = 0 self.timer.step_timer('st1', self.res_idx.shape[0]) for row in range(self.res_idx.shape[0]): self.timer.st1_cstep += 1 step_cntr += 1 if self.timer.st1_cstep == 1 or step_cntr == 200: print('\n', next(self.timer.st1)) step_cntr = 0 PitParVal = self.res_idx[row, -1] setattr(self.model, self.pitcon_scan_parameter, PitParVal) self.model.state_species = self.res_metab[row, :] self.model.state_flux = self.res_flux[row, :] self.model.SetStateSymb(self.model.state_flux, self.model.state_species) self.model.Forcing_Function() if analysis in ['elasv', 'elas', 'mca', 'resp', 'eigen', 'all']: self.model.EvalEvar(self.model.state_species, self.model.state_flux) if analysis in ['elasp', 'elas', 'resp', 'all']: self.model.EvalEpar(self.model.state_species, self.model.state_flux) if analysis in ['mca', 'resp', 'all']: self.model.EvalCC() if analysis in ['resp', 'all']: self.model.EvalRC() if analysis in ['eigen', 'all']: self.model.EvalEigen() self.res_eigen.append(self.model.eigen_values) state_out = [] if self.user_output != None and len(self.user_output) > 0: for attr in self.user_output: try: state_out.append(getattr(self.model, attr)) except Exception as ex: print(ex) self.res_user.append(state_out) self.res_user = scipy.array(self.res_user) print('\n\t%s evaluation complete\n' % analysis) def getArrayListAsArray(self, array_list): """ Stack (concatenate) the list of arrays into a single array. """ output = None if len(array_list) > 1: output = scipy.vstack(array_list) elif len(array_list) == 1: output = array_list[0] return output
bgoli/pysces
pysces/PyscesScan.py
Python
bsd-3-clause
20,294
[ "PySCeS" ]
4ac1a25207a42b554c112565540b4d98d02facb44467ad0619dd23371c3bd05a
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2016, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from sympy import * init_printing() from IPython.display import display import plotly.plotly as py from plotly.graph_objs import * import os # Define the (global) equations # Equation from Neuron paper # # A dendritic segment can robustly classify a pattern by # subsampling a small number of cells from a larger population. Assuming # a random distribution of patterns, the exact probability of a false # match is given by the following equation: where n refers to the size of # the population of cells, a is the number of active cells at any instance # in time, s is the number of actual synapses on a dendritic segment, and # theta is the threshold for NMDA spikes. Following (Ahmad & Hawkins, # 2015), the numerator counts the number of possible ways theta or more # cells can match a fixed set of s synapses. The denominator counts the # number of ways a cells out of n can be active. # b, n, s, a, theta = symbols("b n s a theta") subsampledOmega = (binomial(s, b) * binomial(n - s, a - b)) / binomial(n, a) subsampledFpF = Sum(subsampledOmega, (b, theta, s)) subsampledOmegaSlow = (binomial(s, b) * binomial(n - s, a - b)) subsampledFpFSlow = Sum(subsampledOmegaSlow, (b, theta, s))/ binomial(n, a) display(subsampledFpF) display(subsampledFpFSlow) # Union formula # # Formula for calculating the number of bits that are ON after M union # operations. This number can then be used in the above equations to calculate # error probabilities with unions. # Probability a given bit is 0 after M union operation M = Symbol("M") p0 = Pow((1-(s/n)),M) # Expected number of ON bits after M union operations. numOnBits = (1-p0)*n # Plot probability of a false match as a function of M def falseMatchvsM(n_=1000): a_ = 200 theta_ = 15 s_ = 25 # Arrays used for plotting MList = [] errorList = [] print "\n\nn=%d, a=%d, theta=%d, s=%d" % (n_,a_,theta_,s_) error = 0.0 for M_ in range(1, 20): # Need this otherwise calculation goes to 0 if error >= 0.9999999999: error = 1.0 else: if M_ <= 2: eq3 = subsampledFpFSlow.subs(n, n_).subs(a, a_).subs(theta, theta_) else: eq3 = subsampledFpF.subs(n, n_).subs(a, a_).subs(theta, theta_) numSynapsesAfterUnion = numOnBits.subs(n,n_).subs(s,s_).subs(M,M_).evalf() error = eq3.subs(s,round(numSynapsesAfterUnion)).evalf() print M_,numSynapsesAfterUnion,error MList.append(M_) errorList.append(error) print MList print errorList return MList,errorList def plotFalseMatchvsM(): # Plot probability of a false match as a function of M # Plot three different values of n. n=1000, 10000, 20000? # listofMValues,errorsN1000 = falseMatchvsM(1000) # listofMValues,errorsN10000 = falseMatchvsM(10000) # listofMValues,errorsN20000 = falseMatchvsM(20000) # I get a JSON serialization error if I try to use the above values directly # Go figure! listofMValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] errorsN1000 = [1.00140315240769e-5, 0.0473894530292855, 0.501650232353378, 0.899154755459308, 0.991079536716752, 0.999523524650922, 0.999981553264809, 0.999999512691584, 0.999999990860972, 0.999999999845828, 0.999999999997526, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] errorsN10000 = [5.30352419025194e-20, 2.35602184920806e-14, 1.53934243906984e-11, 1.10302867119927e-9, 2.27921915526762e-8, 2.69253218125502e-7, 1.98072351729197e-6, 9.75307801058064e-6, 3.98373263650013e-5, 0.000127080441383853, 0.000362630253250421, 0.000874610762751977, 0.00190208641223641, 0.00378812896412743, 0.00716447200395456, 0.0123542384410630, 0.0201165770143612, 0.0311403472140338, 0.0453789479134073] errorsN20000 = [1.75826328738259e-24, 9.73603540551588e-19, 7.92130752699486e-16, 7.08428692442973e-14, 2.03825914561597e-12, 2.93568736488724e-11, 2.44471331836285e-10, 1.59493239439383e-9, 8.04780894887436e-9, 3.32242567600452e-8, 1.11328056326208e-7, 3.44426535137730e-7, 9.53448550682057e-7, 2.31864104977855e-6, 5.40383164541756e-6, 1.13919680675529e-5, 2.33141516738363e-5, 4.40336400781654e-5, 8.14089056445047e-5] plotlyUser = os.environ['PLOTLY_USERNAME'] plotlyAPIKey = os.environ['PLOTLY_API_KEY'] py.sign_in(plotlyUser, plotlyAPIKey) trace1 = Scatter( y=errorsN1000, x=listofMValues, line=Line( color='rgb(0, 0, 0)', width=3, shape='spline' ), name="n=1000" ) trace2 = Scatter( y=errorsN10000, x=listofMValues, line=Line( color='rgb(0, 0, 0)', width=3, shape='spline' ), name="n=10000" ) trace3 = Scatter( y=errorsN20000, x=listofMValues, line=Line( color='rgb(0, 0, 0)', width=3, shape='spline' ), name="n=20000" ) data = Data([trace1, trace2, trace3]) layout = Layout( title='', showlegend=False, autosize=False, width=855, height=700, xaxis=XAxis( title='$\\text{Number of combined patterns } (M)$', titlefont=Font( family='', size=16, color='' ), tickfont=Font( family='', size=16, color='' ), exponentformat="none", dtick=2, showline=True, range=[0,20], ), yaxis=YAxis( title='Probability of false positives', type='log', exponentformat='power', autorange=True, titlefont=Font( family='', size=18, color='' ), tickfont=Font( family='', size=12, color='' ), showline=True, ), annotations=Annotations([ Annotation( x=7.7906, y=0.916, xref='x', yref='paper', text='$n = 1000$', showarrow=False, font=Font( family='', size=16, color='' ), align='center', textangle=0, bordercolor='', borderwidth=1, borderpad=1, bgcolor='rgba(0, 0, 0, 0)', opacity=1 ), Annotation( x=7.906, y=0.7148, xref='x', yref='paper', text='$n = 10000$', showarrow=False, font=Font( family='', size=16, color='' ), align='center', textangle=0, bordercolor='', borderwidth=1, borderpad=1, bgcolor='rgba(0, 0, 0, 0)', opacity=1 ), Annotation( x=7.906, y=0.534, xref='x', yref='paper', text='$n = 20000$', showarrow=False, font=Font( family='', size=16, color='' ), align='center', textangle=0, bordercolor='', borderwidth=1, borderpad=1, bgcolor='rgba(0, 0, 0, 0)', opacity=1 ), ]), ) fig = Figure(data=data, layout=layout) plot_url = py.plot(fig) print "url=",plot_url figure = py.get_figure(plot_url) py.image.save_as(figure, 'union_effect_of_n.png', scale=4) def synapsesvsM(s_ = 25): # Compute number of synapses on a segment as a function of M listofMValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] listofSynapses = [] n_=1000 print "\n\nn=%d, s=%d" % (n_,s_) for M_ in listofMValues: numSynapsesAfterUnion = numOnBits.subs(n,n_).subs(s,s_).subs(M,M_).evalf() listofSynapses.append(numSynapsesAfterUnion) print listofSynapses def plotSynapsesvsM(): # Plot number of synapses on a segment as a function of M listofMValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] synapsesS20 = [20.0000000000000, 39.6000000000000, 58.8080000000000, 77.6318400000000, 96.0792032000000, 114.157619136000, 131.874466753280, 149.236977418214, 166.252237869850, 182.927193112453, 199.268649250204, 215.283276265200, 230.977610739896, 246.358058525098, 261.430897354596, 276.202279407504, 290.678233819354, 304.864669142967, 318.767375760108] synapsesS25 = [25.0000000000000, 49.3750000000000, 73.1406250000000, 96.3121093750000, 118.904306640625, 140.931698974609, 162.408406500244, 183.348196337738, 203.764491429295, 223.670379143562, 243.078619664973, 262.001654173349, 280.451612819015, 298.440322498540, 315.979314436076, 333.079831575174, 349.752835785795, 366.009014891150, 381.858789518871] synapsesS30 = [30.0000000000000, 59.1000000000000, 87.3270000000000, 114.707190000000, 141.265974300000, 167.027995071000, 192.017155218870, 216.256640562304, 239.768941345435, 262.575873105072, 284.698596911920, 306.157639004562, 326.972909834425, 347.163722539392, 366.748810863211, 385.746346537314, 404.173956141195, 422.048737456959, 439.387275333250] plotlyUser = os.environ['PLOTLY_USERNAME'] plotlyAPIKey = os.environ['PLOTLY_API_KEY'] py.sign_in(plotlyUser, plotlyAPIKey) trace1 = Scatter( y=synapsesS20, x=listofMValues, line=Line( color='rgb(0, 0, 0)', width=3, shape='spline' ), name="s=20" ) trace2 = Scatter( y=synapsesS25, x=listofMValues, line=Line( color='rgb(0, 0, 0)', width=3, shape='spline' ), name="s=25" ) trace3 = Scatter( y=synapsesS30, x=listofMValues, line=Line( color='rgb(0, 0, 0)', width=3, shape='spline' ), name="s=30" ) data = Data([trace1, trace2, trace3]) layout = Layout( title='', showlegend=False, autosize=False, width=855, height=700, xaxis=XAxis( title='$\\text{Number of combined patterns } (M)$', titlefont=Font( family='', size=16, color='' ), tickfont=Font( family='', size=16, color='' ), exponentformat="none", dtick=2, range=[0,20], ), yaxis=YAxis( title='Number of synapses on segment', exponentformat='none', autorange=True, titlefont=Font( family='', size=18, color='' ), tickfont=Font( family='', size=12, color='' ), ), annotations=Annotations([ Annotation( x=18.0, y=0.616, xref='x', yref='paper', text='$s = 20$', showarrow=False, font=Font( family='', size=16, color='' ), align='center', textangle=0, bordercolor='', borderwidth=1, borderpad=1, bgcolor='rgba(0, 0, 0, 0)', opacity=1 ), Annotation( x=18.0, y=0.7552, xref='x', yref='paper', text='$s = 25$', showarrow=False, font=Font( family='', size=16, color='' ), align='center', textangle=0, bordercolor='', borderwidth=1, borderpad=1, bgcolor='rgba(0, 0, 0, 0)', opacity=1 ), Annotation( x=18.0, y=0.876, xref='x', yref='paper', text='$s = 30$', showarrow=False, font=Font( family='', size=16, color='' ), align='center', textangle=0, bordercolor='', borderwidth=1, borderpad=1, bgcolor='rgba(0, 0, 0, 0)', opacity=1 ), ]), ) fig = Figure(data=data, layout=layout) plot_url = py.plot(fig) print "url=",plot_url figure = py.get_figure(plot_url) py.image.save_as(figure, 'union_number_synapses.png', scale=4) plotFalseMatchvsM() plotSynapsesvsM()
ywcui1990/nupic.research
projects/sdr_paper/sdr_paper_unions.py
Python
agpl-3.0
12,274
[ "NEURON" ]
41f3be41605e215ebe8590b05be21bdadce2e98bc04b3597c0e305b6454f48f0
""" Class that contains client access to the transformation DB handler. """ __RCSID__ = "$Id$" from DIRAC import S_OK, gLogger from DIRAC.Core.Base.Client import Client from DIRAC.Core.Utilities.List import breakListIntoChunks from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations class TransformationClient( Client ): """ Exposes the functionality available in the DIRAC/TransformationHandler This inherits the DIRAC base Client for direct execution of server functionality. The following methods are available (although not visible here). Transformation (table) manipulation deleteTransformation(transName) getTransformationParameters(transName,paramNames) getTransformationWithStatus(status) setTransformationParameter(transName,paramName,paramValue) deleteTransformationParameter(transName,paramName) TransformationFiles table manipulation addFilesToTransformation(transName,lfns) addTaskForTransformation(transName,lfns=[],se='Unknown') getTransformationStats(transName) TransformationTasks table manipulation setTaskStatus(transName, taskID, status) setTaskStatusAndWmsID(transName, taskID, status, taskWmsID) getTransformationTaskStats(transName) deleteTasks(transName, taskMin, taskMax) extendTransformation( transName, nTasks) getTasksToSubmit(transName,numTasks,site='') TransformationLogging table manipulation getTransformationLogging(transName) File/directory manipulation methods (the remainder of the interface can be found below) getFileSummary(lfns) exists(lfns) Web monitoring tools getDistinctAttributeValues(attribute, selectDict) getTransformationStatusCounters() getTransformationSummary() getTransformationSummaryWeb(selectDict, sortList, startItem, maxItems) """ def __init__( self, **kwargs ): """ Simple constructor """ Client.__init__( self, **kwargs ) opsH = Operations() self.maxResetCounter = opsH.getValue( 'Productions/ProductionFilesMaxResetCounter', 10 ) self.setServer( 'Transformation/TransformationManager' ) def setServer( self, url ): self.serverURL = url def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None ): rpcClient = self._getRPC() return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp ) def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask, transformationGroup = 'General', groupSize = 1, inheritedFrom = 0, body = '', maxTasks = 0, eventsPerTask = 0, addFiles = True, timeout = 1800 ): """ add a new transformation """ rpcClient = self._getRPC( timeout = timeout ) return rpcClient.addTransformation( transName, description, longDescription, transType, plugin, agentType, fileMask, transformationGroup, groupSize, inheritedFrom, body, maxTasks, eventsPerTask, addFiles ) def getTransformations( self, condDict = None, older = None, newer = None, timeStamp = None, orderAttribute = None, limit = 100, extraParams = False ): """ gets all the transformations in the system, incrementally. "limit" here is just used to determine the offset. """ rpcClient = self._getRPC() transformations = [] if condDict is None: condDict = {} if timeStamp is None: timeStamp = 'CreationDate' # getting transformations - incrementally offsetToApply = 0 while True: res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit, extraParams, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformations = transformations + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformations ) def getTransformation( self, transName, extraParams = False ): rpcClient = self._getRPC() return rpcClient.getTransformation( transName, extraParams ) def getTransformationFiles( self, condDict = None, older = None, newer = None, timeStamp = None, orderAttribute = None, limit = None, timeout = 1800, offset = 0, maxfiles = None ): """ gets all the transformation files for a transformation, incrementally. "limit" here is just used to determine the offset. """ rpcClient = self._getRPC( timeout = timeout ) transformationFiles = [] if condDict is None: condDict = {} if timeStamp is None: timeStamp = 'LastUpdate' # getting transformationFiles - incrementally offsetToApply = offset retries = 5 limit = limit if limit else 10000 transID = condDict.get( 'TransformationID', 'Unknown' ) while True: res = rpcClient.getTransformationFiles( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply ) if not res['OK']: gLogger.error( "Error getting files for transformation %s (offset %d), %s" % ( str( transID ), offsetToApply, ( 'retry %d times' % retries ) if retries else 'give up' ), res['Message'] ) retries -= 1 if retries: continue return res else: retries = 5 gLogger.verbose( "For conditions %s: result for limit %d, offset %d: %d files" % ( str( condDict ), limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformationFiles += res['Value'] offsetToApply += limit if maxfiles and offsetToApply >= offset + maxfiles: break if len( res['Value'] ) < limit: break return S_OK( transformationFiles ) def getTransformationTasks( self, condDict = None, older = None, newer = None, timeStamp = None, orderAttribute = None, limit = 10000, inputVector = False ): """ gets all the transformation tasks for a transformation, incrementally. "limit" here is just used to determine the offset. """ rpcClient = self._getRPC() transformationTasks = [] if condDict is None: condDict = {} if timeStamp is None: timeStamp = 'CreationTime' # getting transformationFiles - incrementally offsetToApply = 0 while True: res = rpcClient.getTransformationTasks( condDict, older, newer, timeStamp, orderAttribute, limit, inputVector, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformationTasks = transformationTasks + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformationTasks ) def cleanTransformation( self, transID ): """ Clean the transformation, and set the status parameter (doing it here, for easier extensibility) """ # Cleaning rpcClient = self._getRPC() res = rpcClient.cleanTransformation( transID ) if not res['OK']: return res # Setting the status return self.setTransformationParameter( transID, 'Status', 'TransformationCleaned' ) def moveFilesToDerivedTransformation( self, transDict, resetUnused = True ): """ move files input to a transformation, to the derived one """ prod = transDict['TransformationID'] parentProd = int( transDict.get( 'InheritedFrom', 0 ) ) movedFiles = {} if not parentProd: gLogger.warn( "[None] [%d] .moveFilesToDerivedTransformation: Transformation was not derived..." % prod ) return S_OK( ( parentProd, movedFiles ) ) # get the lfns in status Unused/MaxReset of the parent production res = self.getTransformationFiles( condDict = {'TransformationID': parentProd, 'Status': [ 'Unused', 'MaxReset' ]} ) if not res['OK']: gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting Unused files from transformation %s:" % ( prod, parentProd ), res['Message'] ) return res parentFiles = res['Value'] lfns = [lfnDict['LFN'] for lfnDict in parentFiles] if not lfns: gLogger.info( "[None] [%d] .moveFilesToDerivedTransformation: No files found to be moved from transformation %d" % ( prod, parentProd ) ) return S_OK( ( parentProd, movedFiles ) ) # get the lfns of the derived production that were Unused/MaxReset in the parent one res = self.getTransformationFiles( condDict = { 'TransformationID': prod, 'LFN': lfns} ) if not res['OK']: gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting files from derived transformation" % prod, res['Message'] ) return res derivedFiles = res['Value'] derivedStatusDict = dict( [( derivedDict['LFN'], derivedDict['Status'] ) for derivedDict in derivedFiles] ) newStatusFiles = {} parentStatusFiles = {} badStatusFiles = {} for parentDict in parentFiles: lfn = parentDict['LFN'] derivedStatus = derivedStatusDict.get( lfn ) if derivedStatus: parentStatus = parentDict['Status'] # By default move to the parent status (which is Unused or MaxReset) status = parentStatus moveStatus = parentStatus # For MaxReset, set Unused if requested if parentStatus == 'MaxReset': if resetUnused: status = 'Unused' moveStatus = 'Unused from MaxReset' else: status = 'MaxReset-inherited' if derivedStatus.endswith( '-inherited' ): # This is the general case newStatusFiles.setdefault( ( status, parentStatus ), [] ).append( lfn ) movedFiles[moveStatus] = movedFiles.setdefault( moveStatus, 0 ) + 1 else: badStatusFiles[derivedStatus] = badStatusFiles.setdefault( derivedStatus, 0 ) + 1 if parentStatus == 'Unused': # If the file was Unused, set it NotProcessed in parent parentStatusFiles.setdefault( 'NotProcessed', [] ).append( lfn ) else: parentStatusFiles.setdefault( 'Moved', [] ).append( lfn ) for status, count in badStatusFiles.items(): gLogger.warn( '[None] [%d] .moveFilesToDerivedTransformation: Files found in an unexpected status in derived transformation' % prod, '%s: %d' % ( status, count ) ) # Set the status in the parent transformation first for status, lfnList in parentStatusFiles.items(): for lfnChunk in breakListIntoChunks( lfnList, 5000 ): res = self.setFileStatusForTransformation( parentProd, status, lfnChunk ) if not res['OK']: gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d " % ( prod, status, len( lfnList ), parentProd ), res['Message'] ) # Set the status in the new transformation for ( status, oldStatus ), lfnList in newStatusFiles.items(): for lfnChunk in breakListIntoChunks( lfnList, 5000 ): res = self.setFileStatusForTransformation( prod, status, lfnChunk ) if not res['OK']: gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files; resetting them %s in transformation %d" % ( prod, status, len( lfnChunk ), oldStatus, parentProd ), res['Message'] ) res = self.setFileStatusForTransformation( parentProd, oldStatus, lfnChunk ) if not res['OK']: gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d" % ( prod, oldStatus, len( lfnChunk ), parentProd ), res['Message'] ) else: gLogger.info( "[None] [%d] .moveFilesToDerivedTransformation: Successfully moved %d files from %s to %s" % ( prod, len( lfnChunk ), oldStatus, status ) ) # If files were Assigned or Unused at the time of derivation, try and update them as jobs may have run since then res = self.getTransformationFiles( condDict = {'TransformationID': prod, 'Status': [ 'Assigned-inherited', 'Unused-inherited' ]} ) if res['OK']: assignedFiles = res['Value'] if assignedFiles: lfns = [lfnDict['LFN'] for lfnDict in assignedFiles] res = self.getTransformationFiles( condDict = { 'TransformationID':parentProd, 'LFN':lfns} ) if res['OK']: parentFiles = res['Value'] processedLfns = [lfnDict['LFN'] for lfnDict in parentFiles if lfnDict['Status'] == 'Processed'] if processedLfns: res = self.setFileStatusForTransformation( prod, 'Processed-inherited', processedLfns ) if res['OK']: gLogger.info( "[None] [%d] .moveFilesToDerivedTransformation: set %d files to status %s" % ( prod, len( processedLfns ), 'Processed-inherited' ) ) if not res['OK']: gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status for Assigned derived files" % prod, res['Message'] ) return S_OK( ( parentProd, movedFiles ) ) def setFileStatusForTransformation( self, transName, newLFNsStatus = None, lfns = None, force = False ): """ Sets the file status for LFNs of a transformation For backward compatibility purposes, the status and LFNs can be passed in 2 ways: - newLFNsStatus is a dictionary with the form: {'/this/is/an/lfn1.txt': 'StatusA', '/this/is/an/lfn2.txt': 'StatusB', ... } and at this point lfns is not considered - newLFNStatus is a string, that applies to all the LFNs in lfns """ rpcClient = self._getRPC() if newLFNsStatus is None: newLFNsStatus = {} if lfns is None: lfns = [] # create dictionary in case newLFNsStatus is a string if isinstance( lfns, basestring ): lfns = [lfns] if isinstance( newLFNsStatus, basestring ): newLFNsStatus = dict( [( lfn, newLFNsStatus ) for lfn in lfns ] ) # gets status as of today tsFiles = self.getTransformationFiles( {'TransformationID':transName, 'LFN': newLFNsStatus.keys()} ) if not tsFiles['OK']: return tsFiles tsFiles = tsFiles['Value'] newStatuses = {} if tsFiles: # for convenience, makes a small dictionary out of the tsFiles, with the lfn as key tsFilesAsDict = {} for tsFile in tsFiles: tsFilesAsDict[tsFile['LFN']] = [tsFile['Status'], tsFile['ErrorCount'], tsFile['FileID']] # applying the state machine to the proposed status newStatuses = self._applyTransformationFilesStateMachine( tsFilesAsDict, newLFNsStatus, force ) if newStatuses: # if there's something to update # must do it for the file IDs... newStatusForFileIDs = dict( [( tsFilesAsDict[lfn][2], newStatuses[lfn] ) for lfn in newStatuses] ) res = rpcClient.setFileStatusForTransformation( transName, newStatusForFileIDs ) if not res['OK']: return res return S_OK( newStatuses ) def _applyTransformationFilesStateMachine( self, tsFilesAsDict, dictOfProposedLFNsStatus, force ): """ For easier extension, here we apply the state machine of the production files. VOs might want to replace the standard here with something they prefer. tsFiles is a dictionary with the lfn as key and as value a list of [Status, ErrorCount, FileID] dictOfNewLFNsStatus is a dictionary with the proposed status force is a boolean It returns a dictionary with the status updates """ newStatuses = {} for lfn in dictOfProposedLFNsStatus.keys(): if lfn not in tsFilesAsDict.keys(): continue else: newStatus = dictOfProposedLFNsStatus[lfn] # Apply optional corrections if tsFilesAsDict[lfn][0].lower() == 'processed' and dictOfProposedLFNsStatus[lfn].lower() != 'processed': if not force: newStatus = 'Processed' elif tsFilesAsDict[lfn][0].lower() == 'maxreset': if not force: newStatus = 'MaxReset' elif dictOfProposedLFNsStatus[lfn].lower() == 'unused': errorCount = tsFilesAsDict[lfn][1] # every 10 retries (by default) if errorCount and ( ( errorCount % self.maxResetCounter ) == 0 ): if not force: newStatus = 'MaxReset' if tsFilesAsDict[lfn][0].lower() != newStatus: newStatuses[lfn] = newStatus return newStatuses def setTransformationParameter( self, transID, paramName, paramValue, force = False ): """ Sets a transformation parameter. There's a special case when coming to setting the status of a transformation. """ rpcClient = self._getRPC() if paramName.lower() == 'status': # get transformation Type transformation = self.getTransformation( transID ) if not transformation['OK']: return transformation transformationType = transformation['Value']['Type'] # get status as of today originalStatus = self.getTransformationParameters( transID, 'Status' ) if not originalStatus['OK']: return originalStatus originalStatus = originalStatus['Value'] transIDAsDict = {transID: [originalStatus, transformationType]} dictOfProposedstatus = {transID: paramValue} # applying the state machine to the proposed status value = self._applyTransformationStatusStateMachine( transIDAsDict, dictOfProposedstatus, force ) else: value = paramValue return rpcClient.setTransformationParameter( transID, paramName, value ) def _applyTransformationStatusStateMachine( self, transIDAsDict, dictOfProposedstatus, force ): """ For easier extension, here we apply the state machine of the transformation status. VOs might want to replace the standard here with something they prefer. transIDAsDict is a dictionary with the transID as key and as value a list with [Status, Type] dictOfProposedstatus is a dictionary with the proposed status force is a boolean It returns the new status (the standard is just doing nothing: everything is possible) """ return dictOfProposedstatus.values()[0] def isOK( self ): return self.valid def addDirectory( self, path, force = False ): rpcClient = self._getRPC() return rpcClient.addDirectory( path, force )
vmendez/DIRAC
TransformationSystem/Client/TransformationClient.py
Python
gpl-3.0
19,373
[ "DIRAC" ]
82fbdca73febfd75088292216a39979dc71130cfba74cc08e7a81258b454f68a
from typing import List, Any import stim class ExternalStabilizer: """An input-to-output relationship enforced by a stabilizer circuit.""" def __init__(self, *, input: stim.PauliString, output: stim.PauliString): self.input = input self.output = output @staticmethod def from_dual(dual: stim.PauliString, num_inputs: int) -> 'ExternalStabilizer': sign = dual.sign # Transpose input. Ys get negated. for k in range(num_inputs): if dual[k] == 2: sign *= -1 return ExternalStabilizer( input=dual[:num_inputs], output=dual[num_inputs:], ) @staticmethod def canonicals_from_duals(duals: List[stim.PauliString], num_inputs: int) -> List['ExternalStabilizer']: if not duals: return [] duals = [e.copy() for e in duals] num_qubits = len(duals[0]) num_outputs = num_qubits - num_inputs id_out = stim.PauliString(num_outputs) # Pivot on output qubits, to potentially isolate input-only stabilizers. _eliminate_stabilizers(duals, range(num_inputs, num_qubits)) # Separate input-only stabilizers from the rest. input_only_stabilizers = [] output_using_stabilizers = [] for dual in duals: if dual[num_inputs:] == id_out: input_only_stabilizers.append(dual) else: output_using_stabilizers.append(dual) # Separately canonicalize the output-using and input-only stabilizers. _eliminate_stabilizers(output_using_stabilizers, range(num_qubits)) _eliminate_stabilizers(input_only_stabilizers, range(num_inputs)) duals = input_only_stabilizers + output_using_stabilizers return [ExternalStabilizer.from_dual(e, num_inputs) for e in duals] def __mul__(self, other: 'ExternalStabilizer') -> 'ExternalStabilizer': return ExternalStabilizer(input=other.input * self.input, output=self.output * other.output) def __str__(self) -> str: return str(self.input) + ' -> ' + str(self.output) def __eq__(self, other: Any) -> bool: if not isinstance(other, ExternalStabilizer): return NotImplemented return self.output == other.output and self.input == other.input def __ne__(self, other: Any) -> bool: return not self == other def __repr__(self): return f'stimzx.ExternalStabilizer(input={self.input!r}, output={self.output!r})' def _eliminate_stabilizers(stabilizers: List[stim.PauliString], elimination_indices: range): """Performs partial Gaussian elimination on the list of stabilizers.""" min_pivot = 0 for q in elimination_indices: for b in [1, 3]: for pivot in range(min_pivot, len(stabilizers)): p = stabilizers[pivot][q] if p == 2 or p == b: break else: continue for k, stabilizer in enumerate(stabilizers): p = stabilizer[q] if k != pivot and (p == 2 or p == b): stabilizer *= stabilizers[pivot] if min_pivot != pivot: stabilizers[min_pivot], stabilizers[pivot] = stabilizers[pivot], stabilizers[min_pivot] min_pivot += 1
quantumlib/Stim
glue/zx/stimzx/_external_stabilizer.py
Python
apache-2.0
3,343
[ "Gaussian" ]
468a40118d09eb974df5fda135a6e6f18650e11df2e0afab33821ae8906a62e3
#!/usr/bin/env python # -*- coding: utf-8 -*- """ What it does ============ This optional tool will put unsolvated node configurations (e.g. obtained by high-temperature presampling in vacuum) into equally sized solvent boxes. All solvent boxes will be filled with the same number of solvent molecules. The node topologies will be updated accordingly. For known solvent models, the necessary force field include statements will be added to the node topologies. If the specified box size is too small to fit in the specified linear coordinates (if any), the box size will be increased automatically. B{If required, ions can be added by using L{zgf_genion}. Otherwise, the next step is L{zgf_mdrun}, or L{zgf_submit_job_HLRN}, if you are working on HLRN.} How it works ============ At the command line, type:: $ zgf_solvate_nodes """ from ZIBMolPy.pool import Pool from ZIBMolPy.internals import LinearCoordinate from ZIBMolPy.ui import userinput, OptionsList, Option import zgf_grompp import sys import re import os from subprocess import Popen, PIPE import numpy as np import shutil from tempfile import mktemp #=============================================================================== options_desc = OptionsList([ Option("b", "bt", "choice", "Box type", choices=("dodecahedron", "octahedron", "triclinic", "cubic")), Option("x", "box-x", "float", "Box vector length (x)", default=3.0, min_value=0.0), Option("y", "box-y", "float", "Box vector length (y)", default=3.0, min_value=0.0), Option("z", "box-z", "float", "Box vector length (z)", default=3.0, min_value=0.0), Option("s", "solv-model", "choice", "Solvent model", choices=("tip3p", "tip4p", "tip4pew", "tip5p", "spc", "spce", "acetonitrile")), Option("g", "grompp", "file", extension="mdp", default="em.mdp"), ]) sys.modules[__name__].__doc__ += options_desc.epytext() # for epydoc def is_applicable(): pool = Pool() return(len(pool.where("state == 'grompp-able'")) > 0) #=============================================================================== def main(): options = options_desc.parse_args(sys.argv)[0] pool = Pool() needy_nodes = pool.where("state == 'grompp-able'") assert(len(needy_nodes) == len(needy_nodes.multilock())) # make sure we lock ALL nodes if(options.solv_model == "tip3p"): solv_box = "spc216.gro" solv_fn = "tip3p.itp" elif(options.solv_model == "tip4p"): solv_box = "tip4p.gro" solv_fn = "tip4p.itp" elif(options.solv_model == "tip4pew"): solv_box = "tip4p.gro" solv_fn = "tip4pew.itp" elif(options.solv_model == "tip5"): solv_box = "tip5p.gro" solv_fn = "tip5p.itp" elif(options.solv_model == "spc"): solv_box = "spc216.gro" solv_fn = "spc.itp" elif(options.solv_model == "spce"): solv_box = "spc216.gro" solv_fn = "spce.itp" elif(options.solv_model == "acetonitrile"): # TODO one might change this one to "custom" and let user enter name of template box solv_box = "acetonitrile.pdb" msg = "Topology update for acetonitrile is not supported. Proceed?" if not(userinput(msg, "bool")): for n in needy_nodes: n.unlock() return("Quit by user.") # determine maximum length of linears, if any max_linear = query_linear_length(pool) # make box and fill with solvent genbox(pool, max_linear, options.bt, (options.box_x, options.box_y, options.box_z), solv_box) # update topology files (add solvent model and ions includes) if not(options.solv_model == "acetonitrile"): update_tops(pool, solv_fn) for n in needy_nodes: n.state = "em-grompp-able" zgf_grompp.call_grompp(n, mdp_file=options.grompp, final_state="em-mdrun-able") # re-grompp to get a tpr for energy minimization n.unlock() #=============================================================================== def query_linear_length(pool): max_length = 0.0 for n in pool.where("state == 'grompp-able'"): for c in pool.converter: if isinstance(c, LinearCoordinate): lin_length = c.scaled2real( n.internals.getcoord(c) ) if(lin_length > max_length): max_length = lin_length return(max_length) #=============================================================================== def genbox(pool, max_linear, boxtype, dims, solv_box, slack=1.0): # it has to hold that Gromacs box size >= 2*maximum distance restraint length new_dims = () healthy_dim = np.round(max_linear, 3)*2+slack for dim in dims: if(dim < healthy_dim): new_dims = new_dims+(healthy_dim,) else: new_dims = new_dims+(dim,) if not(dims == new_dims): print "Box dimensions changed in order to make room for distance restraints:" print "(%.3f,%.3f,%.3f)"%new_dims n_solmols = [] for n in pool.where("state == 'grompp-able'"): cmd = ["editconf", "-f", n.pdb_fn, "-o", n.pdb_fn, "-bt", boxtype, "-box"] + [str(dim) for dim in new_dims] print("Calling: %s"%" ".join(cmd)) p = Popen(cmd) retcode = p.wait() assert(retcode == 0) # editconf should never fail genbox_fn = mktemp(suffix=".pdb", dir=n.dir) # 1st genbox: finding out how many solvent molecules we can fit in cmd = ["genbox", "-cp", n.pdb_fn, "-o", genbox_fn, "-cs", solv_box] print("Calling: %s"%" ".join(cmd)) p = Popen(cmd, stdout=PIPE, stderr=PIPE) stderr = p.communicate()[1] assert(p.returncode == 0) # genbox should never fail foo = re.search("\nAdded \d+ molecules\n", stderr, re.DOTALL).group(0) n_solmols.append( int( re.findall("\d+", foo)[0] ) ) os.remove(genbox_fn) max_solmols = min(n_solmols) print "Maximum number of SOL molecules per box is %d."%max_solmols for n in pool.where("state == 'grompp-able'"): # 2nd genbox: filling each box with an equal number of solvent molecules cmd = ["genbox", "-cp", n.pdb_fn, "-o", n.pdb_fn, "-cs", solv_box, "-maxsol", str(max_solmols), "-p", n.top_fn] print("Calling: %s"%" ".join(cmd)) p = Popen(cmd) retcode = p.wait() assert(p.returncode == 0) # genbox should never fail #=============================================================================== def update_tops(pool, solv_fn): rawdata = open(pool.top_fn).read() all_incs = re.findall('#include\s+"([^"]*)"(?=\s)', rawdata) ff_inc = [inc for inc in all_incs if 'forcefield.itp' in inc ] assert(len(ff_inc) == 1) # find out name of force field ff_dir = ff_inc[0].rsplit("/", 1)[0] solv_fn = ff_dir+"/"+solv_fn ions_fn = ff_dir+"/ions.itp" inc_solv = False inc_ions = False if not ( solv_fn in all_incs ): inc_solv = True print "Will include %s into topologies ..."%solv_fn if not ( ions_fn in all_incs ): inc_ions = True print "Will include %s into topologies ..."%ions_fn # update topologies if(inc_solv or inc_ions): import fileinput toplist = [pool.top_fn] + [n.top_fn for n in pool.where("state == 'grompp-able'")] for top_fn in toplist: process = False for line in fileinput.input(top_fn, inplace=1): if line.startswith('#include "'+ff_inc[0]+'"'): process = True else: if process: if(inc_solv): print '#include "'+solv_fn+'"' if(inc_ions): print '#include "'+ions_fn+'"' process = False sys.stdout.write(line) #=============================================================================== if(__name__ == "__main__"): main() #EOF
CMD-at-ZIB/ZIBMolPy
tools/zgf_solvate_nodes.py
Python
lgpl-3.0
7,226
[ "Gromacs" ]
5e69f393d7abd1b2f88ed518bba60a9e8a042c6b988438d881ffc296f2f4886d
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- http://www.mdanalysis.org # Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under the GNU Public Licence, v2 or any higher version # # Please cite your use of MDAnalysis in published work: # # R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler, # D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein. # MDAnalysis: A Python package for the rapid analysis of molecular dynamics # simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th # Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy. # # N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein. # MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # """ HOOMD XML topology parser ========================= .. versionadded:: 0.11.0 The :class:`HoomdXMLParser` generates a topology from files for the HOOMD_ code. Read a list of atoms from a `HOOMD XML`_ file to build a basic topology. Masses and charges are set to zero if not present in the XML file. Hoomd XML does not identify molecules or residues, so placeholder values are used for residue numbers. Bonds and angles are read if present. .. _HOOMD: http://codeblue.umich.edu/hoomd-blue/index.html .. _HOOMD XML: http://codeblue.umich.edu/hoomd-blue/doc/page_xml_file_format.html Classes ------- .. autoclass:: HoomdXMLParser :members: :inherited-members: """ from __future__ import absolute_import import xml.etree.ElementTree as ET import numpy as np from . import guessers from ..lib.util import openany from .base import TopologyReaderBase from ..core.topology import Topology from ..core.topologyattrs import ( Atomtypes, Atomids, Angles, Bonds, Charges, Dihedrals, Impropers, Masses, Radii, Resids, Resnums, Segids, ) class HoomdXMLParser(TopologyReaderBase): """Parses a Hoomd XML file to create a Topology Reads the following Attributes: - Atomtypes - Bonds - Angles - Dihedrals - Impropers - Radii - Masses """ format = 'XML' def parse(self): """Parse Hoomd XML file Hoomd XML format does not contain a node for names. The parser will look for a name node anyway, and if it doesn't find one, it will use the atom types as names. If the Hoomd XML file doesn't contain a type node (it should), then all atom types will be \'none\'. Similar to the names, the parser will try to read atom type, mass, and charge from the XML file, but it will use placeholder values if they are not present. Because Hoomd uses unitless mass, charge, etc., if they are not present they will not be guessed - they will be set to zero. .. versionadded:: 0.11.0 """ with openany(self.filename) as stream: tree = ET.parse(stream) root = tree.getroot() configuration = root.find('configuration') natoms = int(configuration.get('natoms')) attrs = {} atype = configuration.find('type') atypes = atype.text.strip().split('\n') if len(atypes) != natoms: raise IOError("Number of types does not equal natoms.") attrs['types'] = Atomtypes(np.array(atypes, dtype=object)) for attrname, attr, mapper, dtype in ( ('diameter', Radii, lambda x: float(x) / 2., np.float32), ('mass', Masses, float, np.float64), ('charge', Charges, float, np.float32), ): try: val = configuration.find(attrname) vals = map(mapper, val.text.strip().split()) except: pass else: attrs[attrname] = attr(np.array(vals, dtype=dtype)) for attrname, attr, in ( ('bond', Bonds), ('angle', Angles), ('dihedral', Dihedrals), ('improper', Impropers), ): try: val = configuration.find(attrname) vals = [tuple(map(int, line.split()[1:])) for line in val.text.strip().split('\n') if line.strip()] except: pass else: if vals: attrs[attrname] = attr(vals) if not 'masses' in attrs: attrs['masses'] = Masses(np.zeros(natoms)) if not 'charges' in attrs: attrs['charges'] = Charges(np.zeros(natoms, dtype=np.float32)) attrs = list(attrs.values()) attrs.append(Atomids(np.arange(natoms) + 1)) attrs.append(Resids(np.array([1]))) attrs.append(Resnums(np.array([1]))) attrs.append(Segids(np.array(['SYSTEM'], dtype=object))) top = Topology(natoms, 1, 1, attrs=attrs) return top
kain88-de/mdanalysis
package/MDAnalysis/topology/HoomdXMLParser.py
Python
gpl-2.0
5,182
[ "HOOMD-blue", "MDAnalysis" ]
f830209c3eecfcd51a35ea2d0789fb23ab39f84875caafb056c9378b81e6cb63
from __main__ import vtk, qt, ctk, slicer import string import numpy import math import operator import collections from functools import reduce class MorphologyStatistics: def __init__(self, labelNodeSpacing, matrixSA, matrixSACoordinates, matrixSAValues, allKeys): self.morphologyStatistics = collections.OrderedDict() self.morphologyStatisticsTiming = collections.OrderedDict() self.morphologyStatistics["Volume mm^3"] = 'self.volumeMM3(self.matrixSAValues, self.cubicMMPerVoxel)' self.morphologyStatistics[ "Volume cc"] = 'self.volumeCC(self.matrixSAValues, self.cubicMMPerVoxel, self.ccPerCubicMM)' self.morphologyStatistics[ "Surface Area mm^2"] = 'self.surfaceArea(self.matrixSA, self.matrixSACoordinates, self.matrixSAValues, self.labelNodeSpacing)' self.morphologyStatistics[ "Surface:Volume Ratio"] = 'self.surfaceVolumeRatio(self.morphologyStatistics["Surface Area mm^2"], self.morphologyStatistics["Volume mm^3"])' self.morphologyStatistics[ "Compactness 1"] = 'self.compactness1(self.morphologyStatistics["Surface Area mm^2"], self.morphologyStatistics["Volume mm^3"])' self.morphologyStatistics[ "Compactness 2"] = 'self.compactness2(self.morphologyStatistics["Surface Area mm^2"], self.morphologyStatistics["Volume mm^3"])' self.morphologyStatistics[ "Maximum 3D Diameter"] = 'self.maximum3DDiameter(self.labelNodeSpacing, self.matrixSA, self.matrixSACoordinates)' self.morphologyStatistics[ "Spherical Disproportion"] = 'self.sphericalDisproportion(self.morphologyStatistics["Surface Area mm^2"], self.morphologyStatistics["Volume mm^3"])' self.morphologyStatistics[ "Sphericity"] = 'self.sphericityValue(self.morphologyStatistics["Surface Area mm^2"], self.morphologyStatistics["Volume mm^3"])' self.keys = set(allKeys).intersection(list(self.morphologyStatistics.keys())) self.labelNodeSpacing = labelNodeSpacing self.matrixSA = matrixSA self.matrixSACoordinates = matrixSACoordinates self.matrixSAValues = matrixSAValues self.cubicMMPerVoxel = reduce(lambda x, y: x * y, self.labelNodeSpacing) self.ccPerCubicMM = 0.001 def volumeMM3(self, matrixSA, cubicMMPerVoxel): return (matrixSA.size * cubicMMPerVoxel) def volumeCC(self, matrixSA, cubicMMPerVoxel, ccPerCubicMM): return (matrixSA.size * cubicMMPerVoxel * ccPerCubicMM) def surfaceArea(self, a, matrixSACoordinates, matrixSAValues, labelNodeSpacing): x, y, z = labelNodeSpacing xz = x * z yz = y * z xy = x * y voxelTotalSA = (2 * xy + 2 * xz + 2 * yz) totalSA = matrixSAValues.size * voxelTotalSA # in matrixSACoordinates # i corresponds to height (z) # j corresponds to vertical (y) # k corresponds to horizontal (x) i, j, k = 0, 0, 0 surfaceArea = 0 for voxel in range(0, matrixSAValues.size): i, j, k = matrixSACoordinates[0][voxel], matrixSACoordinates[1][voxel], matrixSACoordinates[2][voxel] fxy = (numpy.array([a[i + 1, j, k], a[i - 1, j, k]]) == 0) # evaluate to 1 if true, 0 if false fyz = (numpy.array([a[i, j + 1, k], a[i, j - 1, k]]) == 0) # evaluate to 1 if true, 0 if false fxz = (numpy.array([a[i, j, k + 1], a[i, j, k - 1]]) == 0) # evaluate to 1 if true, 0 if false surface = (numpy.sum(fxz) * xz) + (numpy.sum(fyz) * yz) + (numpy.sum(fxy) * xy) surfaceArea += surface return (surfaceArea) def surfaceVolumeRatio(self, surfaceArea, volumeMM3): return (surfaceArea / volumeMM3) def compactness1(self, surfaceArea, volumeMM3): return ((volumeMM3) / ((surfaceArea) ** (2 / 3.0) * math.sqrt(math.pi))) def compactness2(self, surfaceArea, volumeMM3): return ((36 * math.pi) * ((volumeMM3) ** 2) / ((surfaceArea) ** 3)) def maximum3DDiameter(self, labelNodeSpacing, matrixSA, matrixSACoordinates): # largest pairwise euclidean distance between tumor surface voxels x, y, z = labelNodeSpacing minBounds = numpy.array( [numpy.min(matrixSACoordinates[0]), numpy.min(matrixSACoordinates[1]), numpy.min(matrixSACoordinates[2])]) maxBounds = numpy.array( [numpy.max(matrixSACoordinates[0]), numpy.max(matrixSACoordinates[1]), numpy.max(matrixSACoordinates[2])]) a = numpy.array(list(zip(*matrixSACoordinates))) edgeVoxelsMinCoords = numpy.vstack( [a[a[:, 0] == minBounds[0]], a[a[:, 1] == minBounds[1]], a[a[:, 2] == minBounds[2]]]) * [z, y, x] edgeVoxelsMaxCoords = numpy.vstack( [(a[a[:, 0] == maxBounds[0]] + 1), (a[a[:, 1] == maxBounds[1]] + 1), (a[a[:, 2] == maxBounds[2]] + 1)]) * [ z, y, x] maxDiameter = 1 for voxel1 in edgeVoxelsMaxCoords: for voxel2 in edgeVoxelsMinCoords: voxelDistance = numpy.sqrt(numpy.sum((voxel2 - voxel1) ** 2)) if voxelDistance > maxDiameter: maxDiameter = voxelDistance return (maxDiameter) def sphericalDisproportion(self, surfaceArea, volumeMM3): R = ((0.75 * (volumeMM3)) / (math.pi) ** (1 / 3.0)) return ((surfaceArea) / (4 * math.pi * (R ** 2))) def sphericityValue(self, surfaceArea, volumeMM3): return (((math.pi) ** (1 / 3.0) * (6 * volumeMM3) ** (2 / 3.0)) / (surfaceArea)) def EvaluateFeatures(self, printTiming=False, checkStopProcessFunction=None): # Evaluate dictionary elements corresponding to user-selected keys if not self.keys: return self.morphologyStatistics if len(self.matrixSA) == 0: for key in self.keys: self.morphologyStatistics[key] = 0 else: # Volume and Surface Area are pre-calculated even if only one morphology metric is user-selected if printTiming: import time t1 = time.time() self.morphologyStatistics["Volume mm^3"] = eval(self.morphologyStatistics["Volume mm^3"]) self.keys.add("Volume mm^3") if printTiming: self.morphologyStatisticsTiming["Volume mm^3"] = time.time() - t1 self.morphologyStatistics["Surface Area mm^2"] = eval(self.morphologyStatistics["Surface Area mm^2"]) self.keys.add("Surface Area mm^2") if printTiming: t1 = time.time() self.morphologyStatisticsTiming["Surface Area mm^2"] = time.time() - t1 # Remove all the keys that must not be evaluated for key in set(self.morphologyStatistics.keys()).difference(self.keys): self.morphologyStatistics[key] = None if printTiming: for key in self.keys: if isinstance(self.morphologyStatistics[key], str): t1 = time.time() self.morphologyStatistics[key] = eval(self.morphologyStatistics[key]) self.morphologyStatisticsTiming[key] = time.time() - t1 if checkStopProcessFunction is not None: checkStopProcessFunction() return self.morphologyStatistics, self.morphologyStatisticsTiming else: for key in self.keys: if isinstance(self.morphologyStatistics[key], str): self.morphologyStatistics[key] = eval(self.morphologyStatistics[key]) if checkStopProcessFunction is not None: checkStopProcessFunction() return self.morphologyStatistics
acil-bwh/SlicerCIP
Scripted/CIP_LesionModel/FeatureExtractionLib/MorphologyStatistics.py
Python
bsd-3-clause
7,867
[ "VTK" ]
eb31f14c153c549d8b01f5c8560852039ca9408df58b0dbf869b130d0fab560c
""" Unit tests for base DataProviders. .. seealso:: galaxy.datatypes.dataproviders.base """ # currently because of dataproviders.dataset importing galaxy.model this doesn't work #TODO: fix imports there after dist and retry #TODO: fix off by ones in FilteredDataProvider counters import imp import os import unittest import StringIO import tempfilecache import test_base_dataproviders utility = imp.load_source( 'utility', os.path.join( os.path.dirname( __file__ ), '../../util/utility.py' ) ) log = utility.set_up_filelogger( __name__ + '.log' ) utility.add_galaxy_lib_to_path( 'test/unit/datatypes/dataproviders' ) from galaxy import eggs from galaxy.datatypes.dataproviders import line _TODO = """ TestCase hierarchy is a bit of mess here. """ class Test_FilteredLineDataProvider( test_base_dataproviders.Test_FilteredDataProvider ): provider_class = line.FilteredLineDataProvider default_file_contents = """ # this should be stripped out One # as should blank lines # preceding/trailing whitespace too Two Three """ def parses_default_content_as( self ): return [ 'One', 'Two', 'Three' ] def test_counters( self ): """should count: lines read, lines that passed the filter, lines returned """ ( contents, provider, data ) = self.contents_provider_and_data() self.assertCounters( provider, 7, 3, 3 ) def test_filter_fn( self ): """should filter out lines using filter_fn and set counters properly based on filter """ def filter_ts( string ): if string.lower().startswith( 't' ): return None return string ( contents, provider, data ) = self.contents_provider_and_data( filter_fn=filter_ts ) self.assertCounters( provider, 7, 1, 1 ) def test_limit_with_offset( self ): def limit_offset_combo( limit, offset, data_should_be, read, valid, returned ): ( contents, provider, data ) = self.contents_provider_and_data( limit=limit, offset=offset ) self.assertEqual( data, data_should_be ) #self.assertCounters( provider, read, valid, returned ) result_data = self.parses_default_content_as() test_data = [ ( 0, 0, [], 0, 0, 0 ), ( 1, 0, self.parses_default_content_as()[:1], 1, 1, 1 ), ( 2, 0, self.parses_default_content_as()[:2], 2, 2, 2 ), ( 3, 0, self.parses_default_content_as()[:3], 3, 3, 3 ), ( 1, 1, self.parses_default_content_as()[1:2], 1, 1, 1 ), ( 2, 1, self.parses_default_content_as()[1:3], 2, 2, 2 ), ( 3, 1, self.parses_default_content_as()[1:3], 2, 2, 2 ), ( 1, 2, self.parses_default_content_as()[2:3], 1, 1, 1 ), ( 2, 2, self.parses_default_content_as()[2:3], 1, 1, 1 ), ( 3, 2, self.parses_default_content_as()[2:3], 1, 1, 1 ), ] for test in test_data: log.debug( 'limit_offset_combo: %s', ', '.join([ str( e ) for e in test ]) ) limit_offset_combo( *test ) def test_provide_blank( self ): """should return blank lines if ``provide_blank`` is true. """ ( contents, provider, data ) = self.contents_provider_and_data( provide_blank=True ) self.assertEqual( data, [ 'One', '', 'Two', 'Three' ] ) self.assertCounters( provider, 7, 4, 4 ) def test_strip_lines( self ): """should return unstripped lines if ``strip_lines`` is false. """ ( contents, provider, data ) = self.contents_provider_and_data( strip_lines=False ) self.assertEqual( data, ['One\n', '\n', ' Two\n', 'Three\n'] ) self.assertCounters( provider, 7, 4, 4 ) def test_comment_char( self ): """should return unstripped lines if ``strip_lines`` is false. """ ( contents, provider, data ) = self.contents_provider_and_data( comment_char='T' ) self.assertEqual( data, [ '# this should be stripped out', 'One', '# as should blank lines', '# preceding/trailing whitespace too' ] ) self.assertCounters( provider, 7, 4, 4 ) class Test_RegexLineDataProvider( Test_FilteredLineDataProvider ): provider_class = line.RegexLineDataProvider default_file_contents = """ # this should be stripped out One # as should blank lines # preceding/trailing whitespace too Two Three """ def test_regex( self ): """should return lines matching regex (AFTER strip, comments, blanks). """ ( contents, provider, data ) = self.contents_provider_and_data( regex_list=[ r'^O' ] ) self.assertEqual( data, [ 'One' ] ) self.assertCounters( provider, 7, 1, 1 ) def test_regex_list( self ): """should return regex matches using more than one regex by ORing them. """ ( contents, provider, data ) = self.contents_provider_and_data( regex_list=[ r'^O', r'T' ] ) self.assertEqual( data, [ 'One', 'Two', 'Three' ] ) self.assertCounters( provider, 7, 3, 3 ) def test_inverse( self ): """should return inverse matches when ``invert`` is true. """ ( contents, provider, data ) = self.contents_provider_and_data( regex_list=[ r'^O' ], invert=True ) self.assertEqual( data, [ 'Two', 'Three' ] ) self.assertCounters( provider, 7, 2, 2 ) def test_regex_no_match( self ): """should return empty if no regex matches. """ ( contents, provider, data ) = self.contents_provider_and_data( regex_list=[ r'^Z' ] ) self.assertEqual( data, [] ) self.assertCounters( provider, 7, 0, 0 ) def test_regex_w_limit_offset( self ): """regex should play well with limit and offset """ ( contents, provider, data ) = self.contents_provider_and_data( regex_list=[ r'^T' ], limit=1 ) self.assertEqual( data, [ 'Two' ] ) #TODO: once again, valid data, returned data is off self.assertCounters( provider, 6, 1, 1 ) ( contents, provider, data ) = self.contents_provider_and_data( regex_list=[ r'^T' ], limit=1, offset=1 ) self.assertEqual( data, [ 'Three' ] ) self.assertCounters( provider, 7, 2, 1 ) class Test_BlockDataProvider( test_base_dataproviders.Test_FilteredDataProvider ): provider_class = line.BlockDataProvider default_file_contents = """ One ABCD Two ABCD EFGH Three """ def parses_default_content_as( self ): return [ ['One'], ['ABCD'], ['Two'], ['ABCD'], ['EFGH'], ['Three'] ] #TODO: well, this is ham-handed... def test_stringio( self ): pass def test_iterators( self ): pass def test_readlines( self ): pass def test_file( self ): """should work with files """ ( contents, provider, data ) = self.contents_provider_and_data() self.assertEqual( data, self.parses_default_content_as() ) self.assertTrue( isinstance( provider.source, line.FilteredLineDataProvider ) ) self.assertTrue( isinstance( provider.source.source, file ) ) # provider should call close on file self.assertTrue( provider.source.source.closed ) def test_counters( self ): """should count: lines read, lines that passed the filter, lines returned """ ( contents, provider, data ) = self.contents_provider_and_data() self.assertCounters( provider, 6, 6, 6 ) def test_filter_fn( self ): """should filter out lines using filter_fn and set counters properly based on filter """ def filter_ts( string ): if string.lower().startswith( 't' ): return None return string ( contents, provider, data ) = self.contents_provider_and_data( filter_fn=filter_ts ) # no block fns here, so will parse as lines self.assertEqual( data, [ ['One'], ['ABCD'], ['ABCD'], ['EFGH'] ] ) self.assertCounters( provider, 4, 4, 4 ) def test_new_block_delim_fn( self ): """should return blocks based on ``new_block_delim_fn`` """ def is_not_indented( line ): strip_diff = len( line ) - len( line.lstrip() ) return ( strip_diff == 0 ) # in order to use indentation as a delimiter, we need to strip the newlines only ( contents, provider, data ) = self.contents_provider_and_data( strip_lines=False, strip_newlines=True, new_block_delim_fn=is_not_indented ) self.assertEqual( data, [[ 'One', ' ABCD' ], [ 'Two', ' ABCD', ' EFGH' ], [ 'Three' ]] ) self.assertCounters( provider, 3, 3, 3 ) def test_block_filter_fn( self ): """should return blocks only blocks that pass ``block_filter_fn`` """ def is_not_indented( line ): strip_diff = len( line ) - len( line.lstrip() ) return ( strip_diff == 0 ) #def empty_block( block ): # if len( block ) <= 1: # return None # return block def no_tw( block ): if block[0].startswith( 'Tw' ): return None return block ( contents, provider, data ) = self.contents_provider_and_data( strip_lines=False, strip_newlines=True, new_block_delim_fn=is_not_indented, block_filter_fn=no_tw ) self.assertEqual( data, [[ 'One', ' ABCD' ], [ 'Three' ]] ) self.assertCounters( provider, 3, 2, 2 ) def test_hack_block_filter_fn( self ): """should allow other aggregating/mod use in filter_fn Although, it would be better to subclass and override assemble_current_block """ def is_not_indented( line ): strip_diff = len( line ) - len( line.lstrip() ) return ( strip_diff == 0 ) def empty_block( block ): if len( block ) <= 1: return None return { 'header': block[0].strip(), 'data': [ b.strip() for b in block[1:] if b.strip() ] } ( contents, provider, data ) = self.contents_provider_and_data( strip_lines=False, strip_newlines=True, new_block_delim_fn=is_not_indented, block_filter_fn=empty_block ) self.assertEqual( data, [ { 'header': 'One', 'data': [ 'ABCD' ]}, { 'header': 'Two', 'data': [ 'ABCD', 'EFGH' ]} ]) self.assertCounters( provider, 3, 2, 2 ) def test_block_filter_fn_w_limit_offset( self ): """should allow both block fns and limit, offset """ def is_not_indented( line ): strip_diff = len( line ) - len( line.lstrip() ) return ( strip_diff == 0 ) def empty_block( block ): if len( block ) <= 1: return None return block ( contents, provider, data ) = self.contents_provider_and_data( strip_lines=False, strip_newlines=True, new_block_delim_fn=is_not_indented, block_filter_fn=empty_block, limit=1 ) self.assertEqual( data, [[ 'One', ' ABCD' ]] ) self.assertCounters( provider, 1, 1, 1 ) ( contents, provider, data ) = self.contents_provider_and_data( strip_lines=False, strip_newlines=True, new_block_delim_fn=is_not_indented, block_filter_fn=empty_block, limit=2, offset=1 ) self.assertEqual( data, [[ 'Two', ' ABCD', ' EFGH' ]] ) self.assertCounters( provider, 3, 2, 1 ) def test_simple_example( self ): """ """ file_contents = """ >One ABCD # this comment (and the blank line above) won't be included >Two ABCD EFGH """ def fasta_header( line ): return line.startswith( '>' ) def id_seq( block ): return { 'id': block[0][1:], 'seq': ( ''.join( block[1:] ) ) } ( contents, provider, data ) = self.contents_provider_and_data( contents=file_contents, new_block_delim_fn=fasta_header, block_filter_fn=id_seq ) self.assertEqual( data, [{ 'id': 'One', 'seq': 'ABCD' }, { 'id': 'Two', 'seq': 'ABCDEFGH' }] ) self.assertCounters( provider, 2, 2, 2 ) if __name__ == '__main__': unittest.main()
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/test/unit/datatypes/dataproviders/test_line_dataproviders.py
Python
gpl-3.0
12,462
[ "Galaxy" ]
fe617c812d2da296d342e4cee36e10045059173a01deb0b8971a923b0526d7b9
# Version: 0.10 """ The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, and 3.2, 3.3 [![Build Status](https://travis-ci.org/warner/python-versioneer.png?branch=master)](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * run `versioneer-installer` in your source tree: this installs `versioneer.py` * follow the instructions below (also in the `versioneer.py` docstring) ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS variable ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example 'git describe --tags --dirty --always' reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. However, when you use "setup.py build" or "setup.py sdist", `_version.py` in the new copy is replaced by a small static file that contains just the generated version data. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the "git archive" command. As a result, generated tarballs will contain enough information to get the proper version. ## Installation First, decide on values for the following configuration variables: * `versionfile_source`: A project-relative pathname into which the generated version strings should be written. This is usually a `_version.py` next to your project's main `__init__.py` file. If your project uses `src/myproject/__init__.py`, this should be `src/myproject/_version.py`. This file should be checked in to your VCS as usual: the copy created below by `setup.py versioneer` will include code that parses expanded VCS keywords in generated tarballs. The 'build' and 'sdist' commands will replace it with a copy that has just the calculated version string. * `versionfile_build`: Like `versionfile_source`, but relative to the build directory instead of the source directory. These will differ when your setup.py uses 'package_dir='. If you have `package_dir={'myproject': 'src/myproject'}`, then you will probably have `versionfile_build='myproject/_version.py'` and `versionfile_source='src/myproject/_version.py'`. * `tag_prefix`: a string, like 'PROJECTNAME-', which appears at the start of all VCS tags. If your tags look like 'myproject-1.2.0', then you should use tag_prefix='myproject-'. If you use unprefixed tags like '1.2.0', this should be an empty string. * `parentdir_prefix`: a string, frequently the same as tag_prefix, which appears at the start of all unpacked tarball filenames. If your tarball unpacks into 'myproject-1.2.0', this should be 'myproject-'. This tool provides one script, named `versioneer-installer`. That script does one thing: write a copy of `versioneer.py` into the current directory. To versioneer-enable your project: * 1: Run `versioneer-installer` to copy `versioneer.py` into the top of your source tree. * 2: add the following lines to the top of your `setup.py`, with the configuration values you decided earlier: import versioneer versioneer.versionfile_source = 'src/myproject/_version.py' versioneer.versionfile_build = 'myproject/_version.py' versioneer.tag_prefix = '' # tags are like 1.2.0 versioneer.parentdir_prefix = 'myproject-' # dirname like 'myproject-1.2.0' * 3: add the following arguments to the setup() call in your setup.py: version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), * 4: now run `setup.py versioneer`, which will create `_version.py`, and will modify your `__init__.py` to define `__version__` (by calling a function from `_version.py`). It will also modify your `MANIFEST.in` to include both `versioneer.py` and the generated `_version.py` in sdist tarballs. * 5: commit these changes to your VCS. To make sure you won't forget, `setup.py versioneer` will mark everything it touched for addition. ## Post-Installation Usage Once established, all uses of your tree from a VCS checkout should get the current version string. All generated tarballs should include an embedded version string (so users who unpack them will not need a VCS tool installed). If you distribute your project through PyPI, then the release process should boil down to two steps: * 1: git tag 1.0 * 2: python setup.py register sdist upload If you distribute it through github (i.e. users use github to generate tarballs with `git archive`), the process is: * 1: git tag 1.0 * 2: git push; git push --tags Currently, all version strings must be based upon a tag. Versioneer will report "unknown" until your tree has at least one tag in its history. This restriction will be fixed eventually (see issue #12). ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different keys for different flavors of the version string: * `['version']`: condensed tag+distance+shortid+dirty identifier. For git, this uses the output of `git describe --tags --dirty --always` but strips the tag_prefix. For example "0.11-2-g1076c97-dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes ("-dirty"), and that this commit is two revisions ("-2-") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". * `['full']`: detailed revision identifier. For Git, this is the full SHA1 commit id, followed by "-dirty" if the tree contains uncommitted changes, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac-dirty". Some variants are more useful than others. Including `full` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. In the future, this will also include a [PEP-0440](http://legacy.python.org/dev/peps/pep-0440/) -compatible flavor (e.g. `1.2.post0.dev123`). This loses a lot of information (and has no room for a hash-based revision id), but is safe to use in a `setup.py` "`version=`" argument. It also enables tools like *pip* to compare version strings and evaluate compatibility constraint declarations. The `setup.py versioneer` command adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version = get_versions()['version'] del get_versions ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * re-run `versioneer-installer` in your source tree to replace `versioneer.py` * edit `setup.py`, if necessary, to include any new configuration settings indicated by the release notes * re-run `setup.py versioneer` to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is hereby released into the public domain. The `_version.py` that it creates is also in the public domain. """ import os, sys, re from distutils.core import Command from distutils.command.sdist import sdist as _sdist from distutils.command.build import build as _build from distutils.command.build_py import build_py as _build_py versionfile_source = None versionfile_build = None tag_prefix = None parentdir_prefix = None lookupfile = None VCS = "git" LONG_VERSION_PY = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (build by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.10 (https://github.com/warner/python-versioneer) # these strings will be replaced by git during git-archive git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" import subprocess import sys import errno def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): assert isinstance(commands, list) p = None for c in commands: try: # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% args[0]) print(e) return None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None stdout = p.communicate()[0].strip() if sys.version >= '3': stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% args[0]) return None return stdout import sys import re import os.path def get_gits(root, verbose=False): if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %%s" %% root) return None GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] return GITS def get_expanded_variables(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # variables. When used from setup.py, we don't want to import # _version.py, so we do it with a regexp instead. This function is not # used from _version.py. variables = {} try: f = open(versionfile_abs,"r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["full"] = mo.group(1) f.close() except EnvironmentError: pass return variables def versions_from_expanded_variables(variables, tag_prefix, verbose=False): refnames = variables["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("variables are unexpanded, not using") return {} # unexpanded, so not in an unpacked git-archive tarball refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs-tags)) branches = [r for r in refs if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/")] if branches: branch = branches[0] else: branch = "unknown" if verbose: print("likely tags: %s" % ",".join(sorted(tags))) print("likely branches: %s" % ",".join(sorted(branches))) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return { "version": r, "full": variables["full"].strip(), "branch": branch} # no suitable tags, so we use the full revision id if verbose: print("no suitable tags, using full revision id") return { "version": variables["full"].strip(), "full": variables["full"].strip(), "branch": "unknown"} def versions_from_lookup(lookup, root, verbose=False): GITS = get_gits(root, verbose=verbose) if GITS is None: return {} stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if stdout is None: return {} current_branch = stdout.strip() for matcher, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: return {} stdout = run_command(GITS, ["rev-list", "%%s..HEAD" %% ref_commit, "--count"], cwd=root) if stdout is None: return {} num_commits = stdout.strip() stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) if stdout is None: return {} short_hash = stdout.strip() stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: return {} dirty = stdout.strip().endswith("-dirty") stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() version = "%%s-%%s-g%%s" %% (tag, num_commits, short_hash) if dirty: version += "-dirty" full += "-dirty" return {"version": version, "full": full, "branch": current_branch} return {} def versions_from_vcs(tag_prefix, root, verbose=False): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' variables were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. GITS = get_gits(root, verbose=verbose) if GITS is None: return {} stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: return {} if not stdout.startswith(tag_prefix): if verbose: print("tag '%%s' doesn't start with prefix '%%s'" %% (stdout, tag_prefix)) return {} tag = stdout[len(tag_prefix):] stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() if tag.endswith("-dirty"): full += "-dirty" stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if stdout is None: branch = None else: branch = stdout.strip() return {"version": tag, "full": full, "branch": branch} def versions_from_parentdir(parentdir_prefix, root, verbose=False): # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%%s', but '%%s' doesn't start with prefix '%%s'" %% (root, dirname, parentdir_prefix)) return None return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""} tag_prefix = "%(TAG_PREFIX)s" parentdir_prefix = "%(PARENTDIR_PREFIX)s" versionfile_source = "%(VERSIONFILE_SOURCE)s" lookupfile = %(LOOKUPFILE)s def parse_lookup_file(root, lookup_path=None): if not lookup_path: lookup_path = lookupfile if not lookup_path: return [] path = os.path.join(root, lookup_path) if not os.path.exists(path): return [] import re lookup = [] with open(os.path.join(root, lookup_path), "r") as f: for line in f: if '#' in line: line = line[:line.rindex('#')] line = line.strip() try: split_line = line.split() if len(split_line) == 3: pattern, tag, ref_commit = split_line lookup.append([re.compile(pattern), tag, ref_commit]) elif len(split_line) >= 1: lookup.append([re.compile(split_line[0]), None, None]) except: break return lookup def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, verbose=False): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded variables. variables = { "refnames": git_refnames, "full": git_full } ver = versions_from_expanded_variables(variables, tag_prefix, verbose) if ver: return ver try: root = os.path.abspath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in range(len(versionfile_source.split("/"))): root = os.path.dirname(root) except NameError: return default lookup = parse_lookup_file(root, lookup_path=lookup_path) return (versions_from_lookup(lookup, root, verbose) or versions_from_vcs(tag_prefix, root, verbose) or versions_from_parentdir(parentdir_prefix, root, verbose) or default) ''' import subprocess import sys import errno def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): assert isinstance(commands, list) p = None for c in commands: try: # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % args[0]) print(e) return None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None stdout = p.communicate()[0].strip() if sys.version >= '3': stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % args[0]) return None return stdout import sys import re import os.path def get_gits(root, verbose=False): if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) return None GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] return GITS def get_expanded_variables(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # variables. When used from setup.py, we don't want to import # _version.py, so we do it with a regexp instead. This function is not # used from _version.py. variables = {} try: f = open(versionfile_abs,"r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: variables["full"] = mo.group(1) f.close() except EnvironmentError: pass return variables def versions_from_expanded_variables(variables, tag_prefix, verbose=False): refnames = variables["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("variables are unexpanded, not using") return {} # unexpanded, so not in an unpacked git-archive tarball refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) branches = [r for r in refs if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/")] if branches: branch = branches[0] else: branch = "unknown" if verbose: print("likely tags: %s" % ",".join(sorted(tags))) print("likely branches: %s" % ",".join(sorted(branches))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return { "version": r, "full": variables["full"].strip(), "branch": branch } # no suitable tags, so we use the full revision id if verbose: print("no suitable tags, using full revision id") return { "version": variables["full"].strip(), "full": variables["full"].strip(), "branch": "unknown"} def versions_from_lookup(lookup, root, verbose=False): GITS = get_gits(root, verbose=verbose) if GITS is None: return {} stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if stdout is None: return {} current_branch = stdout.strip() for matcher, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: return {} stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root) if stdout is None: return {} num_commits = stdout.strip() stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) if stdout is None: return {} short_hash = stdout.strip() stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: return {} dirty = stdout.strip().endswith("-dirty") stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() version = "%s-%s-g%s" % (tag, num_commits, short_hash) if dirty: version += "-dirty" full += "-dirty" return {"version": version, "full": full, "branch": current_branch} return {} def versions_from_vcs(tag_prefix, root, verbose=False): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' variables were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. GITS = get_gits(root, verbose=verbose) if GITS is None: return {} stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: return {} if not stdout.startswith(tag_prefix): if verbose: print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix)) return {} tag = stdout[len(tag_prefix):] stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if stdout is None: return {} full = stdout.strip() if tag.endswith("-dirty"): full += "-dirty" stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) if stdout is None: branch = None else: branch = stdout.strip() return {"version": tag, "full": full, "branch": branch} def versions_from_parentdir(parentdir_prefix, root, verbose=False): # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" % (root, dirname, parentdir_prefix)) return None return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""} import os.path import sys # os.path.relpath only appeared in Python-2.6 . Define it here for 2.5. def os_path_relpath(path, start=os.path.curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = [x for x in os.path.abspath(start).split(os.path.sep) if x] path_list = [x for x in os.path.abspath(path).split(os.path.sep) if x] # Work out how much of the filepath is shared by start and path. i = len(os.path.commonprefix([start_list, path_list])) rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return os.path.curdir return os.path.join(*rel_list) def do_vcs_install(manifest_in, versionfile_source, ipy): GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source, ipy] try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os_path_relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.10) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. version_version = '%(version)s' version_full = '%(full)s' version_branch = '%(branch)s' def get_versions(default={}, verbose=False): return {'version': version_version, 'full': version_full, 'branch': version_branch} """ DEFAULT = {"version": "unknown", "full": "unknown", "branch": "unknown"} def versions_from_file(filename): versions = {} try: f = open(filename) except EnvironmentError: return versions for line in f.readlines(): mo = re.match("version_version = '([^']+)'", line) if mo: versions["version"] = mo.group(1) mo = re.match("version_full = '([^']+)'", line) if mo: versions["full"] = mo.group(1) mo = re.match("version_branch = '([^']+)'", line) if mo: versions["branch"] = mo.group(1) f.close() return versions def write_to_version_file(filename, versions): f = open(filename, "w") f.write(SHORT_VERSION_PY % versions) f.close() print("set %s to '%s'" % (filename, versions["version"])) def get_root(): try: return os.path.dirname(os.path.abspath(__file__)) except NameError: return os.path.dirname(os.path.abspath(sys.argv[0])) def parse_lookup_file(root, lookup_path=None): if not lookup_path: lookup_path = lookupfile path = os.path.join(root, lookup_path) if not os.path.exists(path): return [] import re lookup = [] with open(os.path.join(root, lookup_path), "r") as f: for line in f: if '#' in line: line = line[:line.rindex("#")] line = line.strip() try: split_line = line.split() if len(split_line) == 3: pattern, tag, ref_commit = split_line lookup.append([re.compile(pattern), tag, ref_commit]) elif len(split_line) >= 1: lookup.append([re.compile(split_line[0]), None, None]) except: break return lookup def get_versions(default=DEFAULT, verbose=False): # returns dict with three keys: 'version', 'full' and 'branch' assert versionfile_source is not None, "please set versioneer.versionfile_source" assert tag_prefix is not None, "please set versioneer.tag_prefix" assert parentdir_prefix is not None, "please set versioneer.parentdir_prefix" # I am in versioneer.py, which must live at the top of the source tree, # which we use to compute the root directory. py2exe/bbfreeze/non-CPython # don't have __file__, in which case we fall back to sys.argv[0] (which # ought to be the setup.py script). We prefer __file__ since that's more # robust in cases where setup.py was invoked in some weird way (e.g. pip) root = get_root() versionfile_abs = os.path.join(root, versionfile_source) if lookupfile: lookup = parse_lookup_file(root, lookup_path = lookupfile) else: lookup = None # extract version from first of _version.py, 'git describe', parentdir. # This is meant to work for developers using a source checkout, for users # of a tarball created by 'setup.py sdist', and for users of a # tarball/zipball created by 'git archive' or github's download-from-tag # feature. variables = get_expanded_variables(versionfile_abs) if variables: ver = versions_from_expanded_variables(variables, tag_prefix) if ver: if verbose: print("got version from expanded variable %s" % ver) return ver ver = versions_from_file(versionfile_abs) if ver: if verbose: print("got version from file %s %s" % (versionfile_abs,ver)) return ver if lookup: ver = versions_from_lookup(lookup, root, verbose=verbose) if ver: if verbose: print("got version from lookup %s" % ver) return ver ver = versions_from_vcs(tag_prefix, root, verbose) if ver: if verbose: print("got version from git %s" % ver) return ver ver = versions_from_parentdir(parentdir_prefix, root, verbose) if ver: if verbose: print("got version from parentdir %s" % ver) return ver if verbose: print("got version from default %s" % ver) return default def get_version(verbose=False): return get_versions(verbose=verbose)["version"] class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): ver = get_version(verbose=True) print("Version is currently: %s" % ver) class cmd_build_py(_build_py): def run(self): _build_py.run(self) versions = get_versions(verbose=True) # now locate _version.py in the new build/ directory and replace it # with an updated value target_versionfile = os.path.join(self.build_lib, versionfile_build) print("UPDATING %s" % target_versionfile) if os.path.exists(target_versionfile): os.unlink(target_versionfile) f = open(target_versionfile, "w") f.write(SHORT_VERSION_PY % versions) f.close() class cmd_build(_build): def run(self): _build.run(self) versions = get_versions(verbose=True) # now locate _version.py in the new build/ directory and replace it # with an updated value target_versionfile = os.path.join(self.build_lib, versionfile_build) print("UPDATING %s" % target_versionfile) if os.path.exists(target_versionfile): os.unlink(target_versionfile) f = open(target_versionfile, "w") f.write(SHORT_VERSION_PY % versions) f.close() if 'cx_Freeze' in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe class cmd_build_exe(_build_exe): def run(self): versions = get_versions(verbose=True) target_versionfile = versionfile_source print("UPDATING %s" % target_versionfile) os.unlink(target_versionfile) f = open(target_versionfile, "w") f.write(SHORT_VERSION_PY % versions) f.close() _build_exe.run(self) os.unlink(target_versionfile) f = open(versionfile_source, "w") f.write(LONG_VERSION_PY % {"DOLLAR": "$", "TAG_PREFIX": tag_prefix, "PARENTDIR_PREFIX": parentdir_prefix, "VERSIONFILE_SOURCE": versionfile_source, "LOOKUPFILE": '"%s"' % lookupfile if lookupfile is not None else "None", }) f.close() class cmd_sdist(_sdist): def run(self): versions = get_versions(verbose=True) self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory (remembering # that it may be a hardlink) and replace it with an updated value target_versionfile = os.path.join(base_dir, versionfile_source) print("UPDATING %s" % target_versionfile) os.unlink(target_versionfile) f = open(target_versionfile, "w") f.write(SHORT_VERSION_PY % self._versioneer_generated_versions) f.close() INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ class cmd_update_files(Command): description = "install/upgrade Versioneer files: __init__.py SRC/_version.py" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): print(" creating %s" % versionfile_source) f = open(versionfile_source, "w") f.write(LONG_VERSION_PY % {"DOLLAR": "$", "TAG_PREFIX": tag_prefix, "PARENTDIR_PREFIX": parentdir_prefix, "VERSIONFILE_SOURCE": versionfile_source, "LOOKUPFILE": '"%s"' % lookupfile if lookupfile is not None else "None", }) f.close() ipy = os.path.join(os.path.dirname(versionfile_source), "__init__.py") try: old = open(ipy, "r").read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) f = open(ipy, "a") f.write(INIT_PY_SNIPPET) f.close() else: print(" %s unmodified" % ipy) # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(get_root(), "MANIFEST.in") simple_includes = set() try: for line in open(manifest_in, "r").readlines(): if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") f = open(manifest_in, "a") f.write("include versioneer.py\n") f.close() else: print(" 'versioneer.py' already in MANIFEST.in") if versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % versionfile_source) f = open(manifest_in, "a") f.write("include %s\n" % versionfile_source) f.close() else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-time keyword # substitution. do_vcs_install(manifest_in, versionfile_source, ipy) def get_cmdclass(): cmds = {'version': cmd_version, 'versioneer': cmd_update_files, 'build': cmd_build, 'build_py': cmd_build_py, 'sdist': cmd_sdist, } if 'cx_Freeze' in sys.modules: # cx_freeze enabled? cmds['build_exe'] = cmd_build_exe del cmds['build'] return cmds
dragondgold/OctoPrint
versioneer.py
Python
agpl-3.0
42,531
[ "Brian" ]
73c03de6f1aecb42147be0344cbea98982df0cf53292d5cf69a5bece31efdf23
from __future__ import division from pybec.fit1D import gauss_peak_1D, parab_peak_1D, sigmoid,\ peakguess1D, sigguess, fit1D, check_1Dfit from numpy import array, arange from numpy.random import poisson import matplotlib.pyplot as plt plt.close('all') rng = 200 X = arange(0, rng+1) n = len(X) noise = 50 N = (array([poisson(noise) for point in range(n)]) - noise) / 50 + 0 # Test Gaussian peak fitting # xc w amp bac gpar = [ rng/1.7, 30, 2.3, 0.001] G = gauss_peak_1D(gpar)(X) GN = G + N ginit_guess = peakguess1D(GN) gfit, ginfo = fit1D(GN, gauss_peak_1D, ginit_guess, err= None, return_all=True) check_1Dfit(GN, ginit_guess, gfit, gauss_peak_1D) # Test parabolic peak fitting # xc w amp bac ppar = [ rng/1.7, 30, 2.7, 0.1] P = parab_peak_1D(ppar)(X) PN = P + N pinit_guess = peakguess1D(PN) pfit, pinfo = fit1D(PN, parab_peak_1D, pinit_guess, err= None, return_all=True) check_1Dfit(PN, pinit_guess, pfit, parab_peak_1D) """ #Test sigmoisal fitting Sx = array([1.00, 1.20, 1.35, 1.38, 1.40, 1.45, 1.50, 1.60, 1.80]) Sy = array([0.05, 0.12, 0.20, 0.35, 0.30, 0.90, 0.80, 0.95, 1.00]) sinit_guess = sigguess(Sx,Sy) sfit = fit1D(Sy, sigmoid, sinit_guess, xdata = Sx, err= None) check_1Dfit(Sy, sinit_guess, sfit, sigmoid, xdata = Sx) """
kevincwright/quagmire
test_pybec/test_fit1D.py
Python
gpl-3.0
1,354
[ "Gaussian" ]
9e512439cb8a93b074f6a98918bb7d1d80ad33bdb1a84ed2dd9778da5bf47255
import os, pickle, random, time from scipy.linalg import norm, eigh, inv, pinv, pinv2, pinvh import numpy as np from sklearn.gaussian_process import GaussianProcess ttt = time.clock() if not os.path.exists('qm7.pkl'): os.system('wget http://www.quantum-machine.org/data/qm7.pkl') dataset = pickle.load(open('qm7.pkl','r')) # -------------------------------------------- # Extract training data # -------------------------------------------- split = 1 N_models = 11 P = dataset['P'][range(0,split)+range(split+1,5)].flatten() X = dataset['X'][P] T = dataset['T'][P] Ptest = dataset['P'][split] Xtest = dataset['X'][Ptest] Ttest = dataset['T'][Ptest] print "TIMER load_data", time.clock() - ttt # -------------------------------------------- # Extract feature(s) from training data # -------------------------------------------- # in this case, only sorted eigenvalues of Coulomb matrix ttt = time.clock() eigX = [(eigh(M, eigvals_only=True))[::-1] for M in X] eigt = [(eigh(M, eigvals_only=True))[::-1] for M in Xtest] print "TIMER eval_features", time.clock() -ttt # Observations y = T.ravel() alpha = [] for theta0 in np.linspace(0.01,1,N_models): # Setup a Gaussian Process model ttt = time.clock() gp = GaussianProcess(corr='absolute_exponential', theta0=theta0, nugget=1e-3, random_start=100, verbose=True) # Fit to data using Maximum Likelihood Estimation of the parameters gp.fit(eigX, y) print "TIMER teach", time.clock() - ttt # # Make the prediction on training set # y_pred, MSE = gp.predict(eigX, eval_MSE=True) # sigma = np.sqrt(MSE) # print('\n training set:') # print('MAE: %5.2f kcal/mol'%np.abs(y_pred-y).mean(axis=0)) # print('RMSE: %5.2f kcal/mol'%np.square(y_pred-y).mean(axis=0)**.5) # Make the prediction on test set y_pred, MSE = gp.predict(eigt, eval_MSE=True) sigma = np.sqrt(MSE) print('\n test set:') print('MAE: %5.2f kcal/mol'%np.abs(y_pred-Ttest.ravel()).mean(axis=0)) print('RMSE: %5.2f kcal/mol'%np.square(y_pred-Ttest.ravel()).mean(axis=0)**.5) alpha.append(gp.gamma)
marcocaccin/MarcoGP
scikit-gp.py
Python
apache-2.0
2,114
[ "Gaussian" ]
101cf12eb5793a2eaa8dbd2330c710af70ee896efef5243d2afadf664b7c5386
""" intro_3_02_example.py First example code from Section 3.2 of "Introduction to SFC Models With Python." Implements model SIM from Godley and Lavoie. Copyright 2017 Brian Romanchuk Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Step 1: Import modules # sfc_models code objects. Using "from <module> import *" is frowned upon, but I wanted to # have less lines of code for beginners to parse. from sfc_models.objects import * # Quick2DPlot() - Plotting functions used by examples; relies upon matplotlib from sfc_models.examples.Quick2DPlot import Quick2DPlot # Step 1.5: set up logging # The next line of code sets the name of the output files based on the code file's name. # This means that if you paste this code into a new file, get a new log name. register_standard_logs('output', __file__) # Step 2: build the model objects # Create model, which holds all entities mod = Model() # Create first country - Canada. (This model only has one country.) can = Country(mod, 'CA', 'Canada') # Create sectors gov = ConsolidatedGovernment(can, 'GOV', 'Government') hh = Household(can, 'HH', 'Household') # A literally non-profit business sector bus = FixedMarginBusiness(can, 'BUS', 'Business Sector', profit_margin=0.0) # Create the linkages between sectors - tax flow, markets - labour ('LAB'), goods ('GOOD') tax = TaxFlow(can, 'TF', 'TaxFlow', .2) labour = Market(can, 'LAB', 'Labour market') goods = Market(can, 'GOOD', 'Goods market') # Need to set the exogenous variable - Government demand for Goods ("G" in economist symbology) mod.AddExogenous('GOV', 'DEM_GOOD', '[20.,] * 105') # Step 3: Invoke the method ("main") that builds the model. mod.main() # Once the framework has built and solved the model equations, we can either work with the output files, # or within Python. Here, we do a plot with Quick2DPlot. mod.TimeSeriesCutoff = 20 time = mod.GetTimeSeries('k') Y_SIM = mod.GetTimeSeries('GOOD__SUP_GOOD') Quick2DPlot(time, Y_SIM, 'Output (Y) - Model SIM', filename='intro_3_02_Y.png')
brianr747/SFC_models
sfc_models/examples/scripts/intro_3_02_example.py
Python
apache-2.0
2,492
[ "Brian" ]
9024c7a0471c3fc95a1075538b1866badc85669d7c159a0f319fd73dbf29d15c
""" Acceptance tests for the Import and Export pages """ from nose.plugins.attrib import attr from datetime import datetime from abc import abstractmethod from common.test.acceptance.tests.studio.base_studio_test import StudioLibraryTest, StudioCourseTest from common.test.acceptance.pages.studio.import_export import ( ExportLibraryPage, ExportCoursePage, ImportLibraryPage, ImportCoursePage) from common.test.acceptance.pages.studio.library import LibraryEditPage from common.test.acceptance.pages.studio.overview import CourseOutlinePage from common.test.acceptance.pages.lms.courseware import CoursewarePage from common.test.acceptance.pages.lms.staff_view import StaffCoursewarePage class ExportTestMixin(object): """ Tests to run both for course and library export pages. """ def test_export(self): """ Scenario: I am able to export a course or library Given that I have a course or library And I click the download button The download will succeed And the file will be of the right MIME type. """ self.export_page.wait_for_export_click_handler() self.export_page.click_export() self.export_page.wait_for_export() good_status, is_tarball_mimetype = self.export_page.download_tarball() self.assertTrue(good_status) self.assertTrue(is_tarball_mimetype) def test_export_timestamp(self): """ Scenario: I perform a course / library export On export success, the page displays a UTC timestamp previously not visible And if I refresh the page, the timestamp is still displayed """ self.assertFalse(self.export_page.is_timestamp_visible()) # Get the time when the export has started. # export_page timestamp is in (MM/DD/YYYY at HH:mm) so replacing (second, microsecond) to # keep the comparison consistent export_start_time = datetime.utcnow().replace(microsecond=0, second=0) self.export_page.wait_for_export_click_handler() self.export_page.click_export() self.export_page.wait_for_export() # Get the time when the export has finished. # export_page timestamp is in (MM/DD/YYYY at HH:mm) so replacing (second, microsecond) to # keep the comparison consistent export_finish_time = datetime.utcnow().replace(microsecond=0, second=0) export_timestamp = self.export_page.parsed_timestamp self.export_page.wait_for_timestamp_visible() # Verify that 'export_timestamp' is between start and finish upload time self.assertLessEqual( export_start_time, export_timestamp, "Course export timestamp should be export_start_time <= export_timestamp <= export_end_time" ) self.assertGreaterEqual( export_finish_time, export_timestamp, "Course export timestamp should be export_start_time <= export_timestamp <= export_end_time" ) self.export_page.visit() self.export_page.wait_for_tasks(completed=True) self.export_page.wait_for_timestamp_visible() def test_task_list(self): """ Scenario: I should see feedback checkpoints when exporting a course or library Given that I am on an export page No task checkpoint list should be showing When I export the course or library Each task in the checklist should be marked confirmed And the task list should be visible """ # The task list shouldn't be visible to start. self.assertFalse(self.export_page.is_task_list_showing(), "Task list shown too early.") self.export_page.wait_for_tasks() self.export_page.wait_for_export_click_handler() self.export_page.click_export() self.export_page.wait_for_tasks(completed=True) self.assertTrue(self.export_page.is_task_list_showing(), "Task list did not display.") @attr(shard=7) class TestCourseExport(ExportTestMixin, StudioCourseTest): """ Export tests for courses. """ def setUp(self): # pylint: disable=arguments-differ super(TestCourseExport, self).setUp() self.export_page = ExportCoursePage( self.browser, self.course_info['org'], self.course_info['number'], self.course_info['run'], ) self.export_page.visit() def test_header(self): """ Scenario: I should see the correct text when exporting a course. Given that I have a course to export from When I visit the export page The correct header should be shown """ self.assertEqual(self.export_page.header_text, 'Course Export') @attr(shard=7) class TestLibraryExport(ExportTestMixin, StudioLibraryTest): """ Export tests for libraries. """ def setUp(self): """ Ensure a library exists and navigate to the library edit page. """ super(TestLibraryExport, self).setUp() self.export_page = ExportLibraryPage(self.browser, self.library_key) self.export_page.visit() def test_header(self): """ Scenario: I should see the correct text when exporting a library. Given that I have a library to export from When I visit the export page The correct header should be shown """ self.assertEqual(self.export_page.header_text, 'Library Export') @attr(shard=7) class ImportTestMixin(object): """ Tests to run for both course and library import pages. """ def setUp(self): super(ImportTestMixin, self).setUp() self.import_page = self.import_page_class(*self.page_args()) self.landing_page = self.landing_page_class(*self.page_args()) self.import_page.visit() @abstractmethod def page_args(self): """ Generates the args for initializing a page object. """ return [] def test_upload(self): """ Scenario: I want to upload a course or library for import. Given that I have a library or course to import into And I have a valid .tar.gz file containing data to replace it with I can select the file and upload it And the page will give me confirmation that it uploaded successfully """ self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_upload() def test_import_timestamp(self): """ Scenario: I perform a course / library import On import success, the page displays a UTC timestamp previously not visible And if I refresh the page, the timestamp is still displayed """ self.assertFalse(self.import_page.is_timestamp_visible()) # Get the time when the import has started. # import_page timestamp is in (MM/DD/YYYY at HH:mm) so replacing (second, microsecond) to # keep the comparison consistent upload_start_time = datetime.utcnow().replace(microsecond=0, second=0) self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_upload() # Get the time when the import has finished. # import_page timestamp is in (MM/DD/YYYY at HH:mm) so replacing (second, microsecond) to # keep the comparison consistent upload_finish_time = datetime.utcnow().replace(microsecond=0, second=0) import_timestamp = self.import_page.parsed_timestamp self.import_page.wait_for_timestamp_visible() # Verify that 'import_timestamp' is between start and finish upload time self.assertLessEqual( upload_start_time, import_timestamp, "Course import timestamp should be upload_start_time <= import_timestamp <= upload_end_time" ) self.assertGreaterEqual( upload_finish_time, import_timestamp, "Course import timestamp should be upload_start_time <= import_timestamp <= upload_end_time" ) self.import_page.visit() self.import_page.wait_for_tasks(completed=True) self.import_page.wait_for_timestamp_visible() def test_landing_url(self): """ Scenario: When uploading a library or course, a link appears for me to view the changes. Given that I upload a library or course A button will appear that contains the URL to the library or course's main page """ self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.assertEqual(self.import_page.finished_target_url(), self.landing_page.url) def test_bad_filename_error(self): """ Scenario: I should be reprimanded for trying to upload something that isn't a .tar.gz file. Given that I select a file that is an .mp4 for upload An error message will appear """ self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball('funny_cat_video.mp4') self.import_page.wait_for_filename_error() def test_task_list(self): """ Scenario: I should see feedback checkpoints when uploading a course or library Given that I am on an import page No task checkpoint list should be showing When I upload a valid tarball Each task in the checklist should be marked confirmed And the task list should be visible """ # The task list shouldn't be visible to start. self.assertFalse(self.import_page.is_task_list_showing(), "Task list shown too early.") self.import_page.wait_for_tasks() self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_tasks(completed=True) self.assertTrue(self.import_page.is_task_list_showing(), "Task list did not display.") def test_bad_import(self): """ Scenario: I should see a failed checklist when uploading an invalid course or library Given that I am on an import page And I upload a tarball with a broken XML file The tasks should be confirmed up until the 'Updating' task And the 'Updating' task should be marked failed And the remaining tasks should not be marked as started """ self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.bad_tarball_name) self.import_page.wait_for_tasks(fail_on='Updating') @attr(shard=7) class TestEntranceExamCourseImport(ImportTestMixin, StudioCourseTest): """ Tests the Course import page """ tarball_name = 'entrance_exam_course.2015.tar.gz' bad_tarball_name = 'bad_course.tar.gz' import_page_class = ImportCoursePage landing_page_class = CourseOutlinePage def page_args(self): return [self.browser, self.course_info['org'], self.course_info['number'], self.course_info['run']] def test_course_updated_with_entrance_exam(self): """ Given that I visit an empty course before import I should not see a section named 'Section' or 'Entrance Exam' When I visit the import page And I upload a course that has an entrance exam section named 'Entrance Exam' And I visit the course outline page again The section named 'Entrance Exam' should now be available. And when I switch the view mode to student view and Visit CourseWare Then I see one section in the sidebar that is 'Entrance Exam' """ self.landing_page.visit() # Should not exist yet. self.assertRaises(IndexError, self.landing_page.section, "Section") self.assertRaises(IndexError, self.landing_page.section, "Entrance Exam") self.import_page.visit() self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_upload() self.landing_page.visit() # There should be two sections. 'Entrance Exam' and 'Section' on the landing page. self.landing_page.section("Entrance Exam") self.landing_page.section("Section") self.landing_page.view_live() courseware = CoursewarePage(self.browser, self.course_id) courseware.wait_for_page() StaffCoursewarePage(self.browser, self.course_id).set_staff_view_mode('Learner') self.assertEqual(courseware.num_sections, 1) self.assertIn( "To access course materials, you must score", courseware.entrance_exam_message_selector.text[0] ) @attr(shard=7) class TestCourseImport(ImportTestMixin, StudioCourseTest): """ Tests the Course import page """ tarball_name = '2015.lzdwNM.tar.gz' bad_tarball_name = 'bad_course.tar.gz' import_page_class = ImportCoursePage landing_page_class = CourseOutlinePage def page_args(self): return [self.browser, self.course_info['org'], self.course_info['number'], self.course_info['run']] def test_course_updated(self): """ Given that I visit an empty course before import I should not see a section named 'Section' When I visit the import page And I upload a course that has a section named 'Section' And I visit the course outline page again The section named 'Section' should now be available """ self.landing_page.visit() # Should not exist yet. self.assertRaises(IndexError, self.landing_page.section, "Section") self.import_page.visit() self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_upload() self.landing_page.visit() # There's a section named 'Section' in the tarball. self.landing_page.section("Section") def test_header(self): """ Scenario: I should see the correct text when importing a course. Given that I have a course to import to When I visit the import page The correct header should be shown """ self.assertEqual(self.import_page.header_text, 'Course Import') def test_multiple_course_import_message(self): """ Given that I visit an empty course before import When I visit the import page And I upload a course with file name 2015.lzdwNM.tar.gz Then timestamp is visible after course is updated successfully And then I create a new course When I visit the import page of this new course Then timestamp is not visible """ self.import_page.visit() self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_upload() self.assertTrue(self.import_page.is_timestamp_visible()) # Create a new course and visit the import page self.course_info = { 'org': 'orgX', 'number': self.unique_id + '_2', 'run': 'test_run_2', 'display_name': 'Test Course 2' + self.unique_id } self.install_course_fixture() self.import_page = self.import_page_class(*self.page_args()) self.import_page.visit() # As this is new course which is never import so timestamp should not present self.assertFalse(self.import_page.is_timestamp_visible()) @attr(shard=7) class TestLibraryImport(ImportTestMixin, StudioLibraryTest): """ Tests the Library import page """ tarball_name = 'library.HhJfPD.tar.gz' bad_tarball_name = 'bad_library.tar.gz' import_page_class = ImportLibraryPage landing_page_class = LibraryEditPage def page_args(self): return [self.browser, self.library_key] def test_library_updated(self): """ Given that I visit an empty library No XBlocks should be shown When I visit the import page And I upload a library that contains three XBlocks And I visit the library page Three XBlocks should be shown """ self.landing_page.visit() self.landing_page.wait_until_ready() # No items should be in the library to start. self.assertEqual(len(self.landing_page.xblocks), 0) self.import_page.visit() self.import_page.wait_for_choose_file_click_handler() self.import_page.upload_tarball(self.tarball_name) self.import_page.wait_for_upload() self.landing_page.visit() self.landing_page.wait_until_ready() # There are three blocks in the tarball. self.assertEqual(len(self.landing_page.xblocks), 3) def test_header(self): """ Scenario: I should see the correct text when importing a library. Given that I have a library to import to When I visit the import page The correct header should be shown """ self.assertEqual(self.import_page.header_text, 'Library Import')
romain-li/edx-platform
common/test/acceptance/tests/studio/test_import_export.py
Python
agpl-3.0
17,465
[ "VisIt" ]
8ad9dd28b9f367419cca474ea579e321bfaeb5b28aef8b624bd8cf9435d8b9f1
#! /usr/bin/env python # -*- coding: utf-8 -*- #rvo.py # Copyright 2015 Jonathan M. Skelton and Adam J. Jackson #COMMENT: EoS data should be a CSV file with each row containing (V, E, p), and no header rows. #COMMENT: We use VASP, so we assume V is in A^3, E is in eV, and p is in kbar. #COMMENT: An example :- # For reference, with the PBEsol EoS ("PbS-EoS-PBEsol.csv"), v0 = 50.86 A^3. # With HSE 06, the pressure at this volume is 26.24 kbar (2.62 GPa). # One iteration of RVO gives a Delta V of 2.28 A^3, and hence a predicted HSE 06 equilibrium volume of 53.14 A^3. # The correct value (from a HSE 06 EoS fitting) is 52.97 A^3, and the pressure at the corrected volume is -2.03 kbar (-0.2 GPa). import csv import math import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter from scipy.optimize import curve_fit from collections import namedtuple import interpolate_cell EVPerCubicAngstromInGPa = 160.217656 mpl.rc('font', **{ 'family' : 'sans-serif', 'size' : 10, 'sans-serif' : 'Arial' }) mpl.rc('lines', **{ 'linewidth' : 0.5 }) _FontSize = 10 _Label1DpFormatter = FuncFormatter(lambda x, pos : "{0:.1f}".format(x)) def murnaghan_fit(eData, vData, initialK0Guess = 50.0, initialK0PrimeGuess = 5.0): def _fit_equation(x, e0, v0, k0, kPrime0): return e0 + k0 * v0 * ((((x / v0) ** (1.0 - kPrime0)) / (kPrime0 * (kPrime0 - 1))) + (x / (kPrime0 * v0)) - (1 / (kPrime0 - 1))) minIndex = np.argmin(eData) e0Init = eData[minIndex] v0Init = vData[minIndex] (e0, v0, k0, kPrime0), pcov = curve_fit(_fit_equation, vData, eData, [e0Init, v0Init, initialK0Guess, initialK0PrimeGuess]) eRMS = math.sqrt(np.mean((eData - _fit_equation(vData, e0, v0, k0, kPrime0)) ** 2)) MurnaghanFit = namedtuple('MurnaghanFit', 'e0 v0 k0 kPrime0 eRMS') return MurnaghanFit(e0, v0, k0, kPrime0, eRMS) def murnaghan_pressure(v, fit): """Calculate the pressure given a volume and fitted parameters for a Murnaghan EOS Arguments: v: unit cell volume in cubic angstroms (AA^3) fit: namedtuple containing fit parameters in units of eV and AA^3 format: namedtuple('MurnaghanFit', 'e0 v0 k0 kPrime0 eRMS') Returns: p: pressure in kbar (10^8 Pa) p(v) = (k0/k'0) * [(v0/v) ^ k'0 -1 ] """ p = (fit.k0/fit.kPrime0) * ((fit.v0 / v) ** fit.kPrime0 - 1) p = p * EVPerCubicAngstromInGPa * 10 # Convert to kbar / A3 return p def apply_rvo_murnaghan(pressure, murnaghan_params): """ Estimate volume change to minimise absolute pressure, given reference fit to Murnaghan EoS Arguments: pressure: External pressure in units of kPa (float) murnaghan_params: namedtuple containing fit parameters in units of eV and AA^3 format: namedtuple('MurnaghanFit', 'e0 v0 k0 kPrime0 eRMS') Returns: Volume change in AA^3 From Murnaghan EOS, dP/dv = (-k0/v) * (/v0)**(-kprime0) Tangent at P=0 therefore has slope m = DP/Dv = (-k0/v0) v0-v ~= (0-P)/m """ m = -murnaghan_params.k0 / murnaghan_params.v0 m = m *EVPerCubicAngstromInGPa * 10 # Convert to kbar / A3 return -pressure/m def _SaveVPFitPlot(pValues, vValues, murnaghan_params, fileName): plt.figure(figsize = (8.6 / 2.54, 6 / 2.54)) plt.plot(pValues / 10.0, vValues, color = 'k', marker = '^', markersize = 5, label = "EoS", fillstyle = 'none') xMin, xMax = plt.xlim() fitOverlayValues = np.linspace(xMin * 10.0, xMax * 10.0, 100) e0, v0, k0, kPrime0, eRMS = murnaghan_params murnaghan_pValues = (k0/kPrime0)*((vValues/v0)**(-kPrime0) -1) * EVPerCubicAngstromInGPa plt.plot(murnaghan_pValues, vValues, color = 'k', marker = 'x', markersize = 3, linestyle = 'none', label = "Murnaghan fit") plt.xlabel(r"$p$ / GPa", fontweight = 'bold') plt.ylabel(r"$V$ / $\AA^{3}$", fontweight = 'bold') plt.legend(loc = 'upper right', frameon = False, prop = { 'size' : _FontSize }) axes = plt.gca() for spine in axes.spines.values(): spine.set_linewidth(0.5) plt.tight_layout() plt.savefig(fileName, format = 'png', dpi = 300) plt.close() def import_VEP(EoSData): vValues, eValues, pValues = [], [], [] with open(EoSData, 'r') as inputReader: inputReaderCSV = csv.reader(inputReader) for row in inputReaderCSV: if row[0][0] != "#": vValue, eValue, pValue = row vValues.append(float(vValue)) eValues.append(float(eValue)) pValues.append(float(pValue)) vValues, eValues, pValues = np.array(vValues), np.array(eValues), np.array(pValues) return (vValues, eValues, pValues) def import_VE(EoSData): vValues, eValues = [], [] with open(EoSData, 'r') as inputReader: inputReaderCSV = csv.reader(inputReader) for row in inputReaderCSV: if row[0][0] != "#": vValue, eValue = row vValues.append(float(vValue)) eValues.append(float(eValue)) vValues, eValues = np.array(vValues), np.array(eValues) return (vValues, eValues) def import_lattice(EoSData): """" Import data from 10-column CSV file in format: Energy, ax,ay,az,bx,by,bz,cx,cy,cz arguments: EoSData: CSV file path as string returns: vValues: list of volumes in cubic angstroms eValues: list of energies in eV lattice_vectors: list of lattice vectors as 3x3 numpy arrays """ # Double precision is used here for the all-electron energy TODO # Is the program losing precision in places due to use of floats? # Floats only have ~ 7.d.p of precision, fine for normalised # energies but not for total energies. Perhaps a warning is needed # for large energies? vValues, eValues, lattice_vectors = [], [], [] with open(EoSData, 'r') as inputReader: inputReaderCSV = csv.reader(inputReader) for row in inputReaderCSV: if row[0][0] != "#": eValue = np.double(row[0]) eValues.append(eValue) lattice = np.array(row[1:10]).reshape([3,3]).astype('float') lattice_vectors.append(lattice) vValue = interpolate_cell.cell_volume(lattice) vValues.append(vValue) return(vValues, eValues, lattice_vectors) def estimate_vectors(lattice_vectors, target_volume, vValues, verbose=False): if verbose: def vprint(*args): for arg in args: print(arg) else: def vprint(*args): pass vprint(" -> Proposed volume of improved cell:" + "{0:.3f} A^3 ".format(target_volume)) vprint(" -> Estimating new lattice vectors:") # We wrap the sorted volumes with their original indices # e.g. [(v1,1),(v3,3),(v2,2)] sorted_volumes = zip(vValues,range(len(vValues))) sorted_volumes.sort() for i in range(len(sorted_volumes)): if (sorted_volumes[i][0] <= target_volume and sorted_volumes[i+1][0] > target_volume): cell1 = lattice_vectors[sorted_volumes[i][1]] cell2 = lattice_vectors[sorted_volumes[i+1][1]] break else: # The target must lie outside the reference range print(" (Extrapolating beyond existing volume range.)\n") if target_volume < sorted_volumes[0][0]: cell1 = lattice_vectors[sorted_volumes[0][1]] cell2 = lattice_vectors[sorted_volumes[1][1]] elif target_volume >= sorted_volumes[-1][1]: cell1 = lattice_vectors[sorted_volumes[-2][1]] cell2 = lattice_vectors[sorted_volumes[-1][1]] else: raise Exception("Trouble finding suitable reference cells") vprint(" Lattice vectors used for interpolation:") vprint(" v = {0:5f} A^3\n".format( interpolate_cell.cell_volume(cell1))) vprint(pretty_vectors(cell1, padding=8)) vprint(" v = {0:5f} A^3\n".format( interpolate_cell.cell_volume(cell2))) vprint(pretty_vectors(cell2, padding=8)) # Solve interpolation factor Lambda = interpolate_cell.solve_v(cell1,cell2,target_volume) vprint(" Interpolation factor Lambda = {0:4f}".format(Lambda)) new_cell = interpolate_cell.interpolate_cell(cell1,cell2,Lambda) vprint(" Suggested lattice vectors for next iteration:\n") vprint(pretty_vectors(new_cell, padding=8)) return new_cell def pretty_vectors(cell,padding=0): """POSCAR-friendly formatting for lattice vector matrices""" pretty_string="" for row in range(3): pretty_string += "{0}{1:4f} {2:4f} {3:4f}\n".format( " "*padding, cell[row,0], cell[row,1], cell[row,2]) return pretty_string def main(filename, pressure, current_volume): EoSData = filename print("Reading EoS from \"{0}\"...".format(EoSData)) # Check input file format: note that row[0][0] is used to check # for comment character as CSV reader always returns a list. with open(EoSData,'r') as f: inputReaderCSV = csv.reader(f) for row in inputReaderCSV: if row[0][0] != '#': data_file_width = len(row) break if data_file_width == 3: print("Importing data from Volume-Energy-Pressure table") vValues, eValues, pValues = import_VEP(EoSData) lattice_vectors = False headerLine = "{0: >8} {1: >7} {2: >6}".format( "V / A^3", "E / eV", "p / GPa") print(headerLine) print("-" * len(headerLine)) for v, e, p in zip(vValues, eValues, pValues): print("{0: >8.2f} {1: >7.2f} {2: >6.2f}".format( v, e, p)) print('') elif data_file_width == 2: print("Importing data from Volume-Energy table") vValues, eValues = import_VE(EoSData) pValues, lattice_vectors = False, False headerLine = "{0: >8} {1: >7}".format("V / A^3", "E / eV") print(headerLine) print("-" * len(headerLine)) for v, e in zip(vValues, eValues): print("{0: >8.2f} {1: >7.2f}".format(v, e)) print('') elif data_file_width == 10: print("Importing data from Energy-lattice vectors table" + " and calculating volumes") vValues, eValues, lattice_vectors = import_lattice(EoSData) pValues = False headerLine = "{0: >8} {1: >7}".format("V / A^3", "E / eV") print(headerLine) print("-" * len(headerLine)) for v, e in zip(vValues, eValues): print("{0: >8.2f} {1: >7.2f}".format(v, e)) print('') else: print("Data file type not recognised") return False print('') print("Performing EoS fit...") murnaghan_params = murnaghan_fit(eValues, vValues) print(" -> V0 = {0:.2f} A^3".format(murnaghan_params.v0)) print(" -> E0 = {0:.2f} eV".format(murnaghan_params.e0)) print(" -> K0 = {0:.2f} GPa".format(murnaghan_params.k0 * EVPerCubicAngstromInGPa)) print(" -> K'0 = {0:.2f}".format(murnaghan_params.kPrime0)) print(" -> RMS = {0:.2e}".format(murnaghan_params.eRMS)) print('') print("Performing dVxc...") rvo_murnaghan = apply_rvo_murnaghan(pressure, murnaghan_params) print(" -> Your volume offset by Murnaghan fitting is:") print(" ---> ** Delta V = {0:.2f} A^3 ** <---".format(rvo_murnaghan)) print('') if current_volume and not lattice_vectors: print(" -> Proposed volume of improved cell:" + "{0:.3f} A^3 ".format(current_volume + rvo_murnaghan)) elif lattice_vectors and not current_volume: print("You have provided lattice vectors as part of the \n" "reference data. If you provide the volume of the \n" "test calculation with the -v argument, this program \n" "can estimate new lattice vectors by interpolating to\n" "the target volume. \n") elif lattice_vectors and current_volume: target_volume = current_volume + rvo_murnaghan estimate_vectors(lattice_vectors, target_volume, vValues, verbose=True) if pValues != False: print("Saving a plot of the RVO EoS fit to \"Fit.png\"...") _SaveVPFitPlot(pValues, vValues, murnaghan_params, "Fit.png") print('') print("Thank you for using RVO!") print('') print('You can find a draft of the accompanying paper at http://arxiv.org/abs/1507.08815') print("(Note that the name of the procedure has been changed from ΔVxc following reviewer feedback.)") print('') if __name__ == "__main__": try: import readline readline.parse_and_bind("tab: complete") except: pass import argparse parser = argparse.ArgumentParser(description="RVO; affordable volume corrections for high-level DFT calculations") parser.add_argument('-f', '--file', action="store", type=str, dest="filename", default=False, help=("csv file containing E-V curve with functional A"+ " in units of eV and cubic angstroms")) parser.add_argument('-p', '--pressure', action="store", type=float, dest="pressure", default=False, help="Pressure at current volume for functional B in GPa") parser.add_argument('-v', '--volume', action="store", type=float, dest="current_volume", default=False, help="Value of current volume; used to estimate new lattice vectors when suitable input file is provided.") args = parser.parse_args() if args.filename: filename = args.filename else: filename = raw_input("Please give path/filename of CSV file containing E-V curve: ") if args.pressure: pressure = args.pressure else: pressure = float(raw_input("Please input pressure at current volume in GPa: ")) main(filename,pressure,args.current_volume)
WMD-Bath/dvxc
rvo.py
Python
gpl-3.0
14,340
[ "VASP" ]
2a67e4b10bcf1ae50c25ba477281eada8c2da9bde26e011267b4f5e1162cce55
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from six.moves import zip, range, map # NOQA import numpy as np import utool as ut import ubelt as ub import cv2 from vtool_ibeis import coverage_kpts # TODO: integrate more COVGRID_DEFAULT = ut.ParamInfoList('coverage_grid', [ ut.ParamInfo('pxl_per_bin', 10, 'ppb', varyvals=[20, 5, 1]), ut.ParamInfo('grid_steps', 3, 'stps', varyvals=[1, 3, 7]), ut.ParamInfo('grid_sigma', 1.6, 'sigma', varyvals=[1.0, 1.6]), ]) def make_grid_coverage_mask(kpts, chipsize, weights, pxl_per_bin=4, grid_steps=1, resize=False, out=None, grid_sigma=1.6): r""" Args: kpts (ndarray[float32_t, ndim=2]): keypoint chipsize (tuple): width, height weights (ndarray[float32_t, ndim=1]): pxl_per_bin (float): grid_steps (int): Returns: ndarray: weightgrid CommandLine: python -m vtool_ibeis.coverage_grid --test-make_grid_coverage_mask --show Example: >>> # DISABLE_DOCTEST >>> from vtool_ibeis.coverage_grid import * # NOQA >>> import vtool_ibeis as vt >>> # build test data >>> kpts, chipsize, weights = coverage_kpts.testdata_coverage('easy1.png') >>> pxl_per_bin = 4 >>> grid_steps = 2 >>> # execute function >>> weightgrid = make_grid_coverage_mask(kpts, chipsize, weights, pxl_per_bin, grid_steps) >>> # verify result >>> result = str(weightgrid) >>> print(result) >>> # xdoctest: +REQUIRES(--show) >>> import plottool_ibeis as pt >>> pt.imshow(weightgrid) >>> ut.show_if_requested() """ import vtool_ibeis as vt coverage_gridtup = sparse_grid_coverage( kpts, chipsize, weights, pxl_per_bin=pxl_per_bin, grid_steps=grid_steps, grid_sigma=grid_sigma ) gridshape = coverage_gridtup[0:2] neighbor_bin_weights, neighbor_bin_indices = coverage_gridtup[-2:] oldshape_indices = neighbor_bin_indices.shape newshape_indices = (np.prod(oldshape_indices[0:2]), oldshape_indices[2]) neighbor_bin_indices = neighbor_bin_indices.reshape(newshape_indices).T neighbor_bin_weights = neighbor_bin_weights.flatten() # Get flat indexing into gridbin neighbor_bin_flat_indices = np.ravel_multi_index(neighbor_bin_indices, gridshape) # Group by bins with weight unique_flatxs, grouped_flatxs = vt.group_indices(neighbor_bin_flat_indices) grouped_weights = vt.apply_grouping(neighbor_bin_weights, grouped_flatxs) # FIXME: boundary cases are not handled right because their vote is split # into the same bin and is fighting with itself durring the max max_weights = list(map(np.max, grouped_weights)) if out is None: weightgrid = np.zeros(gridshape) else: # outvar specified weightgrid = out weightgrid[:] = 0 unique_rows, unique_cols = np.unravel_index(unique_flatxs, gridshape) weightgrid[unique_rows, unique_cols] = max_weights #flat_weightgrid = np.zeros(np.prod(gridshape)) #flat_weightgrid[unique_flatxs] = max_weight #ut.embed() #weightgrid = np.reshape(flat_weightgrid, gridshape) if resize: weightgrid = cv2.resize(weightgrid, chipsize, interpolation=cv2.INTER_NEAREST) return weightgrid def get_subbin_xy_neighbors(subbin_index00, grid_steps, num_cols, num_rows): """ Generate all neighbor of a bin subbin_index00 = left and up subbin index """ subbin_index00 = np.floor(subbin_index00).astype(np.int32) subbin_x0, subbin_y0 = subbin_index00 step_list = np.arange(1 - grid_steps, grid_steps + 1) offset_list = [ # broadcast to the shape we will add too np.array([xoff, yoff])[:, None] for xoff, yoff in list(ut.iprod(step_list, step_list))] neighbor_subbin_index_list = [ np.add(subbin_index00, offset) for offset in offset_list ] # Concatenate all subbin indexes into one array for faster vectorized op neighbor_bin_indices = np.dstack(neighbor_subbin_index_list).T # Clip with no wrapparound min_val = np.array([0, 0]) max_val = np.array([num_cols - 1, num_rows - 1]) np.clip(neighbor_bin_indices, min_val[None, None, :], max_val[None, None, :], out=neighbor_bin_indices) return neighbor_bin_indices def compute_subbin_to_bins_dist(neighbor_bin_centers, subbin_xy_arr): _tmp = np.subtract(neighbor_bin_centers, subbin_xy_arr.T[None, :]) neighbor_subbin_sqrddist_arr = np.power(_tmp, 2, out=_tmp).sum(axis=2) return neighbor_subbin_sqrddist_arr def weighted_gaussian_falloff(neighbor_subbin_sqrddist_arr, weights, grid_sigma): import vtool_ibeis as vt _gaussweights = vt.gauss_func1d_unnormalized(neighbor_subbin_sqrddist_arr, grid_sigma) # If uncommented next line ensure each column sums to 1 #np.divide(_gaussweights, _gaussweights.sum(axis=0)[None, :], out=_gaussweights) # Scale initial weights by the gaussian falloff neighbor_bin_weights = np.multiply(_gaussweights, weights[None, :]) return neighbor_bin_weights def sparse_grid_coverage(kpts, chipsize, weights, pxl_per_bin=.3, grid_steps=1, grid_sigma=1.6): r""" Args: kpts (ndarray[float32_t, ndim=2]): keypoint chipsize (tuple): weights (ndarray): CommandLine: python -m vtool_ibeis.coverage_grid --test-sparse_grid_coverage --show Example: >>> # DISABLE_DOCTEST >>> from vtool_ibeis.coverage_grid import * # NOQA >>> kpts, chipsize, weights = coverage_kpts.testdata_coverage() >>> chipsize = (chipsize[0] + 50, chipsize[1]) >>> pxl_per_bin = 3 >>> grid_steps = 2 >>> grid_sigma = 1.6 >>> coverage_gridtup = sparse_grid_coverage(kpts, chipsize, weights, pxl_per_bin, grid_steps, grid_sigma) >>> # xdoctest: +REQUIRES(--show) >>> import plottool_ibeis as pt >>> show_coverage_grid(*coverage_gridtup) >>> pt.show_if_requested() """ import vtool_ibeis as vt # Compute grid size and stride chip_w, chip_h = chipsize # find enough rows to fit pxl_per_bin pixels into a grid dimension num_rows = max(vt.iround(chip_h / pxl_per_bin), 1) num_cols = max(vt.iround(chip_w / pxl_per_bin), 1) # stride is roughly equal in each direction, depending on rounding errors chipstride = np.array((chip_w / num_cols, chip_h / num_rows)) # Find keypoint subbin locations relative to edge xy_arr = vt.get_xys(kpts) subbin_xy_arr = np.divide(xy_arr, chipstride[:, None]) # Find subbin locations relative to center frac_subbin_index = np.subtract(subbin_xy_arr, .5) neighbor_bin_xy_indices = get_subbin_xy_neighbors(frac_subbin_index, grid_steps, num_cols, num_rows) # Find center neighbor_bin_centers = np.add(neighbor_bin_xy_indices, .5) # compute distance to neighbor neighbor_subbin_sqrddist_arr = compute_subbin_to_bins_dist(neighbor_bin_centers, subbin_xy_arr) # scale weights using guassia falloff neighbor_bin_weights = weighted_gaussian_falloff(neighbor_subbin_sqrddist_arr, weights, grid_sigma) # convert to rowcol neighbor_bin_indices = neighbor_bin_rc_indices = neighbor_bin_xy_indices[:, :, ::-1] # NOQA coverage_gridtup = ( num_rows, num_cols, subbin_xy_arr, neighbor_bin_centers, neighbor_bin_weights, neighbor_bin_indices) return coverage_gridtup # VISUALIZATION FUNCS def show_coverage_grid(num_rows, num_cols, subbin_xy_arr, neighbor_bin_centers, neighbor_bin_weights, neighbor_bin_indices, fnum=None, pnum=None): """ visualizes the voting scheme on the grid. (not a mask, and no max) """ import plottool_ibeis as pt import vtool_ibeis as vt import matplotlib as mpl if fnum is None: fnum = pt.next_fnum() fig = pt.figure(fnum, pnum=pnum) ax = fig.gca() x_edge_indices = np.arange(num_cols) y_edge_indices = np.arange(num_rows) x_center_indices = vt.hist_edges_to_centers(x_edge_indices) y_center_indices = vt.hist_edges_to_centers(y_edge_indices) x_center_grid, y_center_grid = np.meshgrid(x_center_indices, y_center_indices) ax.set_xticks(x_edge_indices) ax.set_yticks(y_edge_indices) # Plot keypoint loc ax.scatter(subbin_xy_arr[0], subbin_xy_arr[1], marker='o') # Plot Weighted Lines to Subbin pt_colors = pt.distinct_colors(len(subbin_xy_arr.T)) segment_list = [] color_list = [] for subbin_centers, subbin_weights in zip(neighbor_bin_centers, neighbor_bin_weights): for pt_xys, center_xys, weight, color in zip(subbin_xy_arr.T, subbin_centers, subbin_weights, pt_colors): # Adjsut weight to alpha for easier visualization alpha = weight INCRESE_ALPHA_VISIBILITY = True if INCRESE_ALPHA_VISIBILITY: min_viz_alpha = .05 alpha = alpha * (1.0 - min_viz_alpha) + min_viz_alpha alpha **= 1.0 #pt.plots.colorline( segment = np.vstack((pt_xys, center_xys)) segment_list.append(segment) # Alpha becomes part of the colors color_list.append(list(color) + [alpha]) # DO NOT USE PLOT VERY SLOW #ax.plot(*segment.T, color=color, alpha=alpha, lw=3) ax = pt.gca() # Plot all segments in single line collection for speed # solid | dashed | dashdot | dotted lc = mpl.collections.LineCollection(segment_list, colors=color_list, linewidth=3, linestyles='solid') ax.add_collection(lc) # Plot Grid Center num_cells = num_cols * num_rows grid_alpha = min(.4, max(1 - (num_cells / 500), .1)) grid_color = [.6, .6, .6, grid_alpha] #print(grid_color) # Plot grid cetner ax.scatter(x_center_grid, y_center_grid, marker='.', color=grid_color, s=grid_alpha) ax.set_xlim(0, num_cols - 1) ax.set_ylim(0, num_rows - 1) #----- pt.dark_background() ax.grid(True, color=[.3, .3, .3]) ax.set_xticklabels([]) ax.set_yticklabels([]) # TESTING FUNCS def get_coverage_grid_gridsearch_configs(): #varied_dict = { # 'pxl_per_bin': [.05, .3, 1.0], # 'grid_steps': [1, 3, 7], # 'grid_sigma': [1.0, 1.6], #} #slice_dict = { # 'pxl_per_bin' : slice(0, 3), # 'grid_steps' : slice(0, 3), # 'grid_sigma' : slice(0, 3), #} cfgdict_list, cfglbl_list = COVGRID_DEFAULT.get_gridsearch_input() # Make configuration for every parameter setting #cfgdict_list, cfglbl_list = ut.make_constrained_cfg_and_lbl_list(varied_dict, slice_dict=slice_dict) return cfgdict_list, cfglbl_list def gridsearch_coverage_grid(): """ CommandLine: python -m vtool_ibeis.coverage_grid --test-gridsearch_coverage_grid --show Example: >>> # DISABLE_DOCTEST >>> from vtool_ibeis.coverage_grid import * # NOQA >>> import plottool_ibeis as pt >>> gridsearch_coverage_grid() >>> pt.show_if_requested() """ import plottool_ibeis as pt fname = None # 'easy1.png' kpts, chipsize, weights = coverage_kpts.testdata_coverage(fname) if len(kpts) > 100: kpts = kpts[::100] weights = weights[::100] cfgdict_list, cfglbl_list = get_coverage_grid_gridsearch_configs() coverage_gridtup_list = [ sparse_grid_coverage(kpts, chipsize, weights, **cfgdict) for cfgdict in ub.ProgIter(cfgdict_list, desc='coverage grid') ] fnum = 1 with ub.Timer('plotting gridsearch'): ut.interact_gridsearch_result_images( show_coverage_grid, cfgdict_list, cfglbl_list, coverage_gridtup_list, fnum=fnum, figtitle='coverage grid', unpack=True, max_plots=25) pt.iup() def gridsearch_coverage_grid_mask(): """ CommandLine: python -m vtool_ibeis.coverage_grid --test-gridsearch_coverage_grid_mask --show Example: >>> # DISABLE_DOCTEST >>> from vtool_ibeis.coverage_grid import * # NOQA >>> import plottool_ibeis as pt >>> gridsearch_coverage_grid_mask() >>> pt.show_if_requested() """ import plottool_ibeis as pt cfgdict_list, cfglbl_list = get_coverage_grid_gridsearch_configs() kpts, chipsize, weights = coverage_kpts.testdata_coverage('easy1.png') gridmask_list = [ 255 * make_grid_coverage_mask(kpts, chipsize, weights, **cfgdict) for cfgdict in ub.ProgIter(cfgdict_list, desc='coverage grid') ] NORMHACK = False if NORMHACK: gridmask_list = [ 255 * (gridmask / gridmask.max()) for gridmask in gridmask_list ] fnum = 1 ut.interact_gridsearch_result_images( pt.imshow, cfgdict_list, cfglbl_list, gridmask_list, fnum=fnum, figtitle='coverage grid', unpack=False, max_plots=25) pt.iup() #pt.show_if_requested() if __name__ == '__main__': """ CommandLine: xdoctest -m vtool_ibeis.coverage_grid """ import xdoctest xdoctest.doctest_module(__file__)
Erotemic/vtool
vtool_ibeis/coverage_grid.py
Python
apache-2.0
13,416
[ "Gaussian" ]
f6bd576ee290273bacf71fee3e7953aa31e0b3f7e26469ecf02e6e207034a844
from logging import getLogger logger = getLogger(__name__) class DominatorTree(object): def __init__(self): self.nodes = [] self.edges = [] def add_node(self, n): if n not in self.nodes: self.nodes.append(n) def add_edge(self, n1, n2): edge = (n1, n2) if edge not in self.edges: self.edges.append(edge) def get_parent_of(self, n): '''parent is immidiate dominator''' for n1, n2 in self.edges: if n2 is n: return n1 return None def get_children_of(self, n): return [n2 for n1, n2 in self.edges if n1 is n] #is v dominator of n? def is_dominator(self, n, v): if n is v: return True for c in self.get_children_of(n): if self.is_dominator(c, v): return True return False def is_child(self, n1, n2): for _n1, _n2 in self.edges: if _n1 is n1 and _n2 is n2: return True return False def dump(self): logger.debug('dominator tree') logger.debug(str(self)) def __str__(self): s = '' for n1, n2 in sorted(self.edges, key=lambda n: n[0].name): s += '{} --> {}\n'.format(n1.name, n2.name) return s class DominatorTreeBuilder(object): def __init__(self, scope): self.scope = scope self.done_block_links = [] self.dominators = {} def process(self): first_block = self.scope.entry_block self._fwd_blks = self._succs self._fwd_loop_blks = self._succs_loop self._back_blks = self._preds self._back_loop_blks = self._preds_loop self.all_blocks = [blk for blk in self.scope.traverse_blocks()] #collect dominators for each block self._walk_block(first_block, self._visit_Block_find_dominator) #build dominator tree tree = DominatorTree() for b, doms in self.dominators.items(): for dom in doms: assert dom.order >= 0 domlist = sorted(list(doms)) assert b is domlist[-1] if len(domlist) >= 2: d1 = domlist[-2] # immediate dominator d2 = domlist[-1] # block itself tree.add_node(d1) tree.add_node(d2) tree.add_edge(d1, d2) return tree def _succs(self, blk): succs = [] for s in blk.succs: succs.append(s) return succs def _succs_loop(self, blk): return blk.succs_loop def _preds(self, blk): preds = [] for s in blk.preds: preds.append(s) return preds def _preds_loop(self, blk): return blk.preds_loop def _walk_block(self, block, visit_func): self.done_block_links = [] self._walk_block_rec(block, visit_func) def _walk_block_rec(self, block, visit_func): visit_func(block) #walk into successors succs = self._fwd_blks(block) for succ in succs: if succ in self._fwd_loop_blks(block): continue #don't visit to already visited block link = (block, succ) if link in self.done_block_links: continue self.done_block_links.append(link) self._walk_block_rec(succ, visit_func) def _visit_Block_find_dominator(self, block): if block in self.dominators: return self.dominators[block] preds = self._back_blks(block) if preds: doms = set(self.all_blocks) for p in preds: if p in self._back_loop_blks(block): continue ds = self._visit_Block_find_dominator(p) doms = ds.intersection(doms) doms.add(block) else: #It must be the super-src block doms = set([block]) self.dominators[block] = doms return doms class DominanceFrontierBuilder(object): def __init__(self): self.dominance_frontier = {} def process(self, block, tree): self._compute_df(block, tree) return self.dominance_frontier def _compute_df(self, block, tree): '''DF[n] = DFlocal[n] | [DFup[c] for c in tree.children[n]] DFlocal[n]: The successors of n that are not strictly dominated by n; DFup[n]: Nodes in the dominance frontier of n that are not strictly dominated by n's immediate dominator. ''' result = set() for succ in block.succs: if tree.get_parent_of(succ) is not block: result.add(succ) for c in tree.get_children_of(block): self._compute_df(c, tree) for v in self.dominance_frontier[c]: if not tree.is_dominator(block, v) or block is v: result.add(v) self.dominance_frontier[block] = result
ktok07b6/polyphony
polyphony/compiler/dominator.py
Python
mit
5,011
[ "VisIt" ]
07efdad63e16e289bb950ca22d3eda9c4e04c778102fe7f3b93f578c923b8269
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ 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/>. """ *************************************************************** **LBInitPeriodicForce** - handles external periodic forces *************************************************************** This class sets and adds an external periodic forces to a liquid """ from espresso.esutil import cxxinit from espresso import pmi from espresso.integrator.LBInit import * from _espresso import integrator_LBInit_PeriodicForce class LBInitPeriodicForceLocal(LBInitLocal, integrator_LBInit_PeriodicForce): """The (local) compute of LBInitPeriodicForce.""" def __init__(self, system, latticeboltzmann): if not pmi._PMIComm or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, integrator_LBInit_PeriodicForce, system, latticeboltzmann) if pmi.isController : class LBInitPeriodicForce(LBInit): __metaclass__ = pmi.Proxy pmiproxydefs = dict( cls = 'espresso.integrator.LBInitPeriodicForceLocal', pmicall = [ "setForce", "addForce"] )
BackupTheBerlios/espressopp
src/integrator/LBInitPeriodicForce.py
Python
gpl-3.0
1,943
[ "ESPResSo" ]
191a5239939634b17e2c742d7ef379fc84c277963b06d81ba6e331df3bf2aaa0
from __future__ import print_function import os import sys import glob import argparse import itertools import collections sys.path.append('/Users/loriab/linux/qcdb') sys.path.append('/Users/loriab/linux/qcdb/databases') import qcdb from qcdb.psivarrosetta import useme2psivar, optclue2psivar from qcdb.modelchems import Method, BasisSet, methods, bases from qcdb.exceptions import * import pandas as pd import numpy as np pd.set_option('display.max_columns', 10) pd.set_option('display.width', 200) SAPT_ALPHA = 0.0 # new for alpha=0 standard: toggle btwn 0.0 and 1.0 # <<< setup >>> parser = argparse.ArgumentParser(description='Expand quantum chemical terms into reaction quantities.') parser.add_argument('-d', '--dbmodule', help='force choice of database module, defaults to project value') parser.add_argument('-p', '--project', help='select pre-configured project') parser.add_argument('-v', '--verbose', type=int, default=1, help='amount of printing') parser.add_argument('-o', '--outdir', default='.', help='directory to write output files') parser.add_argument('-i', '--usemedir', help='directory containing input data files, defaults to project value') args = parser.parse_args() project = args.project homewrite = args.outdir verbose = args.verbose if verbose > 1: print(args) # <<< define projects >>> # pass --> pass if project == 'parenq': dbse = 'A24' ##path = r"""/Users/loriab/linux/qcdb/data/parenqusemefiles/""" path = r"""/Users/loriab/linux/qcdb/data/newparenq/""" # fail --> pass elif project == 'dft': dbse = 'S22' path = r"""/Users/loriab/linux/qcdb/data/dftusemefiles/""" # pass --> pass elif project == 'f12dilabio': dbse = 'A24' path = r"""/Users/loriab/linux/qcdb/data/f12dilabiousemefiles/""" # fail --> pass elif project == 'dhdft': dbse = 'S22' path = r"""/Users/loriab/linux/qcdb/data/dhdftusemefiles/""" #dbse = 'NBC10' #project == 'dhdft2': #path = r"""/Users/loriab/linux/qcdb/data/dhdftusemefiles/DSD/""" # pass --> pass elif project == 'dilabio': dbse = 'A24' path = r"""/Users/loriab/linux/qcdb/data/dilabiousemefiles/""" # pass --> pass elif project == 'pt2': dbse = 'S22' path = r"""/Users/loriab/linux/qcdb/data/pt2usemefiles/""" #path = r"""/Users/loriab/linux/qcdb/data/pt2usemefiles/mini""" # pass --> pass elif project == 'saptone': dbse = 'S22' path = r"""/Users/loriab/linux/qcdb/data/pt2usemefiles/""" elif project == 'sapta0a1conv': # perfectly fine but for testing only dbse = 'S22' path = r"""/Users/loriab/linux/qcdb/data/convert_sapt_alpha1_to_alpha0_usemefiles/""" elif project == 'saptmisc': #dbse = 'ACHC', 'BBI', 'S22by7', 'S66', 'SSI', 'UBQ' dbse = 'ACHC' path = r"""/Users/loriab/linux/qcdb/data/saptmiscusemefiles/""" elif project == 'dftmisc': #dbse = 'BBI', 'SSI' dbse = 'BBI' path = r"""/Users/loriab/linux/qcdb/data/dftmiscusemefiles/""" # not tested elif project in ['pt2misc', 'ccmisc']: dbse = 'SSI' #path = r"""/Users/loriab/linux/qcdb/data/merz3usemefiles/""" path = r"""/Users/loriab/linux/qcdb/data/bfdbwfnusemefiles/""" # not tested #dbse = 'S22' #project = 'aep' #path = r"""/Users/loriab/linux/qcdb/data/pt2usemefiles/""" elif project == 'sflow': dbse = 'S22' path = r"""/Users/loriab/linux/qcdb/data/flowusemefiles/""" elif project in ['dfit', 'dfitm']: #dbse = 'HBC6' #dbse = 'NBC10ext' #dbse = 'ACONF' dbse = 'SSI' path = r"""/Users/loriab/linux/Refitting_DFT_D/Databases/usemefiles/""" elif project in ['bfdbdftm', 'bfdbdft']: dbse = 'SSI' path = r"""/Users/loriab/linux/qcdb/data/bfdbdftusemefiles/""" elif project == 'nbcref': dbse = 'NBC10ext' path = r"""/Users/loriab/linux/Refitting_DFT_D/Databases/usemefiles/""" elif project == 'curveref': dbse = 'S22by7' path = r"""/Users/loriab/linux/Refitting_DFT_D/Databases/usemefiles/""" elif project == 'silver': dbse = 'PCONF' path = r"""/Users/loriab/linux/Refitting_DFT_D/Databases/usemefiles/""" elif project == 'fcnfc': pass else: raise ValidationError("""Project %s not defined.""" % (project)) # <<< learn about Database: rgts, rxns, modes, and stoichiometry dbse = dbse if args.dbmodule is None else args.dbmodule path = path if args.usemedir is None else args.usemedir dbobj = qcdb.Database(dbse, loadfrompickle=True) dbse = dbobj.dbse print('<<<', dbse, '>>>') modes = [] stoich = {} for orxn in dbobj.hrxn.itervalues(): tdict = {} for mode, rxnm in orxn.rxnm.iteritems(): modes.append(mode) rgtindx = 0 for wt in rxnm.itervalues(): tdict[(mode, 'Rgt' + str(rgtindx))] = wt rgtindx += 1 stoich[orxn.dbrxn] = tdict dfstoich = pd.DataFrame.from_dict(stoich, orient='index') modes = set(modes) names = ['rxn'] names.extend(['Rgt' + str(i) for i in range(12)]) maxrgt = 0 for mode in modes: maxrgt = max(maxrgt, dfstoich[mode].shape[1]) dfstoich.index.names = ['rxn'] h2kc = qcdb.psi_hartree2kcalmol if verbose > 1: print('DFSTOICH\n', names[:maxrgt + 1], dfstoich.head(5)) # <<< read usemefiles and convert to giant DataFrame >>> rawdata = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict))) usemeglob = glob.glob('%s/%s*useme*' % (path, dbse)) if len(usemeglob) == 0: raise ValidationError("""No %s usemefiles in %s.""" % (dbse, path)) for useme in usemeglob: spl = os.path.basename(useme).split('.') basis = spl[0].split('-')[-1] piece = '.'.join(spl[1:]) optns = spl[0].split('-')[2:-1] cpmode = 'default' optns2 = [] for opt in sorted(optns): if opt == 'CP': cpmode = opt elif opt == 'unCP': cpmode = 'default' else: try: if useme2psivar[piece] in optclue2psivar[opt]: optns2.append(opt) except KeyError as e: raise ValidationError('Error: option %s needs adding to to optclue2psivar in psivarrosetta.py: %s from %s' % (opt, e, useme)) optns = '-'.join(optns2) if verbose > 2: print(useme, basis, piece, optns, useme2psivar[piece]) try: print('Reading useme: %6s %50s %15s %5s' % (basis, useme2psivar[piece], optns, cpmode)) except KeyError as e: raise ValidationError('Error: useme %s needs adding to useme2psivar in psivarrosetta.py' % (e)) if piece.endswith('usemedash'): tmp = pd.read_csv('%s' % (useme), index_col=0, sep='\s+', comment='#', na_values='None', names=names[:maxrgt + 1]) rawdata[basis][useme2psivar[piece]][optns]['default'] = tmp.dropna(how='all') rawdata[basis][useme2psivar[piece]][optns]['CP'] = tmp.dropna(how='all') elif piece.endswith('usemesapt') or piece.endswith('usemedftsapt') or piece.endswith('usemempsapt'): # moved labels to top, removed comment marker for labels line, col relabeled to mp2cDisp20 for mpsapt tmp = pd.read_csv('%s' % (useme), index_col=0, sep='\s+', comment='#', na_values='None') sapt_cols = tmp.columns.tolist() tmp = pd.DataFrame(tmp.stack(), columns=['Rgt0']) tmp['Rgt0'] *= 0.001 # useme in mHartree tmp = tmp.reorder_levels([1, 0]) tmp.index.names = ['psivar', 'rxn'] for pv in sapt_cols: try: useme2psivar[pv] except KeyError as e: pass # bypass extra columns else: try: tmp2 = tmp.xs(pv, level='psivar') except KeyError as e: pass # bypass empty columns else: rawdata[basis][useme2psivar[pv]][optns]['SA'] = tmp2 else: tmp = pd.read_csv('%s' % (useme), index_col=0, sep='\s+', comment='#', na_values='None', names=names[:maxrgt + 1]) cpmode.replace('unCP', 'default') rawdata[basis][useme2psivar[piece]][optns][cpmode] = tmp.dropna(how='all') if verbose > 1: print(tmp.head(4)) baszip = {} for baskey, basval in sorted(rawdata.iteritems()): pvzip = {} for pvkey, pvval in sorted(basval.iteritems()): metazip = {} if verbose > 0: print("""reading %s %s""" % (pvkey, '.' * (40 - len(pvkey))), end='') for metakey, metaval, in pvval.iteritems(): metazip[metakey] = pd.concat(metaval, axis=1) # merge CP/unCP pvzip[pvkey] = pd.concat(metazip) if verbose > 0: print("""SUCCESS w/ %s %s""" % (baskey, ', '.join(metazip.keys()))) baszip[baskey] = pd.concat(pvzip) df = pd.concat(baszip) df.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] # <<< define utility functions >>> def rxnm_contract_expand(rgts): """Applies the stoichiometry array to the pd.DataFrame *rgts*, then sums across the reagents in each ACTV mode separately thus computing a reaction quantity. The reaction quantity is copied to every reagent within each ACTV mode for ease of further computation and returned. """ stoich_scaled_rgts = dfstoich.mul(rgts) micols = stoich_scaled_rgts.columns.values modes, rgts = zip(*micols) modezip = {} for mode in set(modes): rgts = [rg for md, rg in micols if md == mode] contracted_rxn = stoich_scaled_rgts[mode].sum(axis=1) rgtzip = {rg: contracted_rxn for rg in rgts} modezip[mode] = pd.concat(rgtzip, axis=1) expanded_rgts = pd.concat(modezip, axis=1) return expanded_rgts def cp2sa(rgts): stoich_scaled_rgts = dfstoich.mul(rgts) micols = stoich_scaled_rgts.columns.values modes, rgts = zip(*micols) modezip = {} for mode in set(modes): rgts = [rg for md, rg in micols if md == mode] contracted_rxn = stoich_scaled_rgts[mode].sum(axis=1) modezip[mode] = contracted_rxn expanded_rgts = pd.concat(modezip, axis=1) return expanded_rgts def reactionate(cpmode, rgts): """Apply the stoichiometry that turns reagent energies *rgts* into returned reaction energies, according to active mode *cpmode*. """ if cpmode == 'ave': cp = pd.DataFrame(dfstoich['CP'] * rgts['CP']) uncp = pd.DataFrame(dfstoich['default'] * rgts['default']) ave = 0.5 * (cp + uncp) if verbose > 2: print(ave) return ave.sum(axis=1) else: hjkl = pd.DataFrame(rgts[cpmode] * dfstoich[cpmode], index=rxns) if verbose > 2: print(hjkl) return hjkl.sum(axis=1) def categories(df, lvl): return sorted(set([tup[lvl] for tup in df.index.values])) def append_result_of_func_with_funcargs_to_master_DataFrame_atlevel_with_label(master, label, atlevel, func, funcargs): odr = {'psivar': [1, 3, 0, 2], 'bstrt': [3, 1, 0, 2]} data_rich_args = [master.xs(pv, level=atlevel) if isinstance(pv, basestring) else pv for pv in funcargs] multiopt = [] for item in data_rich_args: try: ####print ' C:', sorted(set([tup[1] for tup in item.index.values])) multiopt.append(sorted(set([tup[1] for tup in item.index.values]))) #multiopt.append(set([tup[1] for tup in item.index.values])) #multiopt.append(set(['-'.join(sorted(set(tup[1].split('-')))) for tup in item.index.values])) #multiopt.append(set(['-'.join(sorted(set(bn.split('-')))) for bn in sorted(set([tup[1] for tup in item.index.values]))])) #if label == 'MP2-F12 CORRELATION ENERGY': #if label == 'adtz': # bnbn = sorted(set([tup[1] for tup in item.index.values])) # print ' s1:', bnbn # bnbn2 = set(['-'.join(sorted(set(bn.split('-')))) for bn in bnbn]) # print ' s2:', bnbn2 #bnbn3 = #print ' s3:', bnbn3 # print ' tup:', ['-'.join(sorted(set(tup[1].split('-')))) for tup in item.index.values] #print ' set:', set([tup[1] for tup in item.index.values]) except AttributeError: pass #if label == 'MP2-F12 CORRELATION ENERGY': #if label == 'adtz': ####print ' ... opt comb:', multiopt # print ' ... options combinations:', list(itertools.product(*multiopt)) optzip = {} for multiopt in itertools.product(*multiopt): imultiopt = iter(multiopt) optlabel = '-'.join(set(sorted([opt for opt in multiopt if opt != '']))) # mm = optlabel.split('-') # if len(mm) > len(set(mm)): # #print ' die nan' # continue # print ' L:', optlabel, 'M:', multiopt data_rich_args_2 = [arg.xs(imultiopt.next(), level='meta') if isinstance(arg, pd.DataFrame) else arg for arg in data_rich_args] #if label.startswith('SCS(MI)-MP2-F12') or label == 'adtz': # print label, optlabel # print data_rich_args_2 candidate = func(data_rich_args_2) candidate = candidate.dropna(axis=0, how='all') if len(candidate) > 0: optzip[optlabel] = candidate ####print ' L:', optlabel, 'M:', multiopt #optzip[optlabel] = func(data_rich_args_2) #if label == 'SCS(MI)-MP2-F12 CORRELATION ENERGY': # print 'optzip', optzip temp = pd.concat(optzip) temp[atlevel] = label temp.set_index(atlevel, append=True, inplace=True) #print atlevel, 'QQpre', temp.index.values[0] temp = temp.reorder_levels(odr[atlevel]) #print atlevel, 'WWpst', temp.index.values[0] return master.append(temp, verify_integrity=True) #return master.combine_first(temp) # <<< define simple functions relating psi variables; follow args use in omega >>> def xtpl_power(args): power, zHI, eHI, eLO = args return (eHI * zHI ** power - eLO * (zHI - 1) ** power) / (zHI ** power - (zHI - 1) ** power) def dispersion_weighting(args): omega, hb_mtd, dd_mtd = args return omega * hb_mtd + (1.0 - omega) * dd_mtd def omega(args): alpha, beta, ratio = args return 0.5 * (1.0 + np.tanh(alpha + beta * ratio)) def difference(args): minuend, subtrahend = args return minuend - subtrahend def product(args): multiplicand, multiplier = args return multiplicand * multiplier def spin_component_scaling(args): os_scale, ss_scale, tot_corl, ss_corl = args return os_scale * (tot_corl - ss_corl) + ss_scale * ss_corl def correction(args): base, plus, minus = args return base + plus - minus def average(args): return sum(args) / len(args) # <<< append to main DataFrame basic psivar equalities not explicit to useme structure >>> lvl = 'psivar' pv0 = collections.OrderedDict() pv0['MP2-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv0['AVG-CCSD-F12 CORRELATION ENERGY'] = {'func': average, 'args': ['CCSD-F12A CORRELATION ENERGY', 'CCSD-F12B CORRELATION ENERGY']} pv0['AVG-CCSD-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'AVG-CCSD-F12 CORRELATION ENERGY']} pv0['CCSD-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD-F12A CORRELATION ENERGY']} pv0['CCSD-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD-F12B CORRELATION ENERGY']} pv0['CCSD-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD-F12C CORRELATION ENERGY']} #pv0['CCSD(T**)-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T**)-F12A CORRELATION ENERGY']} #pv0['CCSD(T**)-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T**)-F12B CORRELATION ENERGY']} #pv0['CCSD(T**)-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T**)-F12C CORRELATION ENERGY']} ###pv0['AVG-CCSD(T)-F12 CORRELATION ENERGY'] = {'func': sum, 'args': ['AVG-CCSD-F12 CORRELATION ENERGY', '(T)-F12AB CORRECTION ENERGY']} pv0['CCSD(T)-F12A CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12A CORRELATION ENERGY', '(T)-F12AB CORRECTION ENERGY']} pv0['CCSD(T)-F12B CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12B CORRELATION ENERGY', '(T)-F12AB CORRECTION ENERGY']} pv0['CCSD(T)-F12C CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12C CORRELATION ENERGY', '(T)-F12C CORRECTION ENERGY']} ###pv0['AVG-CCSD(T)-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'AVG-CCSD(T)-F12 CORRELATION ENERGY']} pv0['CCSD(T)-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T)-F12A CORRELATION ENERGY']} pv0['CCSD(T)-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T)-F12B CORRELATION ENERGY']} pv0['CCSD(T)-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T)-F12C CORRELATION ENERGY']} pv0['B3LYP TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY']} pv0['B970 TOTAL ENERGY'] = {'func': sum, 'args': ['B970 FUNCTIONAL TOTAL ENERGY']} pv0['B97 TOTAL ENERGY'] = {'func': sum, 'args': ['B97 FUNCTIONAL TOTAL ENERGY']} pv0['BP86 TOTAL ENERGY'] = {'func': sum, 'args': ['BP86 FUNCTIONAL TOTAL ENERGY']} pv0['BLYP TOTAL ENERGY'] = {'func': sum, 'args': ['BLYP FUNCTIONAL TOTAL ENERGY']} pv0['M05-2X TOTAL ENERGY'] = {'func': sum, 'args': ['M05-2X FUNCTIONAL TOTAL ENERGY']} pv0['M06-2X TOTAL ENERGY'] = {'func': sum, 'args': ['M06-2X FUNCTIONAL TOTAL ENERGY']} pv0['PBE0 TOTAL ENERGY'] = {'func': sum, 'args': ['PBE0 FUNCTIONAL TOTAL ENERGY']} pv0['PBE TOTAL ENERGY'] = {'func': sum, 'args': ['PBE FUNCTIONAL TOTAL ENERGY']} pv0['WPBE TOTAL ENERGY'] = {'func': sum, 'args': ['WPBE FUNCTIONAL TOTAL ENERGY']} pv0['PBEH-3C TOTAL ENERGY'] = {'func': sum, 'args': ['PBEH-3C FUNCTIONAL TOTAL ENERGY']} # proper basis restriction not imposed pv0['HF TOTAL ENERGY'] = {'func': sum, 'args': ['SCF TOTAL ENERGY']} pv0['MP3 CORRELATION ENERGY'] = {'func': difference, 'args': ['MP3 FNO CORRELATION ENERGY', 'FNO CORRECTION ENERGY']} # TODO not checked pv0['CCSD CORRELATION ENERGY'] = {'func': difference, 'args': ['CCSD FNO CORRELATION ENERGY', 'FNO CORRECTION ENERGY']} # TODO not checked pv0['CCSD(T) CORRELATION ENERGY'] = {'func': difference, 'args': ['CCSD(T) FNO CORRELATION ENERGY', 'FNO CORRECTION ENERGY']} pv0['CCSD(T) TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'CCSD(T) CORRELATION ENERGY']} pv0['CCSDT TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'CCSDT CORRELATION ENERGY']} pv0['CCSDT(Q) TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'CCSDT(Q) CORRELATION ENERGY']} pv0['VV10 TOTAL ENERGY'] = {'func': sum, 'args': ['VV10 FUNCTIONAL TOTAL ENERGY']} pv0['LC-VV10 TOTAL ENERGY'] = {'func': sum, 'args': ['LC-VV10 FUNCTIONAL TOTAL ENERGY']} pv0['M08-HX TOTAL ENERGY'] = {'func': sum, 'args': ['M08-HX FUNCTIONAL TOTAL ENERGY']} pv0['M08-SO TOTAL ENERGY'] = {'func': sum, 'args': ['M08-SO FUNCTIONAL TOTAL ENERGY']} pv0['M11 TOTAL ENERGY'] = {'func': sum, 'args': ['M11 FUNCTIONAL TOTAL ENERGY']} pv0['M11L TOTAL ENERGY'] = {'func': sum, 'args': ['M11L FUNCTIONAL TOTAL ENERGY']} pv0['MP2 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'MP2 CORRELATION ENERGY']} pv0['CCSD TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'CCSD CORRELATION ENERGY']} pv0['MP3 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'MP3 CORRELATION ENERGY']} for pvar, action in pv0.iteritems(): try: if verbose > 0: print("""building %s %s""" % (pvar, '.' * (50 - len(pvar))), end='') df = append_result_of_func_with_funcargs_to_master_DataFrame_atlevel_with_label( master=df, label=pvar, atlevel=lvl, func=action['func'], funcargs=action['args']) if verbose > 0: print("""SUCCESS""") except KeyError, e: if verbose > 0: print("""FAILED, missing %s""" % (e)) # <<< miscellaneous pre-computing >>> # <<< SAPT EXCHSCAL >>> try: if verbose > 0: print('building intermediate SAPT EXCHSCAL1 ...', end='') ex10 = df.xs('SAPT EXCH10 ENERGY', level='psivar') ex10ss = df.xs('SAPT EXCH10(S^2) ENERGY', level='psivar') except KeyError, e: if verbose > 0: print('NOT HANDLED, missing', e) else: ratio = ex10 / ex10ss ones = ratio.copy() ones['Rgt0'] = 1.0 logic = ex10 > 1.0e-5 # return 1.0 if ex10 < 1.0e-5 else ex10 / ex10ss exsc = ratio.where(logic, ones) exsc['psivar'] = 'SAPT EXCHSCAL1' exsc.set_index('psivar', append=True, inplace=True) exsc = exsc.reorder_levels([0, 3, 1, 2]) exsc.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] df = df.append(exsc, verify_integrity=True) if verbose > 0: print('SUCCESS') # <<< SA MP2 CORL >>> for pv in ['HF TOTAL ENERGY', 'MP2 CORRELATION ENERGY', 'HF-CABS TOTAL ENERGY', 'MP2-F12 CORRELATION ENERGY']: try: if verbose > 0: print('building intermediate SA %s ...' % (pv), end='') target = df.xs(pv, level='psivar') * 1.0 except KeyError, e: if verbose > 0: print('NOT HANDLED, missing', e) else: ans = cp2sa(target) target.loc[:, ('SA', 'Rgt0')] = ans['CP'] for md in ['CP', 'default']: try: target.drop(md, axis=1, inplace=True) except KeyError, e: pass target['psivar'] = pv target.set_index('psivar', append=True, inplace=True) target = target.reorder_levels([0, 3, 1, 2]) target.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] df.update(target, raise_conflict=True) if verbose > 0: print('SUCCESS') # <<< MP2 OMEGA >>> if verbose > 0: print('building intermediates DW-MP2 OMEGA, DW-MP2-F12-OMEGA ...', end='') dwmp2 = collections.defaultdict(dict) meta_combos = { '': ['', ''], 'dfmp': ['dfhf', 'dfhf-dfmp']} # TODO comprehensive? right? for mt, mtl in meta_combos.iteritems(): try: dwmp2['DW-MP2 OMEGA'][mt] = \ rxnm_contract_expand(df.xs('HF TOTAL ENERGY', level='psivar').xs(mtl[0], level='meta')) / \ rxnm_contract_expand(df.xs('MP2 TOTAL ENERGY', level='psivar').xs(mtl[1], level='meta')) except KeyError, e: pass try: dwmp2['DW-MP2-F12 OMEGA'][mt] = \ rxnm_contract_expand(df.xs('HF-CABS TOTAL ENERGY', level='psivar').xs(mtl[0], level='meta')) / \ rxnm_contract_expand(df.xs('MP2-F12 TOTAL ENERGY', level='psivar').xs(mtl[1], level='meta')) except KeyError, e: pass if not dwmp2: if verbose > 0: print('NOT HANDLED') else: pvzip = {} for pvkey, pvval in dwmp2.iteritems(): metazip = {} for metakey, metaval, in pvval.iteritems(): metazip[metakey] = metaval pvzip[pvkey] = pd.concat(metazip) df_omega = pd.concat(pvzip) df_omega = df_omega.reorder_levels([2, 0, 1, 3]) df_omega.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] try: df_omega = omega([0.15276, 1.89952, df_omega]) except KeyError, e: pass df = df.append(df_omega, verify_integrity=True) if verbose > 0: print('SUCCESS') # <<< DW-CCSD(T)-F12 >>> try: if verbose > 0: print('building intermediate DW-CCSD(T) OMEGA ...', end='') df.xs('HF-CABS TOTAL ENERGY', level='psivar') df.xs('MP2-F12 TOTAL ENERGY', level='psivar') except KeyError, e: print('NOT HANDLED, missing', e) else: ratio_HFCABS_MP2F12 = rxnm_contract_expand(df.xs('HF-CABS TOTAL ENERGY', level='psivar')) / \ rxnm_contract_expand(df.xs('MP2-F12 TOTAL ENERGY', level='psivar')) # TODO possibly set SA or other rxnm to NaN as inapplicable dwcc = {} try: dwcc['adz'] = omega([-1, 4, ratio_HFCABS_MP2F12.xs('adz', level='bstrt')]) except KeyError as e: pass try: dwcc['atz'] = omega([0.4, 0.6, ratio_HFCABS_MP2F12.xs('atz', level='bstrt')]) except KeyError as e: pass if len(dwcc) == 0: print('NOT HANDLED, missing valid basis set') else: df_omega = pd.concat(dwcc) df_omega['psivar'] = 'DW-CCSD(T)-F12 OMEGA' df_omega.set_index('psivar', append=True, inplace=True) df_omega = df_omega.reorder_levels([0, 3, 1, 2]) df_omega.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] df = df.append(df_omega, verify_integrity=True) if verbose > 0: print('SUCCESS') # <<< (T*)-F12 & (T**)-F12 >>> try: if verbose > 0: print('building intermediates (T*)-F12 & (T**)-F12 SCALE ...', end='') df.xs('MP2 CORRELATION ENERGY', level='psivar') df.xs('MP2-F12 CORRELATION ENERGY', level='psivar') except KeyError, e: if verbose > 0: print('NOT HANDLED, missing', e) else: ratio_MP2F12_MP2 = df.xs('MP2-F12 CORRELATION ENERGY', level='psivar') / \ df.xs('MP2 CORRELATION ENERGY', level='psivar') tstar = ratio_MP2F12_MP2.copy() tstar['psivar'] = '(T*)-F12 SCALE' tstar.set_index('psivar', append=True, inplace=True) tstar = tstar.reorder_levels([0, 3, 1, 2]) tstar.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] df = df.append(tstar, verify_integrity=True) if verbose > 0: print('SUCCESS', end='') tstarstar = ratio_MP2F12_MP2.copy() for md, rg in tstarstar.columns.values: if rg != 'Rgt0': tstarstar.loc[:, (md, rg)] = tstarstar[md]['Rgt0'] tstarstar['psivar'] = '(T**)-F12 SCALE' tstarstar.set_index('psivar', append=True, inplace=True) tstarstar = tstarstar.reorder_levels([0, 3, 1, 2]) tstarstar.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] df = df.append(tstarstar, verify_integrity=True) if verbose > 0: print('SUCCESS') # <<< DASH-D >>> try: if verbose > 0: print('building intermediates -D ...', end='') dashes = df.xs('nobas', level='bstrt') except KeyError, e: if verbose > 0: print('NOT HANDLED', e) else: df_nobas = pd.concat({tup[0]: dashes for tup in df.index.values if tup[0] != 'nobas'}) df_nobas.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] if verbose > 0: print('SUCCESS') df = df.append(df_nobas, verify_integrity=True) #mlist = ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-D2 DISPERSION CORRECTION ENERGY'] #for ml in mlist: # mdf = df.xs(ml, level='psivar').xs('adz', level='bstrt') # #mdf = df.xs(ml, level='psivar').xs('adz', level='bstrt').xs('S22-2', level='rxn') # print(ml, '\n')#, categories(mdf, 0) # #print h2kc * mdf # print(mdf.head(5)) # <<< append to main DataFrame computable method quantities >>> lvl = 'psivar' pv1 = collections.OrderedDict() pv1['B3LYP-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-D2 DISPERSION CORRECTION ENERGY']} pv1['B3LYP-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-D3 DISPERSION CORRECTION ENERGY']} pv1['B3LYP-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['B3LYP-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-D3M DISPERSION CORRECTION ENERGY']} pv1['B3LYP-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['B3LYP-XDM TOTAL ENERGY'] = {'func': sum, 'args': ['B3LYP FUNCTIONAL TOTAL ENERGY', 'B3LYP-XDM DISPERSION CORRECTION ENERGY']} pv1['B2PLYP-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['B2PLYP TOTAL ENERGY', 'B2PLYP-D2 DISPERSION CORRECTION ENERGY']} pv1['B2PLYP-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['B2PLYP TOTAL ENERGY', 'B2PLYP-D3 DISPERSION CORRECTION ENERGY']} pv1['B2PLYP-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['B2PLYP TOTAL ENERGY', 'B2PLYP-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['B2PLYP-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['B2PLYP TOTAL ENERGY', 'B2PLYP-D3M DISPERSION CORRECTION ENERGY']} pv1['B2PLYP-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['B2PLYP TOTAL ENERGY', 'B2PLYP-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['DSD-PBEP86-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['DSD-PBEP86 TOTAL ENERGY', 'DSD-PBEP86-D2 DISPERSION CORRECTION ENERGY']} pv1['DSD-PBEP86-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['DSD-PBEP86 TOTAL ENERGY', 'DSD-PBEP86-D3 DISPERSION CORRECTION ENERGY']} pv1['DSD-PBEP86-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['DSD-PBEP86 TOTAL ENERGY', 'DSD-PBEP86-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['B970-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['B970 FUNCTIONAL TOTAL ENERGY', 'B970-D2 DISPERSION CORRECTION ENERGY']} pv1['B97-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['B97 FUNCTIONAL TOTAL ENERGY', 'B97-D2 DISPERSION CORRECTION ENERGY']} pv1['B97-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['B97 FUNCTIONAL TOTAL ENERGY', 'B97-D3 DISPERSION CORRECTION ENERGY']} pv1['B97-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['B97 FUNCTIONAL TOTAL ENERGY', 'B97-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['B97-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['B97 FUNCTIONAL TOTAL ENERGY', 'B97-D3M DISPERSION CORRECTION ENERGY']} pv1['B97-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['B97 FUNCTIONAL TOTAL ENERGY', 'B97-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['BP86-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['BP86 FUNCTIONAL TOTAL ENERGY', 'BP86-D2 DISPERSION CORRECTION ENERGY']} pv1['BP86-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['BP86 FUNCTIONAL TOTAL ENERGY', 'BP86-D3 DISPERSION CORRECTION ENERGY']} pv1['BP86-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['BP86 FUNCTIONAL TOTAL ENERGY', 'BP86-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['BP86-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['BP86 FUNCTIONAL TOTAL ENERGY', 'BP86-D3M DISPERSION CORRECTION ENERGY']} pv1['BP86-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['BP86 FUNCTIONAL TOTAL ENERGY', 'BP86-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['BLYP-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['BLYP FUNCTIONAL TOTAL ENERGY', 'BLYP-D2 DISPERSION CORRECTION ENERGY']} pv1['BLYP-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['BLYP FUNCTIONAL TOTAL ENERGY', 'BLYP-D3 DISPERSION CORRECTION ENERGY']} pv1['BLYP-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['BLYP FUNCTIONAL TOTAL ENERGY', 'BLYP-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['BLYP-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['BLYP FUNCTIONAL TOTAL ENERGY', 'BLYP-D3M DISPERSION CORRECTION ENERGY']} pv1['BLYP-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['BLYP FUNCTIONAL TOTAL ENERGY', 'BLYP-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['PBE-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['PBE FUNCTIONAL TOTAL ENERGY', 'PBE-D2 DISPERSION CORRECTION ENERGY']} pv1['PBE-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['PBE FUNCTIONAL TOTAL ENERGY', 'PBE-D3 DISPERSION CORRECTION ENERGY']} pv1['PBE-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['PBE FUNCTIONAL TOTAL ENERGY', 'PBE-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['PBE-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['PBE FUNCTIONAL TOTAL ENERGY', 'PBE-D3M DISPERSION CORRECTION ENERGY']} pv1['PBE-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['PBE FUNCTIONAL TOTAL ENERGY', 'PBE-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['PBE0-D2 TOTAL ENERGY'] = {'func': sum, 'args': ['PBE0 FUNCTIONAL TOTAL ENERGY', 'PBE0-D2 DISPERSION CORRECTION ENERGY']} pv1['PBE0-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['PBE0 FUNCTIONAL TOTAL ENERGY', 'PBE0-D3 DISPERSION CORRECTION ENERGY']} pv1['PBE0-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['PBE0 FUNCTIONAL TOTAL ENERGY', 'PBE0-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['PBE0-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['PBE0 FUNCTIONAL TOTAL ENERGY', 'PBE0-D3M DISPERSION CORRECTION ENERGY']} pv1['PBE0-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['PBE0 FUNCTIONAL TOTAL ENERGY', 'PBE0-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['WPBE-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['WPBE FUNCTIONAL TOTAL ENERGY', 'WPBE-D3 DISPERSION CORRECTION ENERGY']} pv1['WPBE-D3(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['WPBE FUNCTIONAL TOTAL ENERGY', 'WPBE-D3(BJ) DISPERSION CORRECTION ENERGY']} pv1['WPBE-D3M TOTAL ENERGY'] = {'func': sum, 'args': ['WPBE FUNCTIONAL TOTAL ENERGY', 'WPBE-D3M DISPERSION CORRECTION ENERGY']} pv1['WPBE-D3M(BJ) TOTAL ENERGY'] = {'func': sum, 'args': ['WPBE FUNCTIONAL TOTAL ENERGY', 'WPBE-D3M(BJ) DISPERSION CORRECTION ENERGY']} pv1['M05-2X-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['M05-2X FUNCTIONAL TOTAL ENERGY', 'M05-2X-D3 DISPERSION CORRECTION ENERGY']} pv1['M06-2X-D3 TOTAL ENERGY'] = {'func': sum, 'args': ['M06-2X FUNCTIONAL TOTAL ENERGY', 'M06-2X-D3 DISPERSION CORRECTION ENERGY']} pv1['WB97X-D TOTAL ENERGY'] = {'func': sum, 'args': ['WB97X FUNCTIONAL TOTAL ENERGY', 'WB97X-D DISPERSION CORRECTION ENERGY']} pv1['DLDF+D TOTAL ENERGY'] = {'func': sum, 'args': ['DLDF FUNCTIONAL TOTAL ENERGY', 'DLDF+D DISPERSION CORRECTION ENERGY']} pv1['CCSD(T) CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T) CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['MP3 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['MP3 CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['MP2.5 CORRELATION ENERGY'] = {'func': dispersion_weighting, 'args': [0.5, 'MP3 CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['MP2.5 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'MP2.5 CORRELATION ENERGY']} pv1['MP2.5 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['MP2.5 CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['CCSD CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['SCS-CCSD CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS-CCSD CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['SCS(MI)-CCSD CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS(MI)-CCSD CORRELATION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['SCS-MP2 CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.2, 1.0 / 3.0, 'MP2 CORRELATION ENERGY', 'MP2 SAME-SPIN CORRELATION ENERGY']} pv1['SCS-MP2 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'SCS-MP2 CORRELATION ENERGY']} pv1['SCS(N)-MP2 CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [0.0, 1.76, 'MP2 CORRELATION ENERGY', 'MP2 SAME-SPIN CORRELATION ENERGY']} pv1['SCS(N)-MP2 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'SCS(N)-MP2 CORRELATION ENERGY']} pv1['DW-MP2 CORRELATION ENERGY'] = {'func': dispersion_weighting, 'args': ['DW-MP2 OMEGA', 'MP2 CORRELATION ENERGY', 'SCS-MP2 CORRELATION ENERGY']} pv1['DW-MP2 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'DW-MP2 CORRELATION ENERGY']} pv1['SCS-MP2-F12 CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.2, 1.0 / 3.0, 'MP2-F12 CORRELATION ENERGY', 'MP2-F12 SAME-SPIN CORRELATION ENERGY']} pv1['SCS-MP2-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS-MP2-F12 CORRELATION ENERGY']} pv1['SCS(N)-MP2-F12 CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [0.0, 1.76, 'MP2-F12 CORRELATION ENERGY', 'MP2-F12 SAME-SPIN CORRELATION ENERGY']} pv1['SCS(N)-MP2-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS(N)-MP2-F12 CORRELATION ENERGY']} pv1['DW-MP2-F12 CORRELATION ENERGY'] = {'func': dispersion_weighting, 'args': ['DW-MP2-F12 OMEGA', 'MP2-F12 CORRELATION ENERGY', 'SCS-MP2-F12 CORRELATION ENERGY']} pv1['DW-MP2-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'DW-MP2-F12 CORRELATION ENERGY']} pv1['SCS-CCSD-F12A CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.27, 1.13, 'CCSD-F12A CORRELATION ENERGY', 'CCSD-F12A SAME-SPIN CORRELATION ENERGY']} pv1['SCS-CCSD-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS-CCSD-F12A CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12A CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.11, 1.28, 'CCSD-F12A CORRELATION ENERGY', 'CCSD-F12A SAME-SPIN CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS(MI)-CCSD-F12A CORRELATION ENERGY']} pv1['SCS-CCSD-F12B CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.27, 1.13, 'CCSD-F12B CORRELATION ENERGY', 'CCSD-F12B SAME-SPIN CORRELATION ENERGY']} pv1['SCS-CCSD-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS-CCSD-F12B CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12B CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.11, 1.28, 'CCSD-F12B CORRELATION ENERGY', 'CCSD-F12B SAME-SPIN CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS(MI)-CCSD-F12B CORRELATION ENERGY']} pv1['SCS-CCSD-F12C CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.27, 1.13, 'CCSD-F12C CORRELATION ENERGY', 'CCSD-F12C SAME-SPIN CORRELATION ENERGY']} pv1['SCS-CCSD-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS-CCSD-F12C CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12C CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': [1.11, 1.28, 'CCSD-F12C CORRELATION ENERGY', 'CCSD-F12C SAME-SPIN CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS(MI)-CCSD-F12C CORRELATION ENERGY']} pv1['CCSD-F12A CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD-F12A CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD-F12B CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD-F12B CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD-F12C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD-F12C CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['SCS-CCSD-F12A CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS-CCSD-F12A CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['SCS-CCSD-F12B CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS-CCSD-F12B CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['SCS-CCSD-F12C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS-CCSD-F12C CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12A CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS(MI)-CCSD-F12A CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12B CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS(MI)-CCSD-F12B CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['SCS(MI)-CCSD-F12C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['SCS(MI)-CCSD-F12C CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['(T*)-F12AB CORRECTION ENERGY'] = {'func': product, 'args': ['(T*)-F12 SCALE', '(T)-F12AB CORRECTION ENERGY']} pv1['(T*)-F12C CORRECTION ENERGY'] = {'func': product, 'args': ['(T*)-F12 SCALE', '(T)-F12C CORRECTION ENERGY']} pv1['(T**)-F12AB CORRECTION ENERGY'] = {'func': product, 'args': ['(T**)-F12 SCALE', '(T)-F12AB CORRECTION ENERGY']} pv1['(T**)-F12C CORRECTION ENERGY'] = {'func': product, 'args': ['(T**)-F12 SCALE', '(T)-F12C CORRECTION ENERGY']} ###pv1['AVG-CCSD(T)-F12 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['AVG-CCSD(T)-F12 CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T)-F12A CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T)-F12A CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T)-F12B CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T)-F12B CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T)-F12C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T)-F12C CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} ###pv1['AVG-CCSD(T*)-F12 CORRELATION ENERGY'] = {'func': sum, 'args': ['AVG-CCSD-F12 CORRELATION ENERGY', '(T*)-F12AB CORRECTION ENERGY']} pv1['CCSD(T*)-F12A CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12A CORRELATION ENERGY', '(T*)-F12AB CORRECTION ENERGY']} pv1['CCSD(T*)-F12B CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12B CORRELATION ENERGY', '(T*)-F12AB CORRECTION ENERGY']} pv1['CCSD(T*)-F12C CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12C CORRELATION ENERGY', '(T*)-F12C CORRECTION ENERGY']} ###pv1['AVG-CCSD(T*)-F12 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['AVG-CCSD(T*)-F12 CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T*)-F12A CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T*)-F12A CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T*)-F12B CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T*)-F12B CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T*)-F12C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T*)-F12C CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} ###pv1['AVG-CCSD(T*)-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'AVG-CCSD(T*)-F12 CORRELATION ENERGY']} pv1['CCSD(T*)-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T*)-F12A CORRELATION ENERGY']} pv1['CCSD(T*)-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T*)-F12B CORRELATION ENERGY']} pv1['CCSD(T*)-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T*)-F12C CORRELATION ENERGY']} ###pv1['AVG-CCSD(T**)-F12 CORRELATION ENERGY'] = {'func': sum, 'args': ['AVG-CCSD-F12 CORRELATION ENERGY', '(T**)-F12AB CORRECTION ENERGY']} pv1['CCSD(T**)-F12A CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12A CORRELATION ENERGY', '(T**)-F12AB CORRECTION ENERGY']} pv1['CCSD(T**)-F12B CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12B CORRELATION ENERGY', '(T**)-F12AB CORRECTION ENERGY']} pv1['CCSD(T**)-F12C CORRELATION ENERGY'] = {'func': sum, 'args': ['CCSD-F12C CORRELATION ENERGY', '(T**)-F12C CORRECTION ENERGY']} pv1['CCSD(T**)-F12A CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T**)-F12A CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T**)-F12B CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T**)-F12B CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['CCSD(T**)-F12C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['CCSD(T**)-F12C CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['AVG-CCSD(T**)-F12 CORRELATION ENERGY'] = {'func': average, 'args': ['CCSD(T)-F12A CORRELATION ENERGY', 'CCSD(T**)-F12B CORRELATION ENERGY']} pv1['AVG-CCSD(T**)-F12 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['AVG-CCSD(T**)-F12 CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['AVG-CCSD(T**)-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'AVG-CCSD(T**)-F12 CORRELATION ENERGY']} pv1['CCSD(T**)-F12A TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T**)-F12A CORRELATION ENERGY']} # duplicate def pv1['CCSD(T**)-F12B TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T**)-F12B CORRELATION ENERGY']} # duplicate def pv1['CCSD(T**)-F12C TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'CCSD(T**)-F12C CORRELATION ENERGY']} # duplicate def pv1['DW-CCSD(T)-F12 CORRELATION ENERGY'] = {'func': dispersion_weighting, 'args': ['DW-CCSD(T)-F12 OMEGA', 'CCSD(T)-F12A CORRELATION ENERGY', 'CCSD(T)-F12B CORRELATION ENERGY']} pv1['DW-CCSD(T)-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'DW-CCSD(T)-F12 CORRELATION ENERGY']} pv1['DW-CCSD(T)-F12 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['DW-CCSD(T)-F12 CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['DW-CCSD(T*)-F12 CORRELATION ENERGY'] = {'func': dispersion_weighting, 'args': ['DW-CCSD(T)-F12 OMEGA', 'CCSD(T*)-F12A CORRELATION ENERGY', 'CCSD(T*)-F12B CORRELATION ENERGY']} pv1['DW-CCSD(T*)-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'DW-CCSD(T*)-F12 CORRELATION ENERGY']} pv1['DW-CCSD(T*)-F12 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['DW-CCSD(T*)-F12 CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['DW-CCSD(T**)-F12 CORRELATION ENERGY'] = {'func': dispersion_weighting, 'args': ['DW-CCSD(T)-F12 OMEGA', 'CCSD(T**)-F12A CORRELATION ENERGY', 'CCSD(T**)-F12B CORRELATION ENERGY']} pv1['DW-CCSD(T**)-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'DW-CCSD(T**)-F12 CORRELATION ENERGY']} pv1['DW-CCSD(T**)-F12 CC CORRECTION ENERGY'] = {'func': difference, 'args': ['DW-CCSD(T**)-F12 CORRELATION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['MP2C CC CORRECTION ENERGY'] = {'func': difference, 'args': ['MP2C DISP20 ENERGY', 'SAPT DISP20 ENERGY']} pv1['MP2C CORRELATION ENERGY'] = {'func': sum, 'args': ['MP2C CC CORRECTION ENERGY', 'MP2 CORRELATION ENERGY']} pv1['MP2C TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'MP2C CORRELATION ENERGY']} pv1['MP2C-F12 CC CORRECTION ENERGY'] = {'func': sum, 'args': ['MP2C CC CORRECTION ENERGY']} pv1['MP2C-F12 CORRELATION ENERGY'] = {'func': sum, 'args': ['MP2C CC CORRECTION ENERGY', 'MP2-F12 CORRELATION ENERGY']} pv1['MP2C-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'MP2C-F12 CORRELATION ENERGY']} pv1['SAPT EXCHSCAL3'] = {'func': lambda x: x[0] ** 3, 'args': ['SAPT EXCHSCAL1']} pv1['SAPT EXCHSCAL'] = {'func': lambda x: x[0] ** SAPT_ALPHA, 'args': ['SAPT EXCHSCAL1']} # new for alpha=0 standard pv1['SAPT HF(2) ALPHA=0.0 ENERGY'] = {'func': lambda x: x[0] - (x[1] + x[2] + x[3] + x[4]), 'args': ['SAPT HF TOTAL ENERGY', 'SAPT ELST10,R ENERGY', 'SAPT EXCH10 ENERGY', 'SAPT IND20,R ENERGY', 'SAPT EXCH-IND20,R ENERGY']} pv1['SAPT HF(2) ENERGY'] = {'func': lambda x: x[1] + (1.0 - x[0]) * x[2], 'args': ['SAPT EXCHSCAL', 'SAPT HF(2) ALPHA=0.0 ENERGY', 'SAPT EXCH-IND20,R ENERGY']} pv1['SAPT HF(3) ENERGY'] = {'func': lambda x: x[1] - (x[2] + x[0] * x[3]), 'args': ['SAPT EXCHSCAL', 'SAPT HF(2) ENERGY', 'SAPT IND30,R ENERGY', 'SAPT EXCH-IND30,R ENERGY']} pv1['SAPT MP2(2) ENERGY'] = {'func': lambda x: x[1] - (x[2] + x[3] + x[4] + x[0] * (x[5] + x[6] + x[7] + x[8])), 'args': ['SAPT EXCHSCAL', 'MP2 CORRELATION ENERGY', 'SAPT ELST12,R ENERGY', 'SAPT IND22 ENERGY', 'SAPT DISP20 ENERGY', 'SAPT EXCH11(S^2) ENERGY', 'SAPT EXCH12(S^2) ENERGY', 'SAPT EXCH-IND22 ENERGY', 'SAPT EXCH-DISP20 ENERGY']} pv1['SAPT MP2(3) ENERGY'] = {'func': lambda x: x[1] - (x[2] + x[0] * x[3]), 'args': ['SAPT EXCHSCAL', 'SAPT MP2(2) ENERGY', 'SAPT IND-DISP30 ENERGY', 'SAPT EXCH-IND-DISP30 ENERGY']} pv1['SAPT MP4 DISP'] = {'func': lambda x: x[0] * x[1] + x[2] + x[3] + x[4] + x[5], 'args': ['SAPT EXCHSCAL', 'SAPT EXCH-DISP20 ENERGY', 'SAPT DISP20 ENERGY', 'SAPT DISP21 ENERGY', 'SAPT DISP22(SDQ) ENERGY', 'SAPT EST.DISP22(T) ENERGY']} pv1['SAPT CCD DISP'] = {'func': lambda x: x[0] * x[1] + x[2] + x[3] + x[4], 'args': ['SAPT EXCHSCAL', 'SAPT EXCH-DISP20 ENERGY', 'SAPT DISP2(CCD) ENERGY', 'SAPT DISP22(S)(CCD) ENERGY', 'SAPT EST.DISP22(T)(CCD) ENERGY']} pv1['SAPT0 ELST ENERGY'] = {'func': sum, 'args': ['SAPT ELST10,R ENERGY']} pv1['SAPT0 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT EXCH10 ENERGY']} pv1['SAPT0 INDC ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3], 'args': ['SAPT EXCHSCAL', 'SAPT HF(2) ENERGY', 'SAPT IND20,R ENERGY', 'SAPT EXCH-IND20,R ENERGY']} pv1['SAPT0 DISP ENERGY'] = {'func': lambda x: x[0] * x[1] + x[2], 'args': ['SAPT EXCHSCAL', 'SAPT EXCH-DISP20 ENERGY', 'SAPT DISP20 ENERGY']} pv1['SAPT0 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT0 ELST ENERGY', 'SAPT0 EXCH ENERGY', 'SAPT0 INDC ENERGY', 'SAPT0 DISP ENERGY']} pv1['SSAPT0 ELST ENERGY'] = {'func': sum, 'args': ['SAPT0 ELST ENERGY']} pv1['SSAPT0 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT0 EXCH ENERGY']} pv1['SSAPT0 INDC ENERGY'] = {'func': lambda x: x[1] + (x[0] - 1.0) * x[2], 'args': ['SAPT EXCHSCAL3', 'SAPT0 INDC ENERGY', 'SAPT EXCH-IND20,R ENERGY']} pv1['SSAPT0 DISP ENERGY'] = {'func': lambda x: x[0] * x[1] + x[2], 'args': ['SAPT EXCHSCAL3', 'SAPT EXCH-DISP20 ENERGY', 'SAPT DISP20 ENERGY']} pv1['SSAPT0 TOTAL ENERGY'] = {'func': sum, 'args': ['SSAPT0 ELST ENERGY', 'SSAPT0 EXCH ENERGY', 'SSAPT0 INDC ENERGY', 'SSAPT0 DISP ENERGY']} pv1['SCS-SAPT0 ELST ENERGY'] = {'func': sum, 'args': ['SAPT0 ELST ENERGY']} pv1['SCS-SAPT0 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT0 EXCH ENERGY']} pv1['SCS-SAPT0 INDC ENERGY'] = {'func': sum, 'args': ['SAPT0 INDC ENERGY']} pv1['SCS-SAPT0 DISP ENERGY'] = {'func': lambda x: x[0] * (x[1] + x[2]) + x[3] * (x[4] + x[5]), 'args': [0.66, 'SAPT EXCH-DISP20(SS) ENERGY', 'SAPT DISP20(SS) ENERGY', 1.2, 'SAPT EXCH-DISP20(OS) ENERGY', 'SAPT DISP20(OS) ENERGY']} # note no xs for SCS disp pv1['SCS-SAPT0 TOTAL ENERGY'] = {'func': sum, 'args': ['SCS-SAPT0 ELST ENERGY', 'SCS-SAPT0 EXCH ENERGY', 'SCS-SAPT0 INDC ENERGY', 'SCS-SAPT0 DISP ENERGY']} pv1['SAPT2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT ELST10,R ENERGY', 'SAPT ELST12,R ENERGY']} pv1['SAPT2 EXCH ENERGY'] = {'func': lambda x: x[1] + x[0] * (x[2] + x[3]), 'args': ['SAPT EXCHSCAL', 'SAPT EXCH10 ENERGY', 'SAPT EXCH11(S^2) ENERGY', 'SAPT EXCH12(S^2) ENERGY']} pv1['SAPT2 INDC ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3] + x[4] + x[0] * x[5], 'args': ['SAPT EXCHSCAL', 'SAPT HF(2) ENERGY', 'SAPT IND20,R ENERGY', 'SAPT EXCH-IND20,R ENERGY', 'SAPT IND22 ENERGY', 'SAPT EXCH-IND22 ENERGY']} pv1['SAPT2 DISP ENERGY'] = {'func': lambda x: x[0] * x[1] + x[2], 'args': ['SAPT EXCHSCAL', 'SAPT EXCH-DISP20 ENERGY', 'SAPT DISP20 ENERGY']} pv1['SAPT2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2 ELST ENERGY', 'SAPT2 EXCH ENERGY', 'SAPT2 INDC ENERGY', 'SAPT2 DISP ENERGY']} pv1['SAPT2+ ELST ENERGY'] = {'func': sum, 'args': ['SAPT ELST10,R ENERGY', 'SAPT ELST12,R ENERGY']} pv1['SAPT2+ EXCH ENERGY'] = {'func': lambda x: x[1] + x[0] * (x[2] + x[3]), 'args': ['SAPT EXCHSCAL', 'SAPT EXCH10 ENERGY', 'SAPT EXCH11(S^2) ENERGY', 'SAPT EXCH12(S^2) ENERGY']} pv1['SAPT2+ INDC ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3] + x[4] + x[0] * x[5], 'args': ['SAPT EXCHSCAL', 'SAPT HF(2) ENERGY', 'SAPT IND20,R ENERGY', 'SAPT EXCH-IND20,R ENERGY', 'SAPT IND22 ENERGY', 'SAPT EXCH-IND22 ENERGY']} pv1['SAPT2+ DISP ENERGY'] = {'func': sum, 'args': ['SAPT MP4 DISP']} pv1['SAPT2+ TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+ ELST ENERGY', 'SAPT2+ EXCH ENERGY', 'SAPT2+ INDC ENERGY', 'SAPT2+ DISP ENERGY']} pv1['SAPT2+(CCD) ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+ ELST ENERGY']} pv1['SAPT2+(CCD) EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+ EXCH ENERGY']} pv1['SAPT2+(CCD) INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+ INDC ENERGY']} pv1['SAPT2+(CCD) DISP ENERGY'] = {'func': sum, 'args': ['SAPT CCD DISP']} pv1['SAPT2+(CCD) TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+(CCD) ELST ENERGY', 'SAPT2+(CCD) EXCH ENERGY', 'SAPT2+(CCD) INDC ENERGY', 'SAPT2+(CCD) DISP ENERGY']} pv1['SAPT2+DMP2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+ ELST ENERGY']} pv1['SAPT2+DMP2 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+ EXCH ENERGY']} pv1['SAPT2+DMP2 INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+ INDC ENERGY', 'SAPT MP2(2) ENERGY']} pv1['SAPT2+DMP2 DISP ENERGY'] = {'func': sum, 'args': ['SAPT2+ DISP ENERGY']} pv1['SAPT2+DMP2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+DMP2 ELST ENERGY', 'SAPT2+DMP2 EXCH ENERGY', 'SAPT2+DMP2 INDC ENERGY', 'SAPT2+DMP2 DISP ENERGY']} pv1['SAPT2+(CCD)DMP2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+ ELST ENERGY']} pv1['SAPT2+(CCD)DMP2 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+ EXCH ENERGY']} pv1['SAPT2+(CCD)DMP2 INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+DMP2 INDC ENERGY']} pv1['SAPT2+(CCD)DMP2 DISP ENERGY'] = {'func': sum, 'args': ['SAPT2+(CCD) DISP ENERGY']} pv1['SAPT2+(CCD)DMP2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+(CCD)DMP2 ELST ENERGY', 'SAPT2+(CCD)DMP2 EXCH ENERGY', 'SAPT2+(CCD)DMP2 INDC ENERGY', 'SAPT2+(CCD)DMP2 DISP ENERGY']} pv1['SAPT2+(3) ELST ENERGY'] = {'func': sum, 'args': ['SAPT ELST10,R ENERGY', 'SAPT ELST12,R ENERGY', 'SAPT ELST13,R ENERGY']} pv1['SAPT2+(3) EXCH ENERGY'] = {'func': lambda x: x[1] + x[0] * (x[2] + x[3]), 'args': ['SAPT EXCHSCAL', 'SAPT EXCH10 ENERGY', 'SAPT EXCH11(S^2) ENERGY', 'SAPT EXCH12(S^2) ENERGY']} pv1['SAPT2+(3) INDC ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3] + x[4] + x[0] * x[5], 'args': ['SAPT EXCHSCAL', 'SAPT HF(2) ENERGY', 'SAPT IND20,R ENERGY', 'SAPT EXCH-IND20,R ENERGY', 'SAPT IND22 ENERGY', 'SAPT EXCH-IND22 ENERGY']} pv1['SAPT2+(3) DISP ENERGY'] = {'func': sum, 'args': ['SAPT MP4 DISP', 'SAPT DISP30 ENERGY']} pv1['SAPT2+(3) TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) ELST ENERGY', 'SAPT2+(3) EXCH ENERGY', 'SAPT2+(3) INDC ENERGY', 'SAPT2+(3) DISP ENERGY']} pv1['SAPT2+(3)(CCD) ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) ELST ENERGY']} pv1['SAPT2+(3)(CCD) EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) EXCH ENERGY']} pv1['SAPT2+(3)(CCD) INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) INDC ENERGY']} pv1['SAPT2+(3)(CCD) DISP ENERGY'] = {'func': sum, 'args': ['SAPT CCD DISP', 'SAPT DISP30 ENERGY']} pv1['SAPT2+(3)(CCD) TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+(3)(CCD) ELST ENERGY', 'SAPT2+(3)(CCD) EXCH ENERGY', 'SAPT2+(3)(CCD) INDC ENERGY', 'SAPT2+(3)(CCD) DISP ENERGY']} pv1['SAPT2+(3)DMP2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) ELST ENERGY']} pv1['SAPT2+(3)DMP2 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) EXCH ENERGY']} pv1['SAPT2+(3)DMP2 INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) INDC ENERGY', 'SAPT MP2(2) ENERGY']} pv1['SAPT2+(3)DMP2 DISP ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) DISP ENERGY']} pv1['SAPT2+(3)DMP2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+(3)DMP2 ELST ENERGY', 'SAPT2+(3)DMP2 EXCH ENERGY', 'SAPT2+(3)DMP2 INDC ENERGY', 'SAPT2+(3)DMP2 DISP ENERGY']} pv1['SAPT2+(3)(CCD)DMP2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) ELST ENERGY']} pv1['SAPT2+(3)(CCD)DMP2 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+(3) EXCH ENERGY']} pv1['SAPT2+(3)(CCD)DMP2 INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+(3)DMP2 INDC ENERGY']} pv1['SAPT2+(3)(CCD)DMP2 DISP ENERGY'] = {'func': sum, 'args': ['SAPT2+(3)(CCD) DISP ENERGY']} pv1['SAPT2+(3)(CCD)DMP2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+(3)(CCD)DMP2 ELST ENERGY', 'SAPT2+(3)(CCD)DMP2 EXCH ENERGY', 'SAPT2+(3)(CCD)DMP2 INDC ENERGY', 'SAPT2+(3)(CCD)DMP2 DISP ENERGY']} pv1['SAPT2+3 ELST ENERGY'] = {'func': sum, 'args': ['SAPT ELST10,R ENERGY', 'SAPT ELST12,R ENERGY', 'SAPT ELST13,R ENERGY']} pv1['SAPT2+3 EXCH ENERGY'] = {'func': lambda x: x[1] + x[0] * (x[2] + x[3]), 'args': ['SAPT EXCHSCAL', 'SAPT EXCH10 ENERGY', 'SAPT EXCH11(S^2) ENERGY', 'SAPT EXCH12(S^2) ENERGY']} pv1['SAPT2+3 INDC ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3] + x[4] + x[0] * x[5] + x[6] + x[0] * x[7], 'args': ['SAPT EXCHSCAL', 'SAPT HF(3) ENERGY', 'SAPT IND20,R ENERGY', 'SAPT EXCH-IND20,R ENERGY', 'SAPT IND22 ENERGY', 'SAPT EXCH-IND22 ENERGY', 'SAPT IND30,R ENERGY', 'SAPT EXCH-IND30,R ENERGY']} pv1['SAPT2+3 DISP ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3] + x[4] + x[0] * x[5], 'args': ['SAPT EXCHSCAL', 'SAPT MP4 DISP', 'SAPT DISP30 ENERGY', 'SAPT EXCH-DISP30 ENERGY', 'SAPT IND-DISP30 ENERGY', 'SAPT EXCH-IND-DISP30 ENERGY']} pv1['SAPT2+3 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+3 ELST ENERGY', 'SAPT2+3 EXCH ENERGY', 'SAPT2+3 INDC ENERGY', 'SAPT2+3 DISP ENERGY']} pv1['SAPT2+3(CCD) ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+3 ELST ENERGY']} pv1['SAPT2+3(CCD) EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+3 EXCH ENERGY']} pv1['SAPT2+3(CCD) INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+3 INDC ENERGY']} pv1['SAPT2+3(CCD) DISP ENERGY'] = {'func': lambda x: x[1] + x[2] + x[0] * x[3] + x[4] + x[0] * x[5], 'args': ['SAPT EXCHSCAL', 'SAPT CCD DISP', 'SAPT DISP30 ENERGY', 'SAPT EXCH-DISP30 ENERGY', 'SAPT IND-DISP30 ENERGY', 'SAPT EXCH-IND-DISP30 ENERGY']} pv1['SAPT2+3(CCD) TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+3(CCD) ELST ENERGY', 'SAPT2+3(CCD) EXCH ENERGY', 'SAPT2+3(CCD) INDC ENERGY', 'SAPT2+3(CCD) DISP ENERGY']} pv1['SAPT2+3DMP2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+3 ELST ENERGY']} pv1['SAPT2+3DMP2 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+3 EXCH ENERGY']} pv1['SAPT2+3DMP2 INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+3 INDC ENERGY', 'SAPT MP2(3) ENERGY']} pv1['SAPT2+3DMP2 DISP ENERGY'] = {'func': sum, 'args': ['SAPT2+3 DISP ENERGY']} pv1['SAPT2+3DMP2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+3DMP2 ELST ENERGY', 'SAPT2+3DMP2 EXCH ENERGY', 'SAPT2+3DMP2 INDC ENERGY', 'SAPT2+3DMP2 DISP ENERGY']} pv1['SAPT2+3(CCD)DMP2 ELST ENERGY'] = {'func': sum, 'args': ['SAPT2+3 ELST ENERGY']} pv1['SAPT2+3(CCD)DMP2 EXCH ENERGY'] = {'func': sum, 'args': ['SAPT2+3 EXCH ENERGY']} pv1['SAPT2+3(CCD)DMP2 INDC ENERGY'] = {'func': sum, 'args': ['SAPT2+3DMP2 INDC ENERGY']} pv1['SAPT2+3(CCD)DMP2 DISP ENERGY'] = {'func': sum, 'args': ['SAPT2+3(CCD) DISP ENERGY']} pv1['SAPT2+3(CCD)DMP2 TOTAL ENERGY'] = {'func': sum, 'args': ['SAPT2+3(CCD)DMP2 ELST ENERGY', 'SAPT2+3(CCD)DMP2 EXCH ENERGY', 'SAPT2+3(CCD)DMP2 INDC ENERGY', 'SAPT2+3(CCD)DMP2 DISP ENERGY']} pv1['DFT-SAPT ELST ENERGY'] = {'func': sum, 'args': ['DFT-SAPT ELST10,R ENERGY']} pv1['DFT-SAPT EXCH ENERGY'] = {'func': sum, 'args': ['DFT-SAPT EXCH10 ENERGY']} pv1['DFT-SAPT INDC ENERGY'] = {'func': sum, 'args': ['SAPT HF(2) ALPHA=0.0 ENERGY', 'DFT-SAPT IND20,R ENERGY', 'DFT-SAPT EXCH-IND20,R ENERGY']} pv1['DFT-SAPT DISP ENERGY'] = {'func': sum, 'args': ['DFT-SAPT DISP20 ENERGY', 'DFT-SAPT EXCH-DISP20 ENERGY']} pv1['DFT-SAPT TOTAL ENERGY'] = {'func': sum, 'args': ['DFT-SAPT ELST ENERGY', 'DFT-SAPT EXCH ENERGY', 'DFT-SAPT INDC ENERGY', 'DFT-SAPT DISP ENERGY']} for pvar, action in pv1.iteritems(): try: if verbose > 0: print("""building %s %s""" % (pvar, '.' * (50 - len(pvar))), end='') df = append_result_of_func_with_funcargs_to_master_DataFrame_atlevel_with_label( master=df, label=pvar, atlevel=lvl, func=action['func'], funcargs=action['args']) if verbose > 0: print("""SUCCESS""") except KeyError, e: if verbose > 0: print("""FAILED, missing %s""" % (e)) #mlist = ['SAPT0 TOTAL ENERGY', 'SAPT0 DISP ENERGY', 'SAPT EXCHSCAL', 'SAPT HF(2) ENERGY'] #mlist = ['MP2 CORRELATION ENERGY', 'MP2C CC CORRECTION ENERGY', 'MP2C CORRELATION ENERGY', 'MP2C TOTAL ENERGY'] #for ml in mlist: # mdf = df.xs(ml, level='psivar').xs('adz', level='bstrt').xs('S22-2', level='rxn') # print ml, '\n'#, categories(mdf, 0) # #print h2kc * mdf # mdf *= h2kc # print mdf.head(5) # <<< define extra Method and BasisSet objects >>> # Note dict key must match object name; i.e., first two strings on line must be the same # Note also that methods are all caps, bases all lowercase #bases['hill1_adtz'] = BasisSet('hill1_adtz', build=[['hillcc_adtz'], ['atz', 'hillcc_adtz']]) # TODO should have None or non-xtpl first element? #bases['hill2_dtzf12'] = BasisSet('hill2_dtzf12', build=[None, None, ['tzf12', 'hillcc_dtzf12', 'hillt_dtzf12']]) #methods['CCSDTNSAF12'] = Method('CCSDTNSAF12', fullname='CCSD(T)-F12a') # <<< append to main DataFrame computable basis treatment quantities >>> lvl = 'bstrt' pv2 = collections.OrderedDict() pv2['dtz'] = {'func': xtpl_power, 'args': [3.0, 3, 'tz', 'dz']} pv2['jadtz'] = {'func': xtpl_power, 'args': [3.0, 3, 'jatz', 'jadz']} pv2['hadtz'] = {'func': xtpl_power, 'args': [3.0, 3, 'hatz', 'hadz']} pv2['adtz'] = {'func': xtpl_power, 'args': [3.0, 3, 'atz', 'adz']} pv2['tqz'] = {'func': xtpl_power, 'args': [3.0, 4, 'qz', 'tz']} pv2['matqz'] = {'func': xtpl_power, 'args': [3.0, 4, 'maqz', 'matz']} pv2['jatqz'] = {'func': xtpl_power, 'args': [3.0, 4, 'jaqz', 'jatz']} pv2['hatqz'] = {'func': xtpl_power, 'args': [3.0, 4, 'haqz', 'hatz']} pv2['atqz'] = {'func': xtpl_power, 'args': [3.0, 4, 'aqz', 'atz']} pv2['q5z'] = {'func': xtpl_power, 'args': [3.0, 5, '5z', 'qz']} pv2['maq5z'] = {'func': xtpl_power, 'args': [3.0, 5, 'ma5z', 'maqz']} pv2['jaq5z'] = {'func': xtpl_power, 'args': [3.0, 5, 'ja5z', 'jaqz']} pv2['haq5z'] = {'func': xtpl_power, 'args': [3.0, 5, 'ha5z', 'haqz']} pv2['aq5z'] = {'func': xtpl_power, 'args': [3.0, 5, 'a5z', 'aqz']} pv2['56z'] = {'func': xtpl_power, 'args': [3.0, 6, '6z', '5z']} pv2['ma56z'] = {'func': xtpl_power, 'args': [3.0, 6, 'ma6z', 'ma5z']} pv2['ja56z'] = {'func': xtpl_power, 'args': [3.0, 6, 'ja6z', 'ja5z']} pv2['ha56z'] = {'func': xtpl_power, 'args': [3.0, 6, 'ha6z', 'ha5z']} pv2['a56z'] = {'func': xtpl_power, 'args': [3.0, 6, 'a6z', 'a5z']} pv2['dtzf12'] = {'func': xtpl_power, 'args': [3.0, 3, 'tzf12', 'dzf12']} pv2['tqzf12'] = {'func': xtpl_power, 'args': [3.0, 4, 'qzf12', 'tzf12']} # Hill xtpl for CCSD-F12b from Table X of JCP 131 194105 (2009) # TODO should only be applied to CCF12, as per definition (literally, only CCF12B) pv2['hillcc_adtz'] = {'func': xtpl_power, 'args': [2.483070, 3, 'atz', 'adz']} pv2['hillcc_atqz'] = {'func': xtpl_power, 'args': [4.255221, 4, 'aqz', 'atz']} pv2['hillcc_aq5z'] = {'func': xtpl_power, 'args': [4.910269, 5, 'a5z', 'aqz']} pv2['hillcc_dtzf12'] = {'func': xtpl_power, 'args': [3.144518, 3, 'tzf12', 'dzf12']} pv2['hillcc_tqzf12'] = {'func': xtpl_power, 'args': [4.595995, 4, 'qzf12', 'tzf12']} # Hill xtpl for unscaled (T)-F12 from Table XI of JCP 131 194105 (2009) pv2['hillt_adtz'] = {'func': xtpl_power, 'args': [2.790300, 3, 'atz', 'adz']} pv2['hillt_dtzf12'] = {'func': xtpl_power, 'args': [2.615472, 3, 'tzf12', 'dzf12']} for pvar, action in pv2.iteritems(): try: if verbose > 0: print("""building %s %s""" % (pvar, '.' * (50 - len(pvar))), end='') df = append_result_of_func_with_funcargs_to_master_DataFrame_atlevel_with_label( master=df, label=pvar, atlevel=lvl, func=action['func'], funcargs=action['args']) if verbose > 0: print("""SUCCESS""") except KeyError, e: if verbose > 0: print("""FAILED, missing %s""" % (e)) # <<< SCS(MI)-MP2 & SCS(MI)-F12 >>> try: if verbose > 0: print('building intermediates SCS(MI)-MP2 ...', end='') df.xs('MP2-F12 CORRELATION ENERGY', level='psivar') df.xs('MP2 CORRELATION ENERGY', level='psivar') except KeyError, e: print('NOT HANDLED, missing', e) else: mi_os = { 'atz': 0.17, 'adtz': 0.29, 'aqz': 0.31, 'atqz': 0.40, 'hatz': 0.17, 'hadtz': 0.29, 'haqz': 0.31, 'hatqz': 0.40, 'jatz': 0.17, 'jadtz': 0.29, 'jaqz': 0.31, 'jatqz': 0.40, 'matz': 0.17, 'maqz': 0.31, 'matqz': 0.40, 'aaqz': 0.31, 'tz': 0.17, 'dtz': 0.29, 'qz': 0.31, 'tqz': 0.40, 'tzf12': 0.17} mi_ss = { 'atz': 1.75, 'adtz': 1.46, 'aqz': 1.46, 'atqz': 1.29, 'hatz': 1.75, 'hadtz': 1.46, 'haqz': 1.46, 'hatqz': 1.29, 'jatz': 1.75, 'jadtz': 1.46, 'jaqz': 1.46, 'jatqz': 1.29, 'matz': 1.75, 'maqz': 1.46, 'matqz': 1.29, 'aaqz': 1.46, 'tz': 1.75, 'dtz': 1.46, 'qz': 1.46, 'tqz': 1.29, 'tzf12': 1.75} mi_os = collections.defaultdict(lambda: np.nan, mi_os) mi_ss = collections.defaultdict(lambda: np.nan, mi_ss) merge = {} merge_os = {} merge_ss = {} for bstrt in categories(df.xs('MP2 CORRELATION ENERGY', level='psivar'), 0): temp_os = df.xs('MP2 CORRELATION ENERGY', level='psivar').xs(bstrt, level='bstrt') temp_ss = df.xs('MP2 CORRELATION ENERGY', level='psivar').xs(bstrt, level='bstrt') temp_os[:][:] = mi_os[bstrt] temp_ss[:][:] = mi_ss[bstrt] merge_os[bstrt] = temp_os merge_ss[bstrt] = temp_ss merge['SCS(MI)-MP2 SCS-OS'] = pd.concat(merge_os) merge['SCS(MI)-MP2 SCS-SS'] = pd.concat(merge_ss) merge_os = {} merge_ss = {} for bstrt in categories(df.xs('MP2-F12 CORRELATION ENERGY', level='psivar'), 0): temp_os = df.xs('MP2-F12 CORRELATION ENERGY', level='psivar').xs(bstrt, level='bstrt') temp_ss = df.xs('MP2-F12 CORRELATION ENERGY', level='psivar').xs(bstrt, level='bstrt') temp_os[:][:] = mi_os[bstrt] temp_ss[:][:] = mi_ss[bstrt] merge_os[bstrt] = temp_os merge_ss[bstrt] = temp_ss merge['SCS(MI)-MP2-F12 SCS-OS'] = pd.concat(merge_os) merge['SCS(MI)-MP2-F12 SCS-SS'] = pd.concat(merge_ss) df_mi = pd.concat(merge) df_mi = df_mi.reorder_levels([1, 0, 2, 3]) df_mi.index.names = ['bstrt', 'psivar', 'meta', 'rxn'] df_mi = df_mi.dropna(how='all') if len(df_mi) > 0: df = df.append(df_mi, verify_integrity=True) if verbose > 0: print('SUCCESS') lvl = 'psivar' pv3 = collections.OrderedDict() pv3['SCS(MI)-MP2 CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': ['SCS(MI)-MP2 SCS-OS', 'SCS(MI)-MP2 SCS-SS', 'MP2 CORRELATION ENERGY', 'MP2 SAME-SPIN CORRELATION ENERGY']} pv3['SCS(MI)-MP2 TOTAL ENERGY'] = {'func': sum, 'args': ['HF TOTAL ENERGY', 'SCS(MI)-MP2 CORRELATION ENERGY']} pv3['SCS(MI)-MP2-F12 CORRELATION ENERGY'] = {'func': spin_component_scaling, 'args': ['SCS(MI)-MP2-F12 SCS-OS', 'SCS(MI)-MP2-F12 SCS-SS', 'MP2-F12 CORRELATION ENERGY', 'MP2-F12 SAME-SPIN CORRELATION ENERGY']} pv3['SCS(MI)-MP2-F12 TOTAL ENERGY'] = {'func': sum, 'args': ['HF-CABS TOTAL ENERGY', 'SCS(MI)-MP2-F12 CORRELATION ENERGY']} for pvar, action in pv3.iteritems(): try: if verbose > 0: print("""building %s %s""" % (pvar, '.' * (50 - len(pvar))), end='') df = append_result_of_func_with_funcargs_to_master_DataFrame_atlevel_with_label( master=df, label=pvar, atlevel=lvl, func=action['func'], funcargs=action['args']) if verbose > 0: print("""SUCCESS""") except KeyError, e: if verbose > 0: print("""FAILED, missing %s""" % (e)) # <<< define simple functions codifying cbs() piecing >>> # TODO move these to be functions in Method or BasisSet # min and max pieces for which basis treatment intent is clearly understood # with the understanding that Method should be defining all those pieces that have uniform basis # desi max_mtd min_bas max_bas #HF/adz 1 1 1 inf (1) #MP2/adz 1 2 1 inf (1) #CC/adz 1 3 1 inf (1) #HF/adtz 1 1 1 2 #MP2/adtz 2 2 1 2 #CC/adtz 2 3 1 2 #CC/atqzadz 3 3 2 3 # stages = min(max_mtd, max_bas) def compute_max_bas(bas): return len(bases[bas].build) def generic_bas(Nstage, bas): return bases[bas].build[Nstage - 1] # 1-indexed stage counting to 0-indexed array storage def compute_max_mtd(stub): if stub in ['HFCABS', 'HF', 'SCF']: return 1 elif 'MP2' in stub and stub not in ['MP25', 'MP2C', 'MP2CF12']: return 2 else: return 3 def generic_mtd(Nstage, stub): if Nstage == 1: return ['%s TOTAL ENERGY' % (stub)] elif Nstage == 2: #return ['%s TOTAL ENERGY' % ('HF-CABS' if 'F12' in stub else 'SCF'), return ['%s TOTAL ENERGY' % ('HF-CABS' if 'F12' in stub else 'HF'), '%s CORRELATION ENERGY' % (stub)] elif Nstage == 3: #return ['%s TOTAL ENERGY' % ('HF-CABS' if 'F12' in stub else 'SCF'), '%s CORRELATION ENERGY' % (stub), '%s CC CORRECTION ENERGY' % (stub)] #return ['%s TOTAL ENERGY' % ('HF-CABS' if 'F12' in stub else 'SCF'), return ['%s TOTAL ENERGY' % ('HF-CABS' if 'F12' in stub else 'HF'), '%s CORRELATION ENERGY' % ('MP2-F12' if 'F12' in stub else 'MP2'), #'%s TOTAL ENERGY' % ('HF'), #'%s CORRELATION ENERGY' % ('MP2'), '%s CC CORRECTION ENERGY' % (stub)] def build_from_lists(mtdlist, baslist, optlist=None): if optlist is None: optlist = [''] * len(mtdlist) #return ie2(sum([df.loc[bas].loc[pcs].loc[opt] for pcs, bas, opt in zip(mtdlist, baslist, optlist)])) # TODO handle mode return reactionate('CP', sum([df.loc[bas].loc[pcs].loc[opt] for pcs, bas, opt in zip(mtdlist, baslist, optlist)])) def build(method, option, cpmode, basis): #print method, option, cpmode, basis Nstage = min(compute_max_mtd(method), compute_max_bas(basis)) baslist = generic_bas(Nstage, basis) mtdlist = generic_mtd(Nstage, methods[method].fullname.upper()) optlist = ['-'.join([opt for opt in option.split('-') if (opt == '' or pcs in optclue2psivar[opt])]) for pcs in mtdlist] # not sure about how this will hold up to multistage # purpose is to prevent duplicate IE with irrelevant option labels surviving for alw in option.split('-'): found = False for piece in optlist: if alw in piece: found = True if not found: return 'Overly' #func = {'CP': ie2, 'unCP': ie_uncp2, 'ave': ie_ave, 'default': default}[cpmode] if baslist is None: raise KeyError # TODO a more specific message that mtd/bas don't mix wouldn't hurt #print '\n <<<', methods[method].fullname, '/', bases[basis].fullname, '>>>' #print 'stages:', 'M:', compute_max_mtd(method), 'B:', compute_max_bas(basis), 'U:', Nstage if method in [] and basis in []: #if method in ['MP2'] and basis in ['aqz']: #if method in ['MP2C', 'MP2CF12'] and basis in ['atqzadz', 'adz', 'adtz']: #if method in ['B3LYPD3'] and basis in ['def2qzvp']: #if method in ['B3LYPD3M', 'B3LYPD3MBJ'] and basis in ['atz']: #if method in ['CCSDT'] and basis in ['a56za5z']: #if method in ['PBEH3C']: #if method in ['B2PLYPD3M']: #if method: print('\n', method, option, cpmode, basis) print('pcss:', mtdlist) print('bass:', baslist) print('opts:', optlist) for pcs, bas, opt in zip(mtdlist, baslist, optlist): print(df.loc[bas].loc[pcs].loc[opt].loc['UBQ-ala28-asp32']) #'HBC1-FaOOFaNN-4.2']) # ACONF-15'] #'NBC1-BzBz_S-5.0'] #'S22-2'] #'A24-1'] #'BBI-150LYS-158LEU-2'] #'S22-2'] acting_cpmode = 'default' if cpmode == 'unCP' else cpmode return reactionate(acting_cpmode, sum([df.loc[bas].loc[pcs].loc[opt] for pcs, bas, opt in zip(mtdlist, baslist, optlist)])) # <<< assemble all model chemistries into columns of new DataFrame >>> rxns = ['%s-%s' % (dbse, rxn) for rxn in dbobj.dbdict[dbobj.dbse].hrxn.keys()] mine = pd.DataFrame({}, index=rxns) mine.index.names = ['rxn'] df.sortlevel(inplace=True) if verbose > 0: print('SORTEDNESS OF DF:', df.index.lexsort_depth) if project == 'dft': mtds = ['B3LYP', 'B3LYPD2', 'B3LYPD3', 'B2PLYP', 'B2PLYPD2', 'B2PLYPD3', 'B970', 'BP86', 'B97', 'WB97XD', 'M052X', 'M062X', 'PBE', 'PBE0', 'XYG3', 'B970D2', 'BP86D2', 'BP86D3', 'M052XD3', 'M062XD3', 'PBED2', 'PBED3', 'PBE0D2', 'PBE0D3', 'B97D2', 'B97D3', 'B3LYPXDM'] bass = ['adz', 'atz', 'dadz', 'datz', 'dz', 'tz', 'hadz', 'hatz', '6311pg_3df_2p_', '6311ppg_3df_2p_'] opts = [''] cpmd = ['unCP', 'CP'] elif project == 'parenq': mtds = ['HF', 'CCSDT', 'CCSDTQ', 'CCSD', 'CCSDFULLT', 'MP2'] bass = ['adz', 'atz', 'hadz', 'jadz', 'atz', 'adtz', 'aq5z'] opts = ['', 'full', 'fno1e5', 'fno1e4', 'fno5e5', 'fno1e6', 'fno1e4-mrcc', 'fno1e3'] cpmd = ['CP'] elif project == 'f12dilabio': mtds = [mtd for mtd in methods if ((mtd == 'HFCABS' or 'F12' in mtd) and ('SC' not in mtd and 'MP2C' not in mtd and 'DWMP2' not in mtd))] bass = ['adz', 'atz', 'aqz', 'a5z', 'dzf12', 'tzf12', 'qzf12', '5zf12', 'adtz', 'atqz', 'aq5z', 'dtzf12', 'tqzf12', 'hill1_adtz', 'hill1_atqz', 'hill1_aq5z', 'hill1_dtzf12', 'hill1_tqzf12'] opts = [''] cpmd = ['CP'] elif project == 'dilabio': mtds = ['HF', 'MP2', 'CCSD', 'CCSDT'] bass = ['adz', 'atz', 'aqz', 'a5z', 'a6z', 'adtz', 'atqz', 'aq5z', 'a56z', 'atqzadz', 'atqzatz', 'aq5zadz', 'aq5zatz'] opts = [''] cpmd = ['CP', 'unCP', 'ave'] elif project == 'dhdft': mtds = ['B3LYP', 'B3LYPD3', 'B2PLYP', 'B2PLYPD3', 'B97D3', 'M052X', 'M062X', 'DSDPBEP86', 'VV10', 'LCVV10', 'DSDPBEP86', 'PBE', 'PBED3', 'PBE0', 'PBE0D3', 'M08HX', 'M08SO', 'M11', 'M11L', 'PBE02', 'DLDFD', 'WB97X2', 'WB97XD', 'M062XD3'] bass = ['adz', 'atz'] opts = ['', 'nfc'] cpmd = ['CP', 'unCP'] elif project == 'fcnfc': mtds = ['B2PLYP', 'B2PLYPD3', 'B2PLYPD3BJ', 'B97', 'B97D3', 'B97D3BJ', 'B3LYP', 'B3LYPD3', 'B3LYPD3BJ'] bass = ['adz', 'atz', 'def2qzvp'] opts = ['dfhf-dfmp-fc', 'dfhf-dfmp-nfc', 'dfhf'] cpmd = ['CP', 'unCP'] elif project == 'dhdft2': mtds = ['DSDPBEP86', 'DSDPBEP86D2', 'DSDPBEP86D3BJ'] bass = ['adz', 'atz'] opts = ['', 'nfc'] cpmd = ['CP', 'unCP'] elif project == 'pt2': mtds = ['HF', 'MP2', 'SCSMP2', 'SCSNMP2', 'SCSMIMP2', 'DWMP2', 'MP2C', 'MP25', 'MP3', 'HFCABS', 'MP2F12', 'SCSMP2F12', 'SCSNMP2F12', 'SCSMIMP2F12', 'DWMP2F12', 'MP2CF12', 'CCSDAF12', 'SCSCCSDAF12', 'SCMICCSDAF12', 'CCSDTAF12', 'CCSDTSAF12', 'CCSDTNSAF12', 'CCSDBF12', 'SCSCCSDBF12', 'SCMICCSDBF12', 'CCSDTBF12', 'CCSDTSBF12', 'CCSDTNSBF12', 'DWCCSDTF12', 'DWCCSDTSF12', 'DWCCSDTNSF12', 'SAPT0', 'SAPT0S', 'SAPTSCS', 'SAPTDFT', 'SAPT2', 'SAPT2P', 'SAPT2PC', 'SAPT2PM', 'SAPT2PCM', 'SAPT3', 'SAPT3C', 'SAPT3M', 'SAPT3CM', 'SAPT3F', 'SAPT3FC', 'SAPT3FM', 'SAPT3FCM', ] bass = ['adz', 'atz', 'aqz', 'a5z', 'adtz', 'atqz', 'aq5z', 'atzadz', 'adtzadz', 'atqzadz', 'atqzatz', 'atzadtz', 'atqzadtz', 'dz', 'jadz', 'hadz', 'tz', 'matz', 'jatz', 'hatz', 'qz', 'aaqz', 'maqz', 'jaqz', 'haqz', 'dtz', 'jadtz', 'hadtz', 'tqz', 'matqz', 'jatqz', 'hatqz', 'atzdz', 'adtzdz', 'atqzdz', 'atqztz', 'atzdtz', 'atqzdtz', 'atzjadz', 'adtzjadz', 'atqzjadz', 'atqzjatz', 'atzjadtz', 'atqzjadtz', 'atzhadz', 'adtzhadz', 'atqzhadz', 'atqzhatz', 'atzhadtz', 'atqzhadtz', 'dzf12', 'tzf12'] opts = ['', 'dfhf', 'dfmp', 'dfhf-dfmp'] cpmd = ['CP', 'SA'] elif project in ['saptone', 'saptmisc', 'sapta0a1conv']: mtds = ['SAPT0', 'SAPT0S', 'SAPTSCS', 'SAPTDFT', 'SAPT2', 'SAPT2P', 'SAPT2PC', 'SAPT2PM', 'SAPT2PCM', 'SAPT3', 'SAPT3C', 'SAPT3M', 'SAPT3CM', 'SAPT3F', 'SAPT3FC', 'SAPT3FM', 'SAPT3FCM'] bass = ['adz', 'atz', 'aqz', 'a5z', 'dz', 'jadz', 'hadz', 'tz', 'matz', 'jatz', 'hatz', 'qz', 'aaqz', 'maqz', 'jaqz', 'haqz'] opts = ['', 'dfmp'] cpmd = ['SA'] elif project == 'pt2misc': mtds = ['HF', 'MP2', 'SCSMP2', 'SCSNMP2', 'SCSMIMP2', 'DWMP2', 'HFCABS', 'MP2F12', 'SCSMP2F12', 'SCSNMP2F12', 'SCSMIMP2F12', 'DWMP2F12'] bass = ['adz', 'atz', 'aqz', 'adtz', 'atqz', 'qz'] opts = ['', 'dfhf', 'dfhf-dfmp'] cpmd = ['CP'] elif project == 'dftmisc': mtds = ['PBEH3C'] bass = ['def2msvp'] opts = ['', 'dfhf'] cpmd = ['unCP'] elif project == 'ccmisc': mtds = ['MP2C', 'MP25', 'MP3', 'MP2CF12', 'CCSDAF12', 'SCSCCSDAF12', 'SCMICCSDAF12', 'CCSDTAF12', 'CCSDTNSAF12', 'CCSDBF12', 'SCSCCSDBF12', 'SCMICCSDBF12', 'CCSDTBF12', 'DWCCSDTF12'] bass = ['adz', 'atz', 'adtz', 'atqzadz', 'aq5zadz', 'atqzatz', 'aq5zatz'] opts = ['', 'dfhf', 'dfhf-dfmp'] cpmd = ['CP', 'SA'] elif project == 'aep': mtds = ['SCSMICCSD'] bass = ['adz', 'atz', 'adtz', 'atqzadz', 'atqzatz'] opts = ['', 'dfhf-dfmp'] cpmd = ['CP'] elif project == 'sflow': mtds = ['MP2'] bass = ['aqz'] opts = ['dfhf-dfmp-dsrgs0p1', 'dfhf-dfmp-dsrgs0p5', 'dfhf-dfmp-dsrgs1p0'] cpmd = ['CP'] elif project in ['dfit', 'bfdbdft']: mtds = ['B3LYP', 'B3LYPD2', 'B3LYPD3', 'B3LYPD3BJ', 'B97', 'B97D2', 'B97D3', 'B97D3BJ', # 'B970', 'B970D2', 'B970D3', 'B970D3BJ', 'BLYP', 'BLYPD2', 'BLYPD3', 'BLYPD3BJ', 'BP86', 'BP86D2', 'BP86D3', 'BP86D3BJ', 'PBE', 'PBED2', 'PBED3', 'PBED3BJ', 'PBE0', 'PBE0D2', 'PBE0D3', 'PBE0D3BJ', 'WPBE', 'WPBED3', 'WPBED3BJ', 'B2PLYP', 'B2PLYPD2', 'B2PLYPD3', 'B2PLYPD3BJ', 'WB97XD', 'M052X', 'WB97XV', 'WB97MV'] bass = ['def2qzvp', 'adz', 'atz'] opts = ['', 'dfhf', 'dfhf-dfmp'] # why B2PLYP with no or dfhf label; why B3LYP w dfhf-dfmp label? cpmd = ['CP', 'unCP'] elif project in ['dfitm', 'bfdbdftm']: mtds = ['B3LYPD3M', 'B3LYPD3MBJ', 'B97D3M', 'B97D3MBJ', 'BLYPD3M', 'BLYPD3MBJ', 'BP86D3M', 'BP86D3MBJ', 'PBED3M', 'PBED3MBJ', 'PBE0D3M', 'PBE0D3MBJ', 'WPBED3M', 'WPBED3MBJ', 'B2PLYPD3M', 'B2PLYPD3MBJ'] bass = ['def2qzvp', 'adz', 'atz'] opts = ['', 'dfhf', 'dfhf-dfmp'] # why B2PLYP with no or dfhf label; why B3LYP w dfhf-dfmp label? cpmd = ['CP', 'unCP'] elif project == 'nbcref': mtds = ['CCSDT'] #bass = ['atqzhatz', 'atqzatz', 'atqzadz', 'atqz'] # for NBC10ext bass = ['aq5zhatz', 'aq5zatz', 'atqz'] # for NBC10B opts = ['', 'dfhf-dfmp'] cpmd = ['CP'] elif project == 'curveref': mtds = ['CCSDT', 'DWCCSDTF12', 'SCMICCSDAF12', 'CCSDTAF12', 'CCSDTBF12', 'CCSDTCF12'] bass = ['adz', 'atz', 'aqz', 'a5z', 'adtz', 'atqz', 'aq5z'] opts = [''] cpmd = ['CP'] elif project == 'silver': mtds = ['DWCCSDTF12', 'CCSDTAF12', 'CCSDTBF12', 'CCSDTABAVGF12', 'MP2', 'MP2F12', 'CCSDTNSAF12'] bass = ['adz', 'aq5zadz', 'aq5z', 'atqzadz', 'atqz', 'atz', 'atqzatz', 'aq5zatz'] opts = ['', 'dfhf-dfmp'] cpmd = ['CP', 'unCP'] # CP for IE, unCP for generic rxns for cpm in cpmd: for mtd in mtds: for bas in bass: for opt in opts: mc = '-'.join([mtd, cpm, bas]) if opt == '' else '-'.join([mtd, opt, cpm, bas]) try: if verbose > 2: print("""<<< Reagents for {} >>>""".format(mc)) tmp = build(mtd, opt, cpm, bas) if verbose > 1: print("""Built model chemistry %s""" % (mc)) except KeyError, e: if verbose > 1: print("""Error building rxn mc: empty '%s' b/c no %s""" % (mc, e)) else: if isinstance(tmp, basestring) and tmp == 'Overly': if verbose > 1: print("""Overly optioned rxn mc: {} for {}""".format(opt, mc)) elif tmp.empty or tmp.dropna(how='all').empty: # invalid for canopy python if verbose > 1: print("""Empty rxn mc: empty '%s'""" % (mc)) else: mine[mc] = tmp def threadtheframe(modelchem, xlimit=4.0): dbdat = [] for rxn in dbobj.hrxn.keys(): data = [] for mc in modelchem: value = h2kc * mine[mc]['%s-%s' % (dbse, rxn)] data.append(None if pd.isnull(value) else value) dbdat.append({'sys': str(rxn), 'color': dbobj.dbdict[dbobj.dbse].hrxn[rxn].color, 'data': data}) qcdb.mpl.thread(dbdat, modelchem, color='sapt', xlimit=xlimit) # commented 5 Jan 2016, below is fine but lacks bypass if pieces missing if False and project == 'f12dilabio': mine['CCSDTNSBF12-CP-hill2_adtz'] = build_from_lists(['HF-CABS TOTAL ENERGY', 'CCSD-F12B CORRELATION ENERGY', '(T)-F12AB CORRECTION ENERGY'], ['atz', 'hillcc_adtz', 'hillt_adtz']) # commented 27 April 2015, missing MP2-full if False and project == 'parenq': mine['DELTQ-full-CP-hadz'] = mine['CCSDTQ-full-CP-hadz'] - mine['CCSDT-full-CP-hadz'] mine['DELTQ-full-CP-jadz'] = mine['CCSDTQ-full-CP-jadz'] - mine['CCSDT-full-CP-jadz'] mine['DELTQ-full-CP-adz'] = mine['CCSDTQ-full-CP-adz'] - mine['CCSDT-full-CP-adz'] mine['DELTQ-full-CP-atz'] = mine['CCSDTQ-full-CP-atz'] - mine['CCSDT-full-CP-atz'] mine['DELTQ-full-CP-adtz'] = mine['CCSDTQ-full-CP-adtz'] - mine['CCSDT-full-CP-adtz'] mine['DELTQ-fno1e4-CP-adz'] = mine['CCSDTQ-fno1e4-CP-adz'] - mine['CCSDT-fno1e4-CP-adz'] mine['DELTQ-fno1e4-CP-atz'] = mine['CCSDTQ-fno1e4-CP-atz'] - mine['CCSDT-fno1e4-CP-atz'] mine['DELTQ-fno1e4-CP-adtz'] = mine['CCSDTQ-fno1e4-CP-adtz'] - mine['CCSDT-fno1e4-CP-adtz'] mine['DELTQ-fno1e5-CP-adz'] = mine['CCSDTQ-fno1e5-CP-adz'] - mine['CCSDT-fno1e5-CP-adz'] mine['DELTQ-fno1e5-CP-atz'] = mine['CCSDTQ-fno1e5-CP-atz'] - mine['CCSDT-fno1e5-CP-atz'] mine['DELTQ-fno1e5-CP-adtz'] = mine['CCSDTQ-fno1e5-CP-adtz'] - mine['CCSDT-fno1e5-CP-adtz'] #mine['DELTQ-fno1e3-CP-adz'] = mine['CCSDTQ-fno1e3-CP-adz'] - mine['CCSDT-fno1e3-CP-adz'] mine['DELTQ-fno1e6-CP-adz'] = mine['CCSDTQ-fno1e6-CP-adz'] - mine['CCSDT-fno1e6-CP-adz'] mine['DELTQ-fno5e5-CP-adz'] = mine['CCSDTQ-fno5e5-CP-adz'] - mine['CCSDT-fno5e5-CP-adz'] mine['DEL2T-full-CP-hadz'] = mine['CCSDT-full-CP-hadz'] - mine['MP2-full-CP-hadz'] mine['DEL2T-full-CP-jadz'] = mine['CCSDT-full-CP-jadz'] - mine['MP2-full-CP-jadz'] mine['DEL2T-full-CP-adz'] = mine['CCSDT-full-CP-adz'] - mine['MP2-full-CP-adz'] mine['DEL2T-full-CP-atz'] = mine['CCSDT-full-CP-atz'] - mine['MP2-full-CP-atz'] mine['DEL2T-full-CP-adtz'] = mine['CCSDT-full-CP-adtz'] - mine['MP2-full-CP-adtz'] mine['DEL2T-fno1e4-CP-adz'] = mine['CCSDT-fno1e4-CP-adz'] - mine['MP2-fno1e4-CP-adz'] mine['DEL2T-fno1e4-CP-atz'] = mine['CCSDT-fno1e4-CP-atz'] - mine['MP2-fno1e4-CP-atz'] mine['DEL2T-fno1e4-CP-adtz'] = mine['CCSDT-fno1e4-CP-adtz'] - mine['MP2-fno1e4-CP-adtz'] mine['DEL2T-fno1e5-CP-adz'] = mine['CCSDT-fno1e5-CP-adz'] - mine['MP2-fno1e5-CP-adz'] mine['DEL2T-fno1e5-CP-atz'] = mine['CCSDT-fno1e5-CP-atz'] - mine['MP2-fno1e5-CP-atz'] mine['DEL2T-fno1e5-CP-adtz'] = mine['CCSDT-fno1e5-CP-adtz'] - mine['MP2-fno1e5-CP-adtz'] #mine['DEL2T-fno1e3-CP-adz'] = mine['CCSDT-fno1e3-CP-adz'] - mine['MP2-fno1e3-CP-adz'] mine['DEL2T-fno1e6-CP-adz'] = mine['CCSDT-fno1e6-CP-adz'] - mine['MP2-fno1e6-CP-adz'] mine['DEL2T-fno5e5-CP-adz'] = mine['CCSDT-fno5e5-CP-adz'] - mine['MP2-fno5e5-CP-adz'] if False: #if project == 'parenq': # TODO these aren't actually interaction energies! mine['CCSDTQ-corl-CP-adz'] = build_from_lists(['CCSDT(Q) CORRELATION ENERGY'], ['adz'], ['fno1e4']) mine['CCSDT-corl-CP-adz'] = build_from_lists(['CCSD(T) CORRELATION ENERGY'], ['adz'], ['fno1e4']) mine['CCSD-corl-CP-adz'] = build_from_lists(['CCSD CORRELATION ENERGY'], ['adz'], ['fno1e4-mrcc']) mine['MP2-corl-CP-adz'] = build_from_lists(['MP2 CORRELATION ENERGY'], ['adz']) mine['CCSDTQ-corl-CP-atz'] = build_from_lists(['CCSDT(Q) CORRELATION ENERGY'], ['atz'], ['fno1e4']) mine['CCSDT-corl-CP-atz'] = build_from_lists(['CCSD(T) CORRELATION ENERGY'], ['atz'], ['fno1e4']) mine['CCSD-corl-CP-atz'] = build_from_lists(['CCSD CORRELATION ENERGY'], ['atz'], ['fno1e4']) mine['MP2-corl-CP-atz'] = build_from_lists(['MP2 CORRELATION ENERGY'], ['atz']) mine['convdel-adz'] = mine['CCSDT-corl-CP-adz'] - mine['MP2-corl-CP-adz'] mine['altdel-adz'] = mine['CCSDTQ-corl-CP-adz'] - mine['CCSD-corl-CP-adz'] minelist = ['convdel-adz', 'altdel-adz', 'CCSDTQ-corl-CP-adz', 'CCSDT-corl-CP-adz', 'CCSD-corl-CP-adz', 'MP2-corl-CP-adz'] mine['convdel-atz'] = mine['CCSDT-corl-CP-atz'] - mine['MP2-corl-CP-atz'] mine['altdel-atz'] = mine['CCSDTQ-corl-CP-atz'] - mine['CCSD-corl-CP-atz'] minelistatz = ['convdel-atz', 'altdel-atz', 'CCSDTQ-corl-CP-atz', 'CCSDT-corl-CP-atz', 'CCSD-corl-CP-atz', 'MP2-corl-CP-atz'] import qcdb.mpl import matplotlib.pyplot as plt #threadtheframe(minelist) #threadtheframe(minelistatz) #threadtheframe(['CCSDTQ-fno1e4-CP-adz', 'CCSDTQ-fno1e4-CP-atz', 'CCSDTQ-fno1e4-CP-adtz', 'CCSDTQ-fno1e5-CP-adtz', 'CCSDTQ-fno1e5-CP-atz', 'CCSDTQ-fno1e5-CP-adz', 'CCSDT-CP-aq5z'], xlimit=7.0) if verbose > 1: print('Reaction Energies', mine.columns) print('MINE top\n', mine.head(5), '\n', mine.tail(5)) # <<< test cases >>> from qcdb.pandas_test import test_pandas test_pandas(h2kc, project, mine) # <<< write qcdb data loader >>> with open('%s/%s_%s.py' % (homewrite, dbse, project), 'w') as handle: print('Writing to %s/%s_%s.py ...' % (homewrite, dbse, project)) handle.write('\ndef load_%s(dbinstance):\n\n' % (project)) for mc in mine.columns: lmc = mc.split('-') # TODO could be done better method = lmc[0] bsse = '_'.join(lmc[1:-1]) basis = lmc[-1] for rxn in dbobj.dbdict[dbobj.dbse].hrxn.keys(): value = h2kc * mine[mc]['%s-%s' % (dbse, rxn)] if pd.isnull(value): if rxn == 2: print('dropping', mc) pass else: handle.write(""" dbinstance.add_ReactionDatum(citation='%s', dbse='%s', rxn=%s, method='%s', mode='%s', basis='%s', value=%.4f)\n""" % (project, dbse, repr(rxn), method, bsse, basis, value)) # <<< write hdf5 >>> with pd.get_store('%s/%s_%s.h5' % (homewrite, dbse, project)) as handle: handle['pdie'] = mine * h2kc print('Writing to %s/%s_%s.h5 ...' % (homewrite, dbse, project)) # <<< SAPT components interlude >>> try: qlvl = 'SAPT2+3(CCD)' qbas = 'atz' code = 'SAPT3FC-SA-atz' df.xs('{} TOTAL ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt') except KeyError, e: try: qlvl = 'SAPT2+' qbas = 'adz' code = 'SAPT2P-SA-adz' df.xs('{} TOTAL ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt') except KeyError, e: try: qlvl = 'SSAPT0' qbas = 'jadz' code = 'SAPT0S-SA-jadz' df.xs('{} TOTAL ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt') except KeyError, e: code = None if code: with open('%s/%s_%s.py' % (homewrite, 'sapt', dbse), 'w') as handle: print('Writing to %s/%s_%s.py ...' % (homewrite, 'sapt', dbse)) handle.write("""DATA = {}\n\n""") handle.write("""DATA['SAPT MODELCHEM'] = '%s'\n""" % (code)) rxns = ['%s-%s' % (dbse, rxn) for rxn in dbobj.dbdict[dbobj.dbse].hrxn.keys()] for bit in ['ELST', 'EXCH', 'INDC', 'DISP']: dfbit = h2kc * df.xs('{} {} ENERGY'.format(qlvl, bit), level='psivar').xs(qbas, level='bstrt') pbit = 'IND' if bit == 'INDC' else bit handle.write("""DATA['SAPT %s ENERGY'] = {}\n""" % (pbit)) for rxn in rxns: handle.write("""DATA['SAPT %s ENERGY']['%s'] = %10.4f\n""" % (pbit, rxn, dfbit.xs(rxn, level='rxn')['SA']['Rgt0'])) # print '{}/{} for {} in {}: RXN, TOT, ELST, EXCH, IND, DISP'.format(qlvl, qbas, len(rxns), dbse) # for rxn in rxns: # qtotl = h2kc * df.xs('{} TOTAL ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt').xs(rxn, level='rxn')['SA']['Rgt0'] # qelst = h2kc * df.xs('{} ELST ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt').xs(rxn, level='rxn')['SA']['Rgt0'] # qexch = h2kc * df.xs('{} EXCH ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt').xs(rxn, level='rxn')['SA']['Rgt0'] # qindc = h2kc * df.xs('{} INDC ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt').xs(rxn, level='rxn')['SA']['Rgt0'] # qdisp = h2kc * df.xs('{} DISP ENERGY'.format(qlvl), level='psivar').xs(qbas, level='bstrt').xs(rxn, level='rxn')['SA']['Rgt0'] # print """%-23s %8.4f %8.4f %8.4f %8.4f %8.4f""" % (rxn, qtotl, qelst, qexch, qindc, qdisp) # <<< collecting section >>> #print 'indexval before', sorted(set([tup[1] for tup in df.index.values])) # TODO write test case missing checker into the build loop # if basis treatment isn't designed for SCF, i.e. adtz where Helgaker xtpl is meant for corl, should first item of build be None? # form indices for mine from master df #rxns = [] #[rxns.append(tup[2]) for tup in df.index.values if not rxns.count(tup[2])] #print 'scf', df.loc['tzf12'].loc['HF-CABS TOTAL ENERGY'] #print 'cc', df.loc['HillCC_dtzf12'].loc['CCSD-F12B CORRELATION ENERGY'] #print '(t)', df.loc['HillT_dtzf12'].loc['(T)-F12AB CORRECTION ENERGY'] #print 'search', df.xs('(T)-F12AB CORRECTION ENERGY', level='psivar') #print mine['CCSDTNSBF12-CP-Hill2_dtzf12'] #print mine.columns #print 'TTTTT' #subject = df.xs('DW-MP2-F12 CORRELATION ENERGY', level='psivar') ##subject.xs('adz', level='bstrt').xs('', level='meta')['CP'][:] = np.nan #print subject #print subject.head(5) #print subject.tail(5) #print 'len', len(subject), categories(subject, 0), categories(subject, 1) #subject = subject.dropna(axis=0, how='all') #print 'TTfrop' #print subject #print subject.head(5) #print subject.tail(5) #print 'len', len(subject), categories(subject, 0), categories(subject, 1) #mlist = ['HF-CABS TOTAL ENERGY', #'SCS(MI)-MP2-F12 SCS-OS', 'SCS(MI)-MP2-F12 SCS-SS', 'MP2-F12 CORRELATION ENERGY', 'MP2-F12 SAME-SPIN CORRELATION ENERGY', # 'SCS(MI)-MP2-F12 CORRELATION ENERGY', 'SCS(MI)-MP2-F12 TOTAL ENERGY'] #for ml in mlist: # mdf = df.xs(ml, level='psivar').xs('atz', level='bstrt') # print ml, '\n', categories(mdf, 0) # print mdf # print mdf.head(50)
loriab/qcdb
bin/reap-DB.py
Python
lgpl-3.0
90,226
[ "CPMD" ]
55097f5097b716aaca4de31b09d0ec0cdf508f2b6c20b587c894bcd5584b3b74
from __future__ import absolute_import import shutil from subprocess import call import numpy import pytest from click.testing import CliRunner from pathlib import Path import datacube.scripts.cli_app from datacube.compat import string_types import imp PROJECT_ROOT = Path(__file__).parents[1] CONFIG_SAMPLES = PROJECT_ROOT / 'docs/config_samples/' LS5_DATASET_TYPES = CONFIG_SAMPLES / 'dataset_types/ls5_scenes.yaml' TEST_DATA = PROJECT_ROOT / 'tests' / 'data' / 'lbg' INGESTER_CONFIGS = CONFIG_SAMPLES / 'ingester' LS5_NBAR_ALBERS = 'ls5_nbar_albers.yaml' LS5_PQ_ALBERS = 'ls5_pq_albers.yaml' GA_LS_PREPARE_SCRIPT = PROJECT_ROOT / 'utils/galsprepare.py' galsprepare = imp.load_source('module.name', str(GA_LS_PREPARE_SCRIPT)) LBG_NBAR = 'LS5_TM_NBAR_P54_GANBAR01-002_090_084_19920323' LBG_PQ = 'LS5_TM_PQ_P55_GAPQ01-002_090_084_19920323' ALBERS_ELEMENT_SIZE = 25 LBG_CELL_X = 15 LBG_CELL_Y = -40 LBG_CELL = (LBG_CELL_X, LBG_CELL_Y) @pytest.fixture() def testdata_dir(tmpdir): datadir = Path(str(tmpdir), 'data') datadir.mkdir() shutil.copytree(str(TEST_DATA), str(tmpdir / 'lbg')) copy_and_update_ingestion_configs(tmpdir, tmpdir, (INGESTER_CONFIGS / file for file in (LS5_NBAR_ALBERS, LS5_PQ_ALBERS))) return tmpdir def copy_and_update_ingestion_configs(destination, output_dir, configs): for ingestion_config in configs: with ingestion_config.open() as input: output_file = destination / ingestion_config.name with output_file.open(mode='w') as output: for line in input: if 'location: ' in line: line = 'location: ' + str(output_dir) + '\n' output.write(line) ignore_me = pytest.mark.xfail(True, reason="get_data/get_description still to be fixed in Unification") @pytest.mark.usefixtures('default_metadata_type') def test_end_to_end(global_integration_cli_args, index, testdata_dir): """ Loads two dataset configurations, then ingests a sample Landsat 5 scene One dataset configuration specifies Australian Albers Equal Area Projection, the other is simply latitude/longitude. The input dataset should be recorded in the index, and two sets of netcdf storage units should be created on disk and recorded in the index. """ lbg_nbar = testdata_dir / 'lbg' / LBG_NBAR lbg_pq = testdata_dir / 'lbg' / LBG_PQ ls5_nbar_albers_ingest_config = testdata_dir / LS5_NBAR_ALBERS ls5_pq_albers_ingest_config = testdata_dir / LS5_PQ_ALBERS # Run galsprepare.py on the NBAR and PQ scenes run_click_command(galsprepare.main, [str(lbg_nbar)]) # Add the LS5 Dataset Types run_click_command(datacube.scripts.cli_app.cli, global_integration_cli_args + ['-v', 'product', 'add', str(LS5_DATASET_TYPES)]) # Index the Datasets run_click_command(datacube.scripts.cli_app.cli, global_integration_cli_args + ['-v', 'dataset', 'add', '--auto-match', str(lbg_nbar), str(lbg_pq)]) # Ingest NBAR run_click_command(datacube.scripts.cli_app.cli, global_integration_cli_args + ['-v', 'ingest', '-c', str(ls5_nbar_albers_ingest_config)]) # Ingest PQ run_click_command(datacube.scripts.cli_app.cli, global_integration_cli_args + ['-v', 'ingest', '-c', str(ls5_pq_albers_ingest_config)]) check_open_with_api(index) check_open_with_dc(index) check_open_with_grid_workflow(index) check_analytics_list_searchables(index) check_get_descriptor(index) check_get_data(index) check_get_data_subset(index) check_get_descriptor_data(index) check_get_descriptor_data_storage_type(index) check_analytics_create_array(index) check_analytics_ndvi_mask_median_expression(index) check_analytics_ndvi_mask_median_expression_storage_type(index) check_analytics_pixel_drill(index) def run_click_command(command, args): result = CliRunner().invoke( command, args=args, catch_exceptions=False ) print(result.output) assert not result.exception assert result.exit_code == 0 def check_open_with_api(index): from datacube.api import API api = API(index=index) # fields = api.list_fields() # assert 'product' in fields descriptor = api.get_descriptor() assert 'ls5_nbar_albers' in descriptor groups = descriptor['ls5_nbar_albers']['groups'] query = { 'variables': ['blue'], 'dimensions': { 'latitude': {'range': (-35, -36)}, 'longitude': {'range': (149, 150)}} } data = api.get_data(query) # , dataset_groups=groups) assert abs(data['element_sizes'][1] - ALBERS_ELEMENT_SIZE) < .0000001 assert abs(data['element_sizes'][2] - ALBERS_ELEMENT_SIZE) < .0000001 def check_open_with_dc(index): from datacube.api.core import Datacube dc = Datacube(index=index) data_array = dc.load(product='ls5_nbar_albers', measurements=['blue'], stack='variable') assert data_array.shape data_array = dc.load(product='ls5_nbar_albers', latitude=(-35, -36), longitude=(149, 150), stack='variable') assert data_array.ndim == 4 assert 'variable' in data_array.dims dataset = dc.load(product='ls5_nbar_albers', measurements=['blue']) assert dataset['blue'].size dataset = dc.load(product='ls5_nbar_albers', latitude=(-35.2, -35.3), longitude=(149.1, 149.2)) assert dataset['blue'].size data_array = dc.load(product='ls5_nbar_albers', latitude=(-35, -36), longitude=(149, 150), measurements=['blue'], group_by='solar_day') products_df = dc.list_products() assert len(products_df) assert len(products_df[products_df['name'].isin(['ls5_nbar_albers'])]) assert len(products_df[products_df['name'].isin(['ls5_pq_albers'])]) assert len(dc.list_measurements()) def check_open_with_grid_workflow(index): type_name = 'ls5_nbar_albers' dt = index.datasets.types.get_by_name(type_name) from datacube.api.grid_workflow import GridWorkflow gw = GridWorkflow(index, dt.grid_spec) cells = gw.list_cells(product=type_name) assert LBG_CELL in cells tile = cells[LBG_CELL] dataset_cell = gw.load(tile, measurements=['blue']) assert dataset_cell['blue'].size dataset_cell = gw.load(tile) assert all(m in dataset_cell for m in ['blue', 'green', 'red', 'nir', 'swir1', 'swir2']) ts = numpy.datetime64('1992-03-23T23:14:25.500000000') tile_key = LBG_CELL + (ts,) tiles = gw.list_tiles(product=type_name) assert tiles assert tile_key in tiles tile = tiles[tile_key] dataset_cell = gw.load(tile, measurements=['blue']) assert dataset_cell['blue'].size dataset_cell = gw.load(tile) assert all(m in dataset_cell for m in ['blue', 'green', 'red', 'nir', 'swir1', 'swir2']) def check_analytics_list_searchables(index): from datacube.analytics.analytics_engine import AnalyticsEngine a = AnalyticsEngine(index=index) result = a.list_searchables() assert len(result) > 0 for storage_type in result: assert len(result[storage_type]['bands']) > 0 assert len(list(result[storage_type]['dimensions'])) > 0 assert result[storage_type]['instrument'] assert result[storage_type]['platform'] assert result[storage_type]['product_type'] assert result[storage_type]['storage_type'] def check_get_descriptor(index): from datetime import datetime from datacube.api import API g = API(index=index) platform = 'LANDSAT_5' product = 'nbar' var1 = 'red' var2 = 'nir' data_request_descriptor = { 'platform': platform, 'product': product, 'variables': (var1, var2), 'dimensions': { 'longitude': { 'range': (149.07, 149.18) }, 'latitude': { 'range': (-35.32, -35.28) }, 'time': { 'range': (datetime(1992, 1, 1), datetime(1992, 12, 31)) } } } d = g.get_descriptor(data_request_descriptor) assert 'storage_units' in list(d.values())[0].keys() assert 'dimensions' in list(d.values())[0].keys() assert 'result_max' in list(d.values())[0].keys() assert 'irregular_indices' in list(d.values())[0].keys() assert 'variables' in list(d.values())[0].keys() assert 'result_min' in list(d.values())[0].keys() assert 'result_shape' in list(d.values())[0].keys() assert isinstance(list(d.values())[0]['storage_units'], dict) assert isinstance(list(d.values())[0]['dimensions'], list) assert isinstance(list(d.values())[0]['result_max'], tuple) assert isinstance(list(d.values())[0]['irregular_indices'], dict) assert isinstance(list(d.values())[0]['result_min'], tuple) assert isinstance(list(d.values())[0]['variables'], dict) assert isinstance(list(d.values())[0]['result_shape'], tuple) assert len(list(d.values())[0]['dimensions']) == \ len(list(d.values())[0]['dimensions']) == \ len(list(d.values())[0]['result_shape']) == \ len(list(d.values())[0]['result_max']) == \ len(list(d.values())[0]['result_min']) for key in list(d.values())[0]['irregular_indices'].keys(): assert key in list(d.values())[0]['dimensions'] assert var1 in list(d.values())[0]['variables'] assert var2 in list(d.values())[0]['variables'] assert 'datatype_name' in list(d.values())[0]['variables'][var1].keys() assert 'nodata_value' in list(d.values())[0]['variables'][var1].keys() assert 'datatype_name' in list(d.values())[0]['variables'][var2].keys() assert 'nodata_value' in list(d.values())[0]['variables'][var2].keys() for su in list(d.values())[0]['storage_units'].values(): assert 'irregular_indices' in su assert 'storage_max' in su assert 'storage_min' in su assert 'storage_path' in su assert 'storage_shape' in su assert isinstance(su['irregular_indices'], dict) assert isinstance(su['storage_max'], tuple) assert isinstance(su['storage_min'], tuple) assert isinstance(su['storage_path'], string_types) assert isinstance(su['storage_shape'], tuple) def check_get_data(index): import numpy as np import xarray as xr from datetime import datetime from datacube.api import API g = API(index=index) platform = 'LANDSAT_5' product = 'nbar' var1 = 'red' var2 = 'nir' data_request_descriptor = { 'platform': platform, 'product': product, 'variables': (var1, var2), 'dimensions': { 'longitude': { 'range': (149.07, 149.18) }, 'latitude': { 'range': (-35.32, -35.28) }, 'time': { 'range': (datetime(1992, 1, 1), datetime(1992, 12, 31)) } } } d = g.get_data(data_request_descriptor) assert 'dimensions' in list(d.keys()) assert 'arrays' in list(d.keys()) assert 'element_sizes' in list(d.keys()) assert 'indices' in list(d.keys()) assert 'coordinate_reference_systems' in list(d.keys()) assert 'size' in list(d.keys()) assert isinstance(d['dimensions'], list) assert isinstance(d['arrays'], dict) assert isinstance(d['element_sizes'], list) assert isinstance(d['indices'], dict) assert isinstance(d['coordinate_reference_systems'], list) assert isinstance(d['size'], tuple) assert len(list(d['dimensions'])) == \ len(list(d['coordinate_reference_systems'])) == \ len(list(d['element_sizes'])) == \ len(list(d['indices'])) == \ len(list(d['size'])) for key in list(d['indices'].keys()): assert key in list(d['dimensions']) assert var1 in list(d['arrays'].keys()) assert var2 in list(d['arrays'].keys()) for crs in d['coordinate_reference_systems']: assert 'reference_system_definition' in crs assert 'reference_system_unit' in crs assert isinstance(crs['reference_system_definition'], string_types) assert isinstance(crs['reference_system_unit'], string_types) for dim in d['indices']: assert isinstance(d['indices'][dim], np.ndarray) assert isinstance(d['arrays'][var1], xr.core.dataarray.DataArray) assert isinstance(d['arrays'][var2], xr.core.dataarray.DataArray) assert d['arrays'][var1].shape == d['size'] assert d['arrays'][var2].shape == d['size'] assert d['arrays'][var1].name == var1 assert d['arrays'][var2].name == var2 assert len(list(d['arrays'][var1].dims)) == len(list(d['dimensions'])) assert len(list(d['arrays'][var2].dims)) == len(list(d['dimensions'])) for dim in list(d['dimensions']): assert dim in list(d['arrays'][var1].dims) assert dim in list(d['arrays'][var2].dims) def check_get_data_subset(index): from datetime import datetime from datacube.api import API g = API(index=index) platform = 'LANDSAT_5' product = 'nbar' var1 = 'red' var2 = 'nir' data_request_descriptor = { 'platform': platform, 'product': product, 'variables': (var1, var2), 'dimensions': { 'x': { 'range': (149.07, 149.18), 'array_range': (5, 10) }, 'y': { 'range': (-35.32, -35.28), 'array_range': (5, 10) }, 'time': { 'range': (datetime(1992, 1, 1), datetime(1992, 12, 31)) } } } d = g.get_data(data_request_descriptor) assert d['arrays'][var1].shape == (1, 5, 5) assert d['arrays'][var2].shape == (1, 5, 5) def check_get_descriptor_data(index): from datetime import datetime from datacube.api import API g = API(index=index) platform = 'LANDSAT_5' product = 'nbar' var1 = 'red' var2 = 'nir' data_request_descriptor = { 'platform': platform, 'product': product, 'variables': (var1, var2), 'dimensions': { 'longitude': { 'range': (149.07, 149.18) }, 'latitude': { 'range': (-35.32, -35.28) }, 'time': { 'range': (datetime(1992, 1, 1), datetime(1992, 12, 31)) } } } d1 = g.get_descriptor(data_request_descriptor) d2 = g.get_data(data_request_descriptor) assert list(d1.values())[0]['result_shape'] == \ d2['size'] == \ d2['arrays'][var1].shape == \ d2['arrays'][var2].shape assert d2['arrays'][var1].shape[0] > 0 assert d2['arrays'][var1].shape[1] > 0 assert d2['arrays'][var1].shape[2] > 0 assert d2['arrays'][var1].shape[0] > 0 assert d2['arrays'][var2].shape[1] > 0 assert d2['arrays'][var2].shape[2] > 0 def check_get_descriptor_data_storage_type(index): from datetime import datetime from datacube.api import API g = API(index=index) storage_type = 'ls5_nbar_albers' var1 = 'red' var2 = 'nir' data_request_descriptor = { 'storage_type': storage_type, 'variables': (var1, var2), 'dimensions': { 'longitude': { 'range': (149.07, 149.18) }, 'latitude': { 'range': (-35.32, -35.28) }, 'time': { 'range': (datetime(1992, 1, 1), datetime(1992, 12, 31)) } } } d1 = g.get_descriptor(data_request_descriptor) d2 = g.get_data(data_request_descriptor) assert list(d1.values())[0]['result_shape'] == \ d2['size'] == \ d2['arrays'][var1].shape == \ d2['arrays'][var2].shape assert d2['arrays'][var1].shape[0] > 0 assert d2['arrays'][var1].shape[1] > 0 assert d2['arrays'][var1].shape[2] > 0 assert d2['arrays'][var1].shape[0] > 0 assert d2['arrays'][var2].shape[1] > 0 assert d2['arrays'][var2].shape[2] > 0 def check_analytics_create_array(index): from datetime import datetime from datacube.analytics.analytics_engine import AnalyticsEngine from datacube.execution.execution_engine import ExecutionEngine a = AnalyticsEngine(index=index) e = ExecutionEngine(index=index) platform = 'LANDSAT_5' product = 'nbar' var1 = 'red' var2 = 'nir' # Lake Burley Griffin dimensions = {'x': {'range': (149.07, 149.18)}, 'y': {'range': (-35.32, -35.28)}, 'time': {'range': (datetime(1992, 1, 1), datetime(1992, 12, 31))}} arrays = a.create_array((platform, product), [var1, var2], dimensions, 'get_data') e.execute_plan(a.plan) assert e.cache['get_data'] def check_analytics_ndvi_mask_median_expression(index): from datetime import datetime from datacube.analytics.analytics_engine import AnalyticsEngine from datacube.execution.execution_engine import ExecutionEngine a = AnalyticsEngine(index=index) e = ExecutionEngine(index=index) platform = 'LANDSAT_5' product = 'nbar' var1 = 'nir' var2 = 'red' pq_product = 'pqa' pq_var = 'pixelquality' # Lake Burley Griffin dimensions = {'x': {'range': (149.07, 149.18)}, 'y': {'range': (-35.32, -35.28)}, 'time': {'range': (datetime(1992, 1, 1), datetime(1992, 12, 31))}} b40 = a.create_array((platform, product), [var1], dimensions, 'b40') b30 = a.create_array((platform, product), [var2], dimensions, 'b30') pq = a.create_array((platform, pq_product), [pq_var], dimensions, 'pq') ndvi = a.apply_expression([b40, b30], '((array1 - array2) / (array1 + array2))', 'ndvi') mask = a.apply_expression([ndvi, pq], 'array1{(array2 == 32767) | (array2 == 16383) | (array2 == 2457)}', 'mask') median_t = a.apply_expression(mask, 'median(array1, 0)', 'medianT') result = e.execute_plan(a.plan) assert e.cache['b40'] assert e.cache['b30'] assert e.cache['pq'] assert e.cache['b40']['array_result'][var1].size > 0 assert e.cache['b30']['array_result'][var2].size > 0 assert e.cache['pq']['array_result'][pq_var].size > 0 assert e.cache['ndvi'] assert e.cache['mask'] assert e.cache['medianT'] def check_analytics_ndvi_mask_median_expression_storage_type(index): from datetime import datetime from datacube.analytics.analytics_engine import AnalyticsEngine from datacube.execution.execution_engine import ExecutionEngine a = AnalyticsEngine(index=index) e = ExecutionEngine(index=index) nbar_storage_type = 'ls5_nbar_albers' var1 = 'nir' var2 = 'red' pq_storage_type = 'ls5_pq_albers' pq_var = 'pixelquality' # Lake Burley Griffin dimensions = {'x': {'range': (149.07, 149.18)}, 'y': {'range': (-35.32, -35.28)}, 'time': {'range': (datetime(1992, 1, 1), datetime(1992, 12, 31))}} b40 = a.create_array(nbar_storage_type, [var1], dimensions, 'b40') b30 = a.create_array(nbar_storage_type, [var2], dimensions, 'b30') pq = a.create_array(pq_storage_type, [pq_var], dimensions, 'pq') ndvi = a.apply_expression([b40, b30], '((array1 - array2) / (array1 + array2))', 'ndvi') mask = a.apply_expression([ndvi, pq], 'array1{(array2 == 32767) | (array2 == 16383) | (array2 == 2457)}', 'mask') median_t = a.apply_expression(mask, 'median(array1, 0)', 'medianT') result = e.execute_plan(a.plan) assert e.cache['b40'] assert e.cache['b30'] assert e.cache['pq'] assert e.cache['b40']['array_result'][var1].size > 0 assert e.cache['b30']['array_result'][var2].size > 0 assert e.cache['pq']['array_result'][pq_var].size > 0 assert e.cache['ndvi'] assert e.cache['mask'] assert e.cache['medianT'] def check_analytics_pixel_drill(index): from datetime import datetime from datacube.analytics.analytics_engine import AnalyticsEngine from datacube.execution.execution_engine import ExecutionEngine a = AnalyticsEngine(index=index) e = ExecutionEngine(index=index) nbar_storage_type = 'ls5_nbar_albers' var1 = 'nir' var2 = 'red' pq_storage_type = 'ls5_pq_albers' pq_var = 'pixelquality' # Lake Burley Griffin dimensions = {'x': {'range': (149.12)}, 'y': {'range': (-35.30)}, 'time': {'range': (datetime(1992, 1, 1), datetime(1992, 12, 31))}} b40 = a.create_array(nbar_storage_type, [var1], dimensions, 'b40') b30 = a.create_array(nbar_storage_type, [var2], dimensions, 'b30') pq = a.create_array(pq_storage_type, [pq_var], dimensions, 'pq') result = e.execute_plan(a.plan) assert e.cache['b40'] assert e.cache['b30'] assert e.cache['pq'] assert e.cache['b40']['array_result'][var1].size > 0 assert e.cache['b30']['array_result'][var2].size > 0 assert e.cache['pq']['array_result'][pq_var].size > 0
ceos-seo/Data_Cube_v2
agdc-v2/integration_tests/test_end_to_end.py
Python
apache-2.0
21,264
[ "NetCDF" ]
5585ce7d8a9e78f8d6fcf7a1238837f8f3f14a26ec65ae49cdd75b1fa9824eb5
# -*- coding: utf-8 -*- # system import os import socket # graphics interface import gtk import pango import cairo import glib try: import Image except: from PIL import Image # calculational help import datetime # self made modules import thumbnailer import checklist import quick from subprocess import * class main: def __init__(self, pf): print "RENDER LISTS WINDOW" self.pf = pf self.win = gtk.Window() self.win.set_title("RENDER LISTS EDITOR") self.win.set_default_size(800,800) self.win.set_position(gtk.WIN_POS_CENTER) self.mainbox = gtk.VBox(False) self.win.add(self.mainbox) self.allowed = True self.RLISTS = [] # LOAD THE FILES self.load() self.mainscroll = 0 ## ICONS LOAD self.plus = gtk.gdk.pixbuf_new_from_file(self.pf+"/py_data/icons/plus.png") self.render = gtk.gdk.pixbuf_new_from_file(self.pf+"/py_data/icons/render.png") self.render_big = gtk.gdk.pixbuf_new_from_file(self.pf+"/py_data/icons/render_big.png") self.delete = gtk.gdk.pixbuf_new_from_file(self.pf+"/py_data/icons/delete.png") # HELPERS self.dW = 0 self.DH = 0 self.mpx = 0 self.mpy = 0 self.mpf = 0 # GRAB TOOL self.tool = "select" # JUST A TOOL WITH NO PARTICULAR THING self.grab = [0,0] # IND of FILE, IND of BLEND self.grabbed = False graph = gtk.DrawingArea() graph.set_size_request(500,700) self.mainbox.pack_start(graph) graph.connect("expose-event", self.framegraph) self.FRAMES = 0 self.win.show_all() #### THIS FUNCTION IS HERE TO LOAD DATA ### def load(self): self.FRAMES = 0 self.RLISTS = [] for FILE in sorted(os.listdir(self.pf+"/py_data/rnd_seq")): #print FILE infile = [] readfile = open(self.pf+"/py_data/rnd_seq/"+FILE, "r") readfile = readfile.read().split("\n") for blend in readfile: if blend.endswith(".blend") and os.path.exists(self.pf+"/"+blend): #print blend infile.append([False, blend]) self.RLISTS.append([FILE, 0, infile]) #NAME OF THE LIST > SCROLL > LIST OF BLENDS IN THIS FILE #### THIS FUNCTION DRAWS THE PIXELS IN THE WINDOW #### def framegraph(self, widget, event): self.FRAMES = self.FRAMES + 1 if self.FRAMES > 9999: self.FRAMES = 0 w, h = widget.window.get_size() xgc = widget.window.new_gc() mx, my, fx = widget.window.get_pointer() # GETTING WHETHER THE WINDOW IS ACTIVE self.winactive = self.win.is_active() ctx = widget.window.cairo_create() ctx.select_font_face("Sawasdee", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) xgc.line_width = 2 # BACKGROUND COLOR xgc.set_rgb_fg_color(gtk.gdk.color_parse("#363636")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, 0, 0, w, h) ## FILL FRAME # BANNER IMAGE FOR INSPIRATION # updating the image if let's say we changed it if self.dW == 0 and self.DH == 0: self.banner = self.pf+"/py_data/banner.png" self.pixbuf = gtk.gdk.pixbuf_new_from_file(self.banner) #lets get how much to scale H scaleimageH = int( float(self.pixbuf.get_height()) / self.pixbuf.get_width() * w) #scaling image to the frame drawpix = self.pixbuf.scale_simple(w, scaleimageH, gtk.gdk.INTERP_NEAREST) #drawing image widget.window.draw_pixbuf(None, drawpix, 0, 0, 0, (h - drawpix.get_height()) / 2, -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) #UI Backdrop ctx3 = widget.window.cairo_create() ctx3.set_source_rgba(0.2,0.2,0.2,0.8) ctx3.rectangle(0, 0, w, h) ctx3.fill() widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.ARROW)) ############################################################################# ############################# DRAW HERE ##################################### ############################################################################# if self.tool == "select": widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.ARROW)) elif self.tool == "grab": widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR)) if self.grabbed: self.tool = "select" self.grabbed = False if "GDK_BUTTON3" in str(fx) and "GDK_BUTTON3" not in str(self.mpf) and self.win.is_active(): self.tool = "select" listY = 200 #SCROLL if self.mpy > my and "GDK_BUTTON2" in str(fx) and "GDK_BUTTON2" in str(self.mpf) and self.win.is_active(): self.mainscroll = self.mainscroll + (my-self.mpy) if self.mpy < my and "GDK_BUTTON2" in str(fx) and "GDK_BUTTON2" in str(self.mpf) and self.win.is_active(): self.mainscroll = self.mainscroll - (self.mpy-my) if self.mainscroll < 0-(len(self.RLISTS)*listY-h): self.mainscroll = 0-(len(self.RLISTS)*listY-h) if self.mainscroll > 0: self.mainscroll = 0 for ind, LIST in enumerate(self.RLISTS): blendX = 100 ### SCROLL ### if my in range((listY*ind)+self.mainscroll+20, (listY*ind)+self.mainscroll+20+listY): if self.mpx > mx and "GDK_BUTTON2" in str(fx) and "GDK_BUTTON2" in str(self.mpf) and self.win.is_active(): self.RLISTS[ind][1] = self.RLISTS[ind][1] + (mx-self.mpx) if self.mpx < mx and "GDK_BUTTON2" in str(fx) and "GDK_BUTTON2" in str(self.mpf) and self.win.is_active(): self.RLISTS[ind][1] = self.RLISTS[ind][1] - (self.mpx-mx) if self.RLISTS[ind][1] < 0-(len(LIST[2])*(blendX+40)-w): self.RLISTS[ind][1] = 0-(len(LIST[2])*(blendX+40)-w) if self.RLISTS[ind][1] > 0: self.RLISTS[ind][1] = 0 # RLIST FRAME xgc.set_rgb_fg_color(gtk.gdk.color_parse("#3f3f3f")) ## CHOSE COLOR #widget.window.draw_rectangle(xgc, True, 0, (listY*ind)+self.mainscroll+20, w, listY-20) ctx3 = widget.window.cairo_create() ctx3.set_source_rgba(0,0,0,0.4) ctx3.rectangle(0, (listY*ind)+self.mainscroll+20, w, listY-20) ctx3.fill() ### DELETE LIST ICON #### # MOUSE OVER if mx in range(w-22, w) and my in range((listY*ind)+self.mainscroll+15, (listY*ind)+self.mainscroll+15+22): xgc.set_rgb_fg_color(gtk.gdk.color_parse("#e47649")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, w-23, (listY*ind)+self.mainscroll+14, 18, 18) if "GDK_BUTTON1" in str(fx) and "GDK_BUTTON1" not in str(self.mpf) and self.win.is_active(): widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) try: os.remove(self.pf+"/py_data/rnd_seq/"+LIST[0]) except: pass self.load() widget.window.draw_pixbuf(None, self.delete, 0, 0, w-22, (listY*ind)+self.mainscroll+15 , -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) ## TITLE ## ctx.set_source_rgb(1,1,1) ctx.set_font_size(15) ctx.move_to( 40, (listY*ind)+self.mainscroll+37) ctx.show_text(LIST[0]) ##### THE INSIDE FILES ## list_scroll = LIST[1] rendrnow = True checkedfirstrendnow = False if len(LIST[2]) == 0 and self.tool == "grab": if my in range((listY*ind)+self.mainscroll+15, (listY*ind)+self.mainscroll+15 + listY): xgc.set_rgb_fg_color(gtk.gdk.color_parse("#4c4c4c")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, 5 , (listY*ind)+self.mainscroll+50-2, blendX+4, blendX+4) # IF RELESED if "GDK_BUTTON1" not in str(fx) and "GDK_BUTTON1" in str(self.mpf) and self.win.is_active(): # moving line is like copying it first # and then deleting the previous one ### MARK ### # marking to delete the line print self.RLISTS[self.grab[0]][2][self.grab[1]][1] delete_filename = self.RLISTS[self.grab[0]][0] delete_file = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "r") delete_file = delete_file.read().split("\n") print "\n----- DELETE FILE ------ (before)\n" for dn, i in enumerate(delete_file): print i if i == self.RLISTS[self.grab[0]][2][self.grab[1]][1]: delete_file[dn] = "!!!DELETE!!!" print "\n----- DELETE FILE ------ (after)\n" for dn, i in enumerate(delete_file): print i if delete_file[-1] == "": delete_file = delete_file[:-1] save = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "w") for i in delete_file: save.write(i+"\n") save.close() ### INSERT #### insert_filename = self.RLISTS[ind][0] save = open(self.pf+"/py_data/rnd_seq/"+insert_filename, "w") save.write(self.RLISTS[self.grab[0]][2][self.grab[1]][1]+"\n") save.close() ### REMOVE #### delete_filename = self.RLISTS[self.grab[0]][0] delete_file = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "r") delete_file = delete_file.read().split("\n") delete_file.remove("!!!DELETE!!!") if delete_file[-1] == "": delete_file = delete_file[:-1] save = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "w") for i in delete_file: save.write(i+"\n") save.close() self.load() self.grabbed =True ## IF THERE ARE BLENDS for n, BLEND in enumerate(LIST[2]): if self.tool == "grab" and self.grab[0] == ind and self.grab[1] == n: xgc.set_rgb_fg_color(gtk.gdk.color_parse("#4c4c4c")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll-2 , (listY*ind)+self.mainscroll+50-2, blendX+4, blendX+4) else: # GETTING FILE PERCENTAGE # START = 1 END = 1 FOLDER = "storyboard" FORMAT = "PNG" try: rndfile = open(self.pf+"/"+BLEND[1][:BLEND[1].rfind("/")]+"/extra/"+BLEND[1][BLEND[1].rfind("/")+1:]+".rnd", "r") for line in rndfile.read().split("\n"): if line.startswith("START = "): START = int(line[line.find("= ")+1:]) if line.startswith("END = "): END = int(line[line.find("= ")+1:]) if line.startswith("FORMAT = "): FORMAT = str(line[line.find("= ")+1:]).strip() if line.startswith("FOLDER = "): FOLDER = str(line[line.find("= ")+1:]).strip() framnames = [] for frame in range(START, END+1): framnames.append(quick.getfileoutput(frame, FORMAT)) count = 0 for i in os.listdir(self.pf+FOLDER): if i in framnames: count = count + 1 BLEND_COMP = float(count)/float(END+1-START) except: pass #print BLEND_COMP ctx.set_source_rgb(1,1,1) ctx.set_font_size(10) ctx.move_to( ((blendX+40)*n)+list_scroll+10, (listY*ind)+self.mainscroll+listY-25) ctx.show_text(str(int(BLEND_COMP*100))+" %") xgc.set_rgb_fg_color(gtk.gdk.color_parse("#4c4c4c")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll, (listY*ind)+self.mainscroll+listY-10, blendX, 2) xgc.set_rgb_fg_color(gtk.gdk.color_parse("#e47649")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll, (listY*ind)+self.mainscroll+listY-10, int(blendX*BLEND_COMP), 2) xgc.set_rgb_fg_color(gtk.gdk.color_parse("#4c4c4c")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll , (listY*ind)+self.mainscroll+50, blendX, blendX) ## TITLE ## ctx.set_source_rgb(1,1,1) ctx.set_font_size(10) ctx.move_to( ((blendX+40)*n)+list_scroll+10, (listY*ind)+self.mainscroll+listY-40) ctx.show_text(BLEND[1][BLEND[1].rfind("/")+1:]) ### REMOVE BUTTON #### # MOUSE OVER if mx in range(((blendX+40)*n)+list_scroll+blendX, ((blendX+40)*n)+list_scroll+blendX+16) and my in range((listY*ind)+self.mainscroll+40, (listY*ind)+self.mainscroll+40+16): xgc.set_rgb_fg_color(gtk.gdk.color_parse("#e47649")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll+blendX-1, (listY*ind)+self.mainscroll+39, 18, 18) if "GDK_BUTTON1" in str(fx) and "GDK_BUTTON1" not in str(self.mpf) and self.win.is_active(): widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) try: DF = open(self.pf+"/py_data/rnd_seq/"+LIST[0], "r") DF = DF.read().split("\n") NF = "" for d in DF: if BLEND[1] not in d: NF = NF + d+"\n" SF = open(self.pf+"/py_data/rnd_seq/"+LIST[0], "w") SF.write(NF) SF.close() except: pass self.load() widget.window.draw_pixbuf(None, self.delete, 0, 0, ((blendX+40)*n)+list_scroll+blendX, (listY*ind)+self.mainscroll+40 , -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) # IF IT'S RENDERING CURRENTLY if int(BLEND_COMP) == 1: rendrnow = False if rendrnow: xgc.set_rgb_fg_color(gtk.gdk.color_parse("#e47649")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll-2 , (listY*ind)+self.mainscroll+50-2, blendX+4, blendX+4) rendrnow= False checkedfirstrendnow = True if int(BLEND_COMP) == 1 and checkedfirstrendnow == False: rendrnow = True ### IMAGE ### if BLEND[0] and BLEND[0] != "None": widget.window.draw_pixbuf(None, BLEND[0], 0, 0, ((blendX+40)*n)+list_scroll, (listY*ind)+self.mainscroll+50 , -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) elif BLEND[0] != "None" and self.FRAMES > n and ((blendX+40)*n)+list_scroll in range(0, w): try: print self.pf+BLEND[1] BPic = gtk.gdk.pixbuf_new_from_file(thumbnailer.blenderthumb(self.pf+"/"+BLEND[1], 100,100)) except: raise BPic = "None" self.RLISTS[ind][2][n][0] = BPic ## MOUSE OVER let's say fot the grab tool ### if mx in range( ((blendX+40)*n)+list_scroll-2, ((blendX+40)*n)+list_scroll-2+blendX+4): if my in range((listY*ind)+self.mainscroll+50-2, (listY*ind)+self.mainscroll+50-2+blendX+4): widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR)) if self.tool == "grab": xgc.set_rgb_fg_color(gtk.gdk.color_parse("#2c2c2c")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, ((blendX+40)*n)+list_scroll-15, (listY*ind)+self.mainscroll+40, 2, blendX+80) # IF RELESED if "GDK_BUTTON1" not in str(fx) and "GDK_BUTTON1" in str(self.mpf) and self.win.is_active(): # moving line is like copying it first # and then deleting the previous one ### MARK ### # marking to delete the line print self.RLISTS[self.grab[0]][2][self.grab[1]][1] delete_filename = self.RLISTS[self.grab[0]][0] delete_file = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "r") delete_file = delete_file.read().split("\n") print "\n----- DELETE FILE ------ (before)\n" for dn, i in enumerate(delete_file): print i if i == self.RLISTS[self.grab[0]][2][self.grab[1]][1]: delete_file[dn] = "!!!DELETE!!!" print "\n----- DELETE FILE ------ (after)\n" for dn, i in enumerate(delete_file): print i if delete_file[-1] == "": delete_file = delete_file[:-1] save = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "w") for i in delete_file: save.write(i+"\n") save.close() ### INSERT #### # opening the file insert_filename = self.RLISTS[ind][0] insert_file = open(self.pf+"/py_data/rnd_seq/"+insert_filename, "r") insert_file = insert_file.read().split("\n") print "\n----- INSERT FILE ------(before)\n" for i in insert_file: print i insert_file.insert(n, self.RLISTS[self.grab[0]][2][self.grab[1]][1]) print "\n----- INSERT FILE ------(after)\n" for i in insert_file: print i if insert_file[-1] == "": insert_file = insert_file[:-1] save = open(self.pf+"/py_data/rnd_seq/"+insert_filename, "w") for i in insert_file: save.write(i+"\n") save.close() ### REMOVE #### delete_filename = self.RLISTS[self.grab[0]][0] delete_file = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "r") delete_file = delete_file.read().split("\n") delete_file.remove("!!!DELETE!!!") if delete_file[-1] == "": delete_file = delete_file[:-1] save = open(self.pf+"/py_data/rnd_seq/"+delete_filename, "w") for i in delete_file: save.write(i+"\n") save.close() self.load() self.grabbed =True elif "GDK_BUTTON1" in str(fx) and "GDK_BUTTON1" not in str(self.mpf) and self.win.is_active(): self.tool = "grab" self.grab = [ind, n] #RENDER ICON# widget.window.draw_pixbuf(None, self.render, 0, 0, 10, (listY*ind)+self.mainscroll+20 , -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) ### ACTIVATE THE RENDER #### xgc.set_rgb_fg_color(gtk.gdk.color_parse("#4c4c4c")) ## CHOSE COLOR #MOUSE OVER if mx in range(w-210, w) and my in range((listY*ind)+self.mainscroll+20+listY-50, (listY*ind)+self.mainscroll+20+listY-50+44): # get mouse to show the hand widget.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND1)) xgc.set_rgb_fg_color(gtk.gdk.color_parse("#e47649")) if "GDK_BUTTON1" in str(fx) and "GDK_BUTTON1" not in str(self.mpf) and self.win.is_active(): ## POPEN MOTHERFUCKER # subprocess Popen(["python2", self.pf+"/py_data/modules/render.py", self.pf+"/py_data/rnd_seq/"+LIST[0]], universal_newlines=True) widget.window.draw_rectangle(xgc, True, w-210, (listY*ind)+self.mainscroll+20+listY-50, w, 44) ctx.set_source_rgb(1,1,1) ctx.set_font_size(25) ctx.move_to( w-150, (listY*ind)+self.mainscroll+20+listY-15) ctx.show_text("RENDER") widget.window.draw_pixbuf(None, self.render_big, 0, 0, w-200, (listY*ind)+self.mainscroll+20+listY-48 , -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) if self.tool == "grab": #WRITTING IT HERE SO IT WILL OVERWTITE ONTO PREVIOUSLY WRITTEN THINGS ind = self.grab[0] n = self.grab[1] try: BLEND = self.RLISTS[ind][2][n] if BLEND[0] and BLEND[0] != "None": widget.window.draw_pixbuf(None, BLEND[0], 0, 0, mx, my , -1, -1, gtk.gdk.RGB_DITHER_NONE, 0, 0) else: xgc.set_rgb_fg_color(gtk.gdk.color_parse("#4c4c4c")) ## CHOSE COLOR widget.window.draw_rectangle(xgc, True, mx , my, blendX+4, blendX+4) ## TITLE ## ctx.set_source_rgb(1,1,1) ctx.set_font_size(10) ctx.move_to( mx+10, my+listY-80) ctx.show_text(BLEND[1][BLEND[1].rfind("/")+1:]) except: pass ############################################################################# ############################# UNTIL HERE #################################### ############################################################################# # TESTING SOMETHING ctx.set_font_size(20) ctx.move_to( mx, my) #ctx.show_text(str(mx)+":"+str(my)+" "+str(self.mainscroll)) self.dW = w self.DH = h self.mpx = mx self.mpy = my self.mpf = fx def callback(): if self.allowed == True: widget.queue_draw() glib.timeout_add(1, callback)
JYamihud/blender-organizer
py_data/modules/render_lists.py
Python
gpl-2.0
30,411
[ "FLEUR" ]
47f27837beeca9b533bb9c5f81a71b12576e8e109bd4cd2fc1bc00a6e84e7356
# -*- coding: utf-8 -*- """ Created on Wed Mar 9 16:05:59 2016 @author: dongyu https://github.com/nasa/PyAMPR/blob/master/pyampr/google_earth_tools.py https://ocefpaf.github.io/python4oceanographers/blog/2014/03/10/gearth/ https://github.com/hetland/octant/blob/master/octant/sandbox/googleearth.py """ from netCDF4 import Dataset, MFDataset import matplotlib.pyplot as plt import numpy as np import shutil import subprocess import os import time from datetime import datetime from simplekml import (Kml, OverlayXY, ScreenXY, Units, RotationXY, AltitudeMode, Camera) import FileTool import pdb class Pmap(object): """ A general class for visualizing the concentration of oil spill in Google Earth """ def __init__(self,filename, row, col, starttime, bbox=[-95.25,-94.45,28.9,29.9], mpl=8, google_earth=True): """ filename is the name of GNOME output row and col are the rows and columns of the grid to calculate the particle concentration bbox is the domain to visualize the data mpl is the multiplier and the interval to generate figures, default setting is 8 for example, there are 200 files avaiable, but you need to generate 25 figures to save GPU storage and time """ # change directory to GNOME basedir = os.getcwd() os.chdir(basedir+'/GNOME/') dire=os.getcwd() nc=Dataset(filename,'r') particle_num=int(nc.variables['particle_count'][:][0]) data_length=len(nc.variables['longitude'][:]) self.runC(filename, data_length, particle_num, bbox, row, col) print 'Calculating probability, this takes about 1 min !!!\n' for i in xrange(80, 0, -10): print '%d seconds left ...'%i time.sleep(10) os.chdir(dire) ############read count matrix (particle trajectories)############ west=bbox[0]; east=bbox[1] south=bbox[2]; north=bbox[3] x = np.linspace(west, east, col) y = np.linspace(south, north, row) X, Y = np.meshgrid(x, y) ############count time length AKA files number in /data_C DIR = dire+'/data_C' ntime=len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])-8 if google_earth: print "Creating probability map on Google Earth !!!\n" ##########convert coordinate to google earth projection######## if os.path.exists(dire+'/figure'): shutil.rmtree(dire+'/figure') os.makedirs(dire+'/figure') pixels = 512 * 10 for j in range(ntime/mpl): i = j*mpl filename=dire+'/data_C/'+'out_count'+str(i)+'.nc' a=Dataset(filename,'r') count=a.variables['data'][:] count=count.astype('float') count[count==0]=np.nan ## calculate probability count = count / count[np.isnan(count)==False].max() fig, ax = self.gearth_fig(llcrnrlon=west, llcrnrlat=south, urcrnrlon=east, urcrnrlat=north, pixels=pixels) cs = ax.contourf(X,Y,count,200) ax.set_axis_off() plt.savefig(dire+'/figure/'+str(i)+'.png', transparent=True) plt.close() ## colorbar fig1 = plt.figure(figsize=(1.0, 4.0), facecolor=None, frameon=False) ax1 = fig1.add_axes([0.0, 0.05, 0.2, 0.9]) cb = fig1.colorbar(cs, cax=ax1) #cb.set_label('Probability', rotation=-90, color='k') #, labelpad=20) cb.set_label(' ', rotation=-90, color='k') fig1.savefig('legend.png', transparent=False, format='png') bbox=[west, south, east, north] #################Generate the KML file from figures############# self.make_kml(ntime,bbox,starttime,mpl) ############# Deleting figures and count_out files ############# fig_folder=dire+'/figure' for the_file in os.listdir(fig_folder): file_path = os.path.join(fig_folder, the_file) if os.path.isfile(file_path): os.unlink(file_path) else: print "Creating probability map on Python Basemap!!!\n" from mpl_toolkits.basemap import Basemap count0 = np.zeros([row, col]) for j in range(ntime/mpl): i = j*mpl filename = '%s/data_C/out_count%s.nc'%(dire, str(i)) a = Dataset(filename,'r') count=a.variables['data'][:] count=count.astype('float') #count[count==0]=np.nan ## calculate probability count = count / count.max() count0 += count count0[count0==0]=np.nan count0 = count0 / count0[np.isnan(count0)==False].max() pdb.set_trace() ## plotting fig = plt.figure(figsize=(10,8)) basemap = Basemap(projection='merc',llcrnrlat=south,urcrnrlat=north,\ llcrnrlon=west,urcrnrlon=east, resolution='h') basemap.drawcoastlines() basemap.fillcontinents(color='coral',lake_color='aqua') basemap.drawcountries() basemap.drawstates() llons, llats=basemap(*(X,Y)) con=basemap.contourf(llons,llats,count0,200,zorder=4, alpha=0.6) cbar = plt.colorbar(con, orientation='vertical') cbar.set_label("probability") pdb.set_trace() for i in range(ntime): filename=dire+'/data_C/'+'out_count'+str(i)+'.nc' self.deleteFile(filename) ## change directory back os.chdir(basedir) def deleteFile(self,srcname): if os.path.isfile(srcname): os.remove(srcname) def runC(self, filename, data_length, particle_num, bbox, row_num, column_num): """ The function is used to update the C++ program with parameters and execuate the program to generate netcdf file for particle concentration """ dire=os.getcwd() if os.path.exists(dire+'/data_C'): shutil.rmtree(dire+'/data_C') os.makedirs(dire+'/data_C') scripts = ['../DATA/data_C/Makefile', '../DATA/data_C/Makefile.in', \ '../DATA/data_C/old_readnetcdf.cpp', filename] for ss in scripts: FileTool.move_file(ss, dire+'/data_C') os.chdir(dire+'/data_C') f=open(dire+'/data_C/old_readnetcdf.cpp','r') content=f.readlines() open(dire+'/data_C/readnetcdf.cpp','w').write('') h=open(dire+'/data_C/readnetcdf.cpp','w') for line in content: h.write(line.replace('data_length',str(data_length)).replace('particle_num',str(particle_num)). replace('west_point',str(bbox[0])).replace('east_point',str(bbox[1])).replace('south_point',str(bbox[2])).replace('north_point',str(bbox[3])).replace('GNOME_file',filename).replace('row_num',str(row_num)).replace('column_num',str(column_num))) h.close() subprocess.Popen('make',shell=False) time.sleep(3) subprocess.Popen('./readnetcdf',shell=False) def make_kml(self, ntime, bbox, starttime, mpl, colorbar=True): """TODO: LatLon bbox, list of figs, optional colorbar figure, and several simplekml kw...""" """bbox is the cooridnate""" llcrnrlon=bbox[0] #west llcrnrlat=bbox[1] #south urcrnrlon=bbox[2] #east urcrnrlat=bbox[3] #north dire=os.getcwd()+'/figure/' obj=[str(i) for i in xrange(ntime)] kml = Kml() altitude = 161000 #This is 100 miles #set the view altitude: 2e7 roll = 0 tilt = 0 altitudemode = AltitudeMode.relativetoground camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]), longitude=np.mean([urcrnrlon, llcrnrlon]), altitude=altitude, roll=roll, tilt=tilt, altitudemode=altitudemode) kml.document.camera = camera starttime = datetime.strptime(starttime, '%Y-%m-%d-%H') yr = datetime.strftime(starttime, '%Y') month = datetime.strftime(starttime, '%m') day = datetime.strftime(starttime, '%d') hr = datetime.strftime(starttime, '%H') #yr=tbox[0] #2014 #month=tbox[1] #8 #day=tbox[2] #21 for j in range(ntime/mpl): i=j*mpl fig=dire+str(i)+'.png' #draworder += 1 obj[i] = kml.newgroundoverlay(name='GroundOverlay') #obj[i].draworder = draworder obj[i].visibility = 1 obj[i].name = 'overlay' obj[i].color = '9effffff' obj[i].latlonbox.rotation = 0 obj[i].gxaltitudemode = 'clampToSeaFloor' #obj[i].timespan.begin="2011-02-20T"+str("%02d" % i)+":00:00Z" #obj[i].timespan.end="2011-02-20T"+str("%02d" % (i+1))+":00:00Z" obj[i].timestamp.when=yr+'-'+month+'-'+str('%02d' % (int(day)+i/96))+'T'\ + str("%02d" % (int(hr)+ (i/4)%24))+':' +str("%02d" %((i*15)%60))+':00Z' obj[i].icon.href = fig obj[i].latlonbox.east = llcrnrlon obj[i].latlonbox.south = llcrnrlat obj[i].latlonbox.north = urcrnrlat obj[i].latlonbox.west = urcrnrlon #pdb.set_trace() if colorbar: # Options for colorbar are hard-coded (to avoid a big mess). screen = kml.newscreenoverlay(name='ScreenOverlay') screen.icon.href = 'legend.png' screen.overlayxy = OverlayXY(x=0, y=0, xunits=Units.fraction, yunits=Units.fraction) screen.screenxy = ScreenXY(x=0.015, y=0.075, xunits=Units.fraction, yunits=Units.fraction) screen.rotationXY = RotationXY(x=0.5, y=0.5, xunits=Units.fraction, yunits=Units.fraction) screen.size.x = 0 screen.size.y = 0 screen.size.xunits = Units.fraction screen.size.yunits = Units.fraction screen.visibility = 1 kmzfile = 'GNOME_PM.kmz' #kmzfile = kw.pop('kmzfile', 'GNOME_GE.kmz') kml.savekmz(kmzfile) print "#### Successfully generate the Google Earth file %s"%kmzfile def gearth_fig(self, llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, pixels=1024): """Return a Matplotlib `fig` and `ax` handles for a Google-Earth Image.""" aspect = np.cos(np.mean([llcrnrlat, urcrnrlat]) * np.pi/180.0) xsize = np.ptp([urcrnrlon, llcrnrlon]) * aspect ysize = np.ptp([urcrnrlat, llcrnrlat]) aspect = ysize / xsize if aspect > 1.0: figsize = (10.0 / aspect, 10.0) else: figsize = (10.0, 10.0 * aspect) if False: plt.ioff() # Make `True` to prevent the KML components from poping-up. fig = plt.figure(figsize=figsize, facecolor=None, frameon=False, dpi=pixels//10) # KML friendly image. If using basemap try: `fix_aspect=False`. ax = fig.add_axes([0, 0, 1, 1]) ax.set_xlim(llcrnrlon, urcrnrlon) ax.set_ylim(llcrnrlat, urcrnrlat) return fig, ax if __name__ == "__main__": bbox=[-95.78,-94.45,28.3,29.9] google_plot('GNOME_output.nc', 300, 300, bbox, mpl=8)
UT-CWE/Hyospy
Hyospy_ensemble/lib/Probability_map.py
Python
mit
11,874
[ "NetCDF" ]
cf242929dac30d26ce157f5bdf435313b16e4be44ddf7484252c2477a8cb7f87