Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> vi = [ 6, 'minor' ],
vii = [ 7, 'minor' ],
)
class Literal(object):
def __init__(self):
"""
Constructs an interpreter for specific note names or chords.
It doesn't need to know a scale and is pretty basic.
literal = Literal()
roman.do("C4,E4,G4") == chord("C4 major")
roman.do("C4 major") == chord("C4,E4,G4")
roman.do("C4") == note("C4")
"""
pass
def do(self, sym):
"""
Accepts symbols like C4-major or C4,E4,G4
or note symbols like 'C4'
"""
# The dash is a bit of a notation hack, it's there because "C4 major"
# would look like two symbols, so we need to have no whitespace
# between them
if sym is None or sym == '-':
# REST:
<|code_end|>
, generate the next line using the imports in this file:
from camp.core.note import note
from camp.core.chord import chord, Chord
and context (functions, classes, or occasionally code) from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
. Output only the next line. | return chord([]) |
Using the snippet: <|code_start|> def do(self, sym):
"""
Accepts symbols like C4-major or C4,E4,G4
or note symbols like 'C4'
"""
# The dash is a bit of a notation hack, it's there because "C4 major"
# would look like two symbols, so we need to have no whitespace
# between them
if sym is None or sym == '-':
# REST:
return chord([])
if '-' in sym:
return chord(sym.replace("-"," "))
elif "," in sym:
return chord(sym.split(","))
else:
return note(sym)
def do_notes(self, sym):
"""
Same as do() but always get back an array of notes.
"""
# DRY: duplication with Roman.py - FIXME
if sym == '-':
# REST
return []
note_or_chord = self.do(sym)
if note_or_chord is None:
return []
<|code_end|>
, determine the next line of code. You have imports:
from camp.core.note import note
from camp.core.chord import chord, Chord
and context (class names, function names, or code) available:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
. Output only the next line. | elif type(note_or_chord) == Chord: |
Here is a snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class FxBuses(object):
__slots__ = [ '_buses', '_factory' ]
def __init__(self, song, **buses):
self._factory = song
self._buses = dict()
for (bus_name, bus) in buses.items():
if getattr(bus, '__call__', None) is not None:
bus = bus(song)
<|code_end|>
. Write the next line using the current file imports:
from camp.tracker.fx_bus import FxBus
and context from other files:
# Path: camp/tracker/fx_bus.py
# class FxBus(object):
#
# def __init__(self, member_list):
# self._nodes = [ member.copy() for member in member_list ]
#
# def nodes(self):
# return [ node.copy() for node in self._nodes ]
#
# def to_data(self):
# return [ x.to_data() for x in self._nodes ]
, which may include functions, classes, or code. Output only the next line. | if not isinstance(bus, FxBus): |
Next line prediction: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class TestChord(object):
def test_basics(self):
<|code_end|>
. Use current file imports:
(from camp.core.note import note
from camp.core.chord import Chord, chord)
and context including class names, function names, or small code snippets from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
#
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
. Output only the next line. | notes = [ note('C4'), note('E4'), note('G4')] |
Here is a snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class TestChord(object):
def test_basics(self):
notes = [ note('C4'), note('E4'), note('G4')]
<|code_end|>
. Write the next line using the current file imports:
from camp.core.note import note
from camp.core.chord import Chord, chord
and context from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
#
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
, which may include functions, classes, or code. Output only the next line. | chord1 = Chord(notes=notes) |
Given the code snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class TestChord(object):
def test_basics(self):
notes = [ note('C4'), note('E4'), note('G4')]
chord1 = Chord(notes=notes)
assert chord1.notes[0] == note('C4')
assert chord1.notes[1] == note('E4')
assert chord1.notes[2] == note('G4')
assert str(chord1) == 'Chord<C4,E4,G4>'
<|code_end|>
, generate the next line using the imports in this file:
from camp.core.note import note
from camp.core.chord import Chord, chord
and context (functions, classes, or occasionally code) from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
#
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
. Output only the next line. | chord2 = chord(['G4','C4','E4']) |
Given the code snippet: <|code_start|>
self._factory = song
self._patterns = dict()
self._save(patterns)
def _save(self, patterns):
for (name, pattern) in patterns.items():
if isinstance(pattern, str):
pattern = pattern.replace("|","").split()
# print("USING PATTERN: %s" % pattern)
self._patterns[name] = self.create(pattern)
def create(self, pattern):
raise NotImplementedError()
def as_dict(self):
return self._patterns
class RandomPatterns(Patterns):
def __init__(self, song, mode=None, patterns=None):
self.mode = mode
super().__init__(song, patterns=patterns)
def create(self, pattern):
return Randomly(pattern, mode=self.mode)
class EndlessPatterns(Patterns):
def create(self, pattern):
<|code_end|>
, generate the next line using the imports in this file:
from camp.band.selectors.endlessly import Endlessly
from camp.band.selectors.repeatedly import Repeatedly
from camp.band.selectors.randomly import Randomly
and context (functions, classes, or occasionally code) from other files:
# Path: camp/band/selectors/endlessly.py
# class Endlessly(Selector):
#
# def __init__(self, alist, mode=None):
# self.data = alist
# self.my_generator = endlessly_generate(alist)
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Endlessly", data=dict(alist=self.data))
#
# Path: camp/band/selectors/repeatedly.py
# class Repeatedly(Selector):
#
# def __init__(self, alist, cycles=1, mode=None):
# self.data = alist
# self.cycles = cycles
# self.my_generator = do_generate(cycles, alist)
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Repeatedly", data=dict(alist=self.data, cycles=self.cycles))
#
# Path: camp/band/selectors/randomly.py
# class Randomly(Selector):
#
# # see examples/11_randomness.py for usage
#
# # TODO: implement serialism by allowing a serialism=True flag which will pop
# # the item off the list once consumed. When done, update comments in 11_randomness.py
# # to show the example.
#
# def __init__(self, alist, mode='choice'):
# self.data = alist
# self.mode = mode
# self.my_generator = endlessly_generate(alist, mode)
#
# random.seed()
#
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Randomly", data=dict(alist=self.data, mode=self.mode))
. Output only the next line. | return Endlessly(pattern) |
Predict the next line after this snippet: <|code_start|> return self._patterns
class RandomPatterns(Patterns):
def __init__(self, song, mode=None, patterns=None):
self.mode = mode
super().__init__(song, patterns=patterns)
def create(self, pattern):
return Randomly(pattern, mode=self.mode)
class EndlessPatterns(Patterns):
def create(self, pattern):
return Endlessly(pattern)
class BasicPatterns(Patterns):
def create(self, pattern):
return pattern
class RepeatedPatterns(Patterns):
def __init__(self, song, hold=None, patterns=None):
self.hold = hold
self.mode = mode
super().__init__(song, patterns=patterns)
def create(self, pattern):
<|code_end|>
using the current file's imports:
from camp.band.selectors.endlessly import Endlessly
from camp.band.selectors.repeatedly import Repeatedly
from camp.band.selectors.randomly import Randomly
and any relevant context from other files:
# Path: camp/band/selectors/endlessly.py
# class Endlessly(Selector):
#
# def __init__(self, alist, mode=None):
# self.data = alist
# self.my_generator = endlessly_generate(alist)
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Endlessly", data=dict(alist=self.data))
#
# Path: camp/band/selectors/repeatedly.py
# class Repeatedly(Selector):
#
# def __init__(self, alist, cycles=1, mode=None):
# self.data = alist
# self.cycles = cycles
# self.my_generator = do_generate(cycles, alist)
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Repeatedly", data=dict(alist=self.data, cycles=self.cycles))
#
# Path: camp/band/selectors/randomly.py
# class Randomly(Selector):
#
# # see examples/11_randomness.py for usage
#
# # TODO: implement serialism by allowing a serialism=True flag which will pop
# # the item off the list once consumed. When done, update comments in 11_randomness.py
# # to show the example.
#
# def __init__(self, alist, mode='choice'):
# self.data = alist
# self.mode = mode
# self.my_generator = endlessly_generate(alist, mode)
#
# random.seed()
#
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Randomly", data=dict(alist=self.data, mode=self.mode))
. Output only the next line. | return Repeatedly(pattern, hold=self.hold) |
Using the snippet: <|code_start|>class Patterns(object):
def __init__(self, song, patterns=None):
assert patterns is not None
self._factory = song
self._patterns = dict()
self._save(patterns)
def _save(self, patterns):
for (name, pattern) in patterns.items():
if isinstance(pattern, str):
pattern = pattern.replace("|","").split()
# print("USING PATTERN: %s" % pattern)
self._patterns[name] = self.create(pattern)
def create(self, pattern):
raise NotImplementedError()
def as_dict(self):
return self._patterns
class RandomPatterns(Patterns):
def __init__(self, song, mode=None, patterns=None):
self.mode = mode
super().__init__(song, patterns=patterns)
def create(self, pattern):
<|code_end|>
, determine the next line of code. You have imports:
from camp.band.selectors.endlessly import Endlessly
from camp.band.selectors.repeatedly import Repeatedly
from camp.band.selectors.randomly import Randomly
and context (class names, function names, or code) available:
# Path: camp/band/selectors/endlessly.py
# class Endlessly(Selector):
#
# def __init__(self, alist, mode=None):
# self.data = alist
# self.my_generator = endlessly_generate(alist)
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Endlessly", data=dict(alist=self.data))
#
# Path: camp/band/selectors/repeatedly.py
# class Repeatedly(Selector):
#
# def __init__(self, alist, cycles=1, mode=None):
# self.data = alist
# self.cycles = cycles
# self.my_generator = do_generate(cycles, alist)
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Repeatedly", data=dict(alist=self.data, cycles=self.cycles))
#
# Path: camp/band/selectors/randomly.py
# class Randomly(Selector):
#
# # see examples/11_randomness.py for usage
#
# # TODO: implement serialism by allowing a serialism=True flag which will pop
# # the item off the list once consumed. When done, update comments in 11_randomness.py
# # to show the example.
#
# def __init__(self, alist, mode='choice'):
# self.data = alist
# self.mode = mode
# self.my_generator = endlessly_generate(alist, mode)
#
# random.seed()
#
#
# def draw(self):
# result = next(self.my_generator)
# return result
#
# def to_data(self):
# return dict(cls="camp.band.selectors.selector.Randomly", data=dict(alist=self.data, mode=self.mode))
. Output only the next line. | return Randomly(pattern, mode=self.mode) |
Using the snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
def do_generate(cycles, alist):
for x in range(0, cycles):
for item in alist:
yield item
<|code_end|>
, determine the next line of code. You have imports:
from camp.band.selectors.selector import Selector
and context (class names, function names, or code) available:
# Path: camp/band/selectors/selector.py
# class Selector(object):
#
# def __init__(self, alist, mode=None):
# raise NotImplementedError()
#
# def draw(self):
# raise NotImplementedError()
#
# def to_data(self):
# raise NotImplementedError()
. Output only the next line. | class Repeatedly(Selector): |
Here is a snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class TestScale(object):
def test_basics(self):
<|code_end|>
. Write the next line using the current file imports:
from camp.core.note import note
from camp.core.chord import chord
from camp.core.scale import Scale, scale
and context from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# Path: camp/core/scale.py
# class Scale(object):
#
# def __init__(self, root=None, typ=None):
#
# """
# Constructs a scale:
#
# scale = Scale(root='C4', typ='major')
# """
#
# assert root is not None
# assert typ is not None
# if isinstance(root, str):
# root = note(root)
# self.root = root
# self.typ = typ
#
# def generate(self, length=None):
# """
# Allows traversal of a scale in a forward direction.
# Example:
# for note in scale.generate(length=2):
# print note
# """
#
#
# assert length is not None
#
# typ = SCALE_ALIASES.get(self.typ, self.typ)
# scale_data = SCALE_TYPES[typ][:]
#
# octave_shift = 0
# index = 0
# while (length is None or length > 0):
#
# if index == len(scale_data):
# index = 0
# octave_shift = octave_shift + 1
# result = self.root.transpose(degrees=scale_data[index], octaves=octave_shift)
# yield(result)
# index = index + 1
# if length is not None:
# length = length - 1
#
# def __eq__(self, other):
# """
# Scales are equal if they are the ... same scale
# """
# if other is None:
# return False
# return self.root == other.root and self.typ == other.typ
#
# def short_name(self):
# return "%s %s" % (self.root.short_name(), self.typ)
#
# def __repr__(self):
# return "Scale<%s>" % self.short_name()
#
# def scale(input):
# """
# Shortcut: scale(['C major') -> Scale object
# """
# (root, typ) = input.split()
# return Scale(root=note(root), typ=typ)
, which may include functions, classes, or code. Output only the next line. | scale1 = Scale(root=note('C4'), typ='major') |
Given snippet: <|code_start|>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.
"""
class TestScale(object):
def test_basics(self):
scale1 = Scale(root=note('C4'), typ='major')
scale2 = scale('C4 major')
assert scale1 == scale2
assert str(scale1) == 'Scale<C4 major>'
def _scale_test(self, expression=None, expected=None, length=None):
if isinstance(expected, str):
expected = expected.split()
assert length is not None
scale1 = scale(expression)
results = [ note for note in scale1.generate(length=length) ]
print("generating: %s for %s" % (expression, length))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from camp.core.note import note
from camp.core.chord import chord
from camp.core.scale import Scale, scale
and context:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# Path: camp/core/scale.py
# class Scale(object):
#
# def __init__(self, root=None, typ=None):
#
# """
# Constructs a scale:
#
# scale = Scale(root='C4', typ='major')
# """
#
# assert root is not None
# assert typ is not None
# if isinstance(root, str):
# root = note(root)
# self.root = root
# self.typ = typ
#
# def generate(self, length=None):
# """
# Allows traversal of a scale in a forward direction.
# Example:
# for note in scale.generate(length=2):
# print note
# """
#
#
# assert length is not None
#
# typ = SCALE_ALIASES.get(self.typ, self.typ)
# scale_data = SCALE_TYPES[typ][:]
#
# octave_shift = 0
# index = 0
# while (length is None or length > 0):
#
# if index == len(scale_data):
# index = 0
# octave_shift = octave_shift + 1
# result = self.root.transpose(degrees=scale_data[index], octaves=octave_shift)
# yield(result)
# index = index + 1
# if length is not None:
# length = length - 1
#
# def __eq__(self, other):
# """
# Scales are equal if they are the ... same scale
# """
# if other is None:
# return False
# return self.root == other.root and self.typ == other.typ
#
# def short_name(self):
# return "%s %s" % (self.root.short_name(), self.typ)
#
# def __repr__(self):
# return "Scale<%s>" % self.short_name()
#
# def scale(input):
# """
# Shortcut: scale(['C major') -> Scale object
# """
# (root, typ) = input.split()
# return Scale(root=note(root), typ=typ)
which might include code, classes, or functions. Output only the next line. | assert chord(results) == chord(expected) |
Given the following code snippet before the placeholder: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class TestScale(object):
def test_basics(self):
<|code_end|>
, predict the next line using imports from the current file:
from camp.core.note import note
from camp.core.chord import chord
from camp.core.scale import Scale, scale
and context including class names, function names, and sometimes code from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# Path: camp/core/scale.py
# class Scale(object):
#
# def __init__(self, root=None, typ=None):
#
# """
# Constructs a scale:
#
# scale = Scale(root='C4', typ='major')
# """
#
# assert root is not None
# assert typ is not None
# if isinstance(root, str):
# root = note(root)
# self.root = root
# self.typ = typ
#
# def generate(self, length=None):
# """
# Allows traversal of a scale in a forward direction.
# Example:
# for note in scale.generate(length=2):
# print note
# """
#
#
# assert length is not None
#
# typ = SCALE_ALIASES.get(self.typ, self.typ)
# scale_data = SCALE_TYPES[typ][:]
#
# octave_shift = 0
# index = 0
# while (length is None or length > 0):
#
# if index == len(scale_data):
# index = 0
# octave_shift = octave_shift + 1
# result = self.root.transpose(degrees=scale_data[index], octaves=octave_shift)
# yield(result)
# index = index + 1
# if length is not None:
# length = length - 1
#
# def __eq__(self, other):
# """
# Scales are equal if they are the ... same scale
# """
# if other is None:
# return False
# return self.root == other.root and self.typ == other.typ
#
# def short_name(self):
# return "%s %s" % (self.root.short_name(), self.typ)
#
# def __repr__(self):
# return "Scale<%s>" % self.short_name()
#
# def scale(input):
# """
# Shortcut: scale(['C major') -> Scale object
# """
# (root, typ) = input.split()
# return Scale(root=note(root), typ=typ)
. Output only the next line. | scale1 = Scale(root=note('C4'), typ='major') |
Predict the next line after this snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
class TestScale(object):
def test_basics(self):
scale1 = Scale(root=note('C4'), typ='major')
<|code_end|>
using the current file's imports:
from camp.core.note import note
from camp.core.chord import chord
from camp.core.scale import Scale, scale
and any relevant context from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# Path: camp/core/scale.py
# class Scale(object):
#
# def __init__(self, root=None, typ=None):
#
# """
# Constructs a scale:
#
# scale = Scale(root='C4', typ='major')
# """
#
# assert root is not None
# assert typ is not None
# if isinstance(root, str):
# root = note(root)
# self.root = root
# self.typ = typ
#
# def generate(self, length=None):
# """
# Allows traversal of a scale in a forward direction.
# Example:
# for note in scale.generate(length=2):
# print note
# """
#
#
# assert length is not None
#
# typ = SCALE_ALIASES.get(self.typ, self.typ)
# scale_data = SCALE_TYPES[typ][:]
#
# octave_shift = 0
# index = 0
# while (length is None or length > 0):
#
# if index == len(scale_data):
# index = 0
# octave_shift = octave_shift + 1
# result = self.root.transpose(degrees=scale_data[index], octaves=octave_shift)
# yield(result)
# index = index + 1
# if length is not None:
# length = length - 1
#
# def __eq__(self, other):
# """
# Scales are equal if they are the ... same scale
# """
# if other is None:
# return False
# return self.root == other.root and self.typ == other.typ
#
# def short_name(self):
# return "%s %s" % (self.root.short_name(), self.typ)
#
# def __repr__(self):
# return "Scale<%s>" % self.short_name()
#
# def scale(input):
# """
# Shortcut: scale(['C major') -> Scale object
# """
# (root, typ) = input.split()
# return Scale(root=note(root), typ=typ)
. Output only the next line. | scale2 = scale('C4 major') |
Next line prediction: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
<|code_end|>
. Use current file imports:
(from camp.band.members.member import Member)
and context including class names, function names, or small code snippets from other files:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
. Output only the next line. | class Arp(Member): |
Continue the code snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
<|code_end|>
. Use current file imports:
from camp.band.members.member import Member
and context (classes, functions, or code) from other files:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
. Output only the next line. | class Subdivide(Member): |
Using the snippet: <|code_start|> yield False
else:
yield True
elif mode == 'exhaust':
my_list = alist[:]
while len(my_list) > 0:
print("DRAWING")
length = len(my_list)
index = random.randint(0,length) - 1
item = my_list.pop(index)
print("EXHAUST YIELDS: %s" % item)
yield item
print("ALL DONE")
elif mode == 'human':
while True:
length = len(alist)
index = random.randint(0,alist) - 1
item = alist.pop(index)
yield item
else:
raise Exception("unknown Randomly mode: %s" % mode)
<|code_end|>
, determine the next line of code. You have imports:
from camp.band.selectors.selector import Selector
import random
import copy
and context (class names, function names, or code) available:
# Path: camp/band/selectors/selector.py
# class Selector(object):
#
# def __init__(self, alist, mode=None):
# raise NotImplementedError()
#
# def draw(self):
# raise NotImplementedError()
#
# def to_data(self):
# raise NotImplementedError()
. Output only the next line. | class Randomly(Selector): |
Based on the snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
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.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from camp.band.members.member import Member
and context (classes, functions, sometimes code) from other files:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
. Output only the next line. | class Transpose(Member): |
Given snippet: <|code_start|>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.
"""
class Instruments(object):
__slots__ = [ "_instruments", "_factory" ]
def __init__(self, song, **instruments):
self._factory = song
self._instruments = dict()
for (instrument_name, instrument) in instruments.items():
print("CREATING INSTRUMENT: %s" % instrument)
instrument._factory = song
print(instrument.channel)
if instrument.channel is None:
raise Exception("DEBUG: channel is None")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from camp.tracker.instrument import Instrument
and context:
# Path: camp/tracker/instrument.py
# class Instrument(object):
#
# def __init__(self, channel=None, notation='roman'):
#
# self.channel = channel
# self.notation = notation
#
# if type(self.channel) != int:
# raise Exception("channel must be set, as an integer, got: %s" % self.channel)
# if notation not in VALID_NOTATIONS:
# raise Exception("invalid notation type: %s" % notation)
#
# def to_data(self):
# return dict(cls="camp.band.tracker.instrument.Instrument", data=dict(channel=self.channel, notation=self.notation))
which might include code, classes, or functions. Output only the next line. | if type(instrument) != Instrument: |
Next line prediction: <|code_start|> locrian = [ 1, 'b2', 'b3', 4, 'b5', 'b6', 'b7' ],
lydian = [ 1, 2, 3, 'b4', 5, 6, 7 ],
major_pentatonic = [ 1, 2, 3, 5, 6 ],
melodic_minor_asc = [ 1, 2, 'b3', 4, 5, 'b7', 'b8', 8 ],
melodic_minor_desc = [ 1, 2, 'b3', 4, 5, 'b6', 'b7', 8 ],
minor_pentatonic = [ 1, 'b3', 4, 5, 'b7' ],
mixolydian = [ 1, 2, 3, 4, 5, 6, 'b7' ],
phyrigian = [ 1, 'b2', 'b3', 4, 5, 'b6', 'b7' ],
)
SCALE_ALIASES = dict(
aeolian = 'natural_minor',
ionian = 'major',
minor = 'natural_minor'
)
class Scale(object):
def __init__(self, root=None, typ=None):
"""
Constructs a scale:
scale = Scale(root='C4', typ='major')
"""
assert root is not None
assert typ is not None
if isinstance(root, str):
<|code_end|>
. Use current file imports:
(from camp.core.note import note)
and context including class names, function names, or small code snippets from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
. Output only the next line. | root = note(root) |
Here is a snippet: <|code_start|>
def summarized_placeholder(name, prefix=None, key=tf.GraphKeys.SUMMARIES):
prefix = '' if not prefix else prefix + '/'
p = tf.placeholder(tf.float32, name=name)
tf.summary.scalar(prefix + name, p, collections=[key])
return p
def resize_area(tensor, like):
_, h, w, _ = tf.unstack(tf.shape(like))
return tf.stop_gradient(tf.image.resize_area(tensor, [h, w]))
def resize_bilinear(tensor, like):
_, h, w, _ = tf.unstack(tf.shape(like))
return tf.stop_gradient(tf.image.resize_bilinear(tensor, [h, w]))
def downsample(tensor, num):
_,height, width,_ = tensor.shape.as_list()
if height%2==0 and width%2==0:
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
from ..ops import downsample as downsample_ops
and context from other files:
# Path: src/e2eflow/ops.py
# OP_NAMES = ['backward_warp', 'downsample', 'correlation', 'forward_warp']
# def compile(op=None):
# def correlation(first, second, **kwargs):
# def _BackwardWarpGrad(op, grad):
# def _ForwardWarpGrad(op, grad):
# def _CorrelationGrad(op, in_grad, in_grad1, in_grad2):
, which may include functions, classes, or code. Output only the next line. | return downsample_ops(tensor, num) |
Here is a snippet: <|code_start|>
DISOCC_THRESH = 0.8
def length_sq(x):
return tf.reduce_sum(tf.square(x), 3, keepdims=True)
def compute_losses(im1, im2, flow_fw, flow_bw,
border_mask=None,
mask_occlusion='',
data_max_distance=1):
losses = {}
im2_warped = image_warp(im2, flow_fw)
im1_warped = image_warp(im1, flow_bw)
im_diff_fw = im1 - im2_warped
im_diff_bw = im2 - im1_warped
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
import numpy as np
from tensorflow.contrib.distributions import Normal
from ..ops import backward_warp, forward_warp
from .image_warp import image_warp
and context from other files:
# Path: src/e2eflow/ops.py
# OP_NAMES = ['backward_warp', 'downsample', 'correlation', 'forward_warp']
# def compile(op=None):
# def correlation(first, second, **kwargs):
# def _BackwardWarpGrad(op, grad):
# def _ForwardWarpGrad(op, grad):
# def _CorrelationGrad(op, in_grad, in_grad1, in_grad2):
#
# Path: src/e2eflow/core/image_warp.py
# def image_warp(im, flow):
# """Performs a backward warp of an image using the predicted flow.
#
# Args:
# im: Batch of images. [num_batch, height, width, channels]
# flow: Batch of flow vectors. [num_batch, height, width, 2]
# Returns:
# warped: transformed image of the same shape as the input image.
# """
# with tf.variable_scope('image_warp'):
#
# num_batch, height, width, channels = tf.unstack(tf.shape(im))
# max_x = tf.cast(width - 1, 'int32')
# max_y = tf.cast(height - 1, 'int32')
# zero = tf.zeros([], dtype='int32')
#
# # We have to flatten our tensors to vectorize the interpolation
# im_flat = tf.reshape(im, [-1, channels])
# flow_flat = tf.reshape(flow, [-1, 2])
#
# # Floor the flow, as the final indices are integers
# # The fractional part is used to control the bilinear interpolation.
# flow_floor = tf.to_int32(tf.floor(flow_flat))
# bilinear_weights = flow_flat - tf.floor(flow_flat)
#
# # Construct base indices which are displaced with the flow
# pos_x = tf.tile(tf.range(width), [height * num_batch])
# grid_y = tf.tile(tf.expand_dims(tf.range(height), 1), [1, width])
# pos_y = tf.tile(tf.reshape(grid_y, [-1]), [num_batch])
#
# x = flow_floor[:, 0]
# y = flow_floor[:, 1]
# xw = bilinear_weights[:, 0]
# yw = bilinear_weights[:, 1]
#
# # Compute interpolation weights for 4 adjacent pixels
# # expand to num_batch * height * width x 1 for broadcasting in add_n below
# wa = tf.expand_dims((1 - xw) * (1 - yw), 1) # top left pixel
# wb = tf.expand_dims((1 - xw) * yw, 1) # bottom left pixel
# wc = tf.expand_dims(xw * (1 - yw), 1) # top right pixel
# wd = tf.expand_dims(xw * yw, 1) # bottom right pixel
#
# x0 = pos_x + x
# x1 = x0 + 1
# y0 = pos_y + y
# y1 = y0 + 1
#
# x0 = tf.clip_by_value(x0, zero, max_x)
# x1 = tf.clip_by_value(x1, zero, max_x)
# y0 = tf.clip_by_value(y0, zero, max_y)
# y1 = tf.clip_by_value(y1, zero, max_y)
#
# dim1 = width * height
# batch_offsets = tf.range(num_batch) * dim1
# base_grid = tf.tile(tf.expand_dims(batch_offsets, 1), [1, dim1])
# base = tf.reshape(base_grid, [-1])
#
# base_y0 = base + y0 * width
# base_y1 = base + y1 * width
# idx_a = base_y0 + x0
# idx_b = base_y1 + x0
# idx_c = base_y0 + x1
# idx_d = base_y1 + x1
#
# Ia = tf.gather(im_flat, idx_a)
# Ib = tf.gather(im_flat, idx_b)
# Ic = tf.gather(im_flat, idx_c)
# Id = tf.gather(im_flat, idx_d)
#
# warped_flat = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])
# warped = tf.reshape(warped_flat, [num_batch, height, width, channels])
#
# return warped
, which may include functions, classes, or code. Output only the next line. | disocc_fw = tf.cast(forward_warp(flow_fw) < DISOCC_THRESH, tf.float32) |
Continue the code snippet: <|code_start|>
DISOCC_THRESH = 0.8
def length_sq(x):
return tf.reduce_sum(tf.square(x), 3, keepdims=True)
def compute_losses(im1, im2, flow_fw, flow_bw,
border_mask=None,
mask_occlusion='',
data_max_distance=1):
losses = {}
<|code_end|>
. Use current file imports:
import tensorflow as tf
import numpy as np
from tensorflow.contrib.distributions import Normal
from ..ops import backward_warp, forward_warp
from .image_warp import image_warp
and context (classes, functions, or code) from other files:
# Path: src/e2eflow/ops.py
# OP_NAMES = ['backward_warp', 'downsample', 'correlation', 'forward_warp']
# def compile(op=None):
# def correlation(first, second, **kwargs):
# def _BackwardWarpGrad(op, grad):
# def _ForwardWarpGrad(op, grad):
# def _CorrelationGrad(op, in_grad, in_grad1, in_grad2):
#
# Path: src/e2eflow/core/image_warp.py
# def image_warp(im, flow):
# """Performs a backward warp of an image using the predicted flow.
#
# Args:
# im: Batch of images. [num_batch, height, width, channels]
# flow: Batch of flow vectors. [num_batch, height, width, 2]
# Returns:
# warped: transformed image of the same shape as the input image.
# """
# with tf.variable_scope('image_warp'):
#
# num_batch, height, width, channels = tf.unstack(tf.shape(im))
# max_x = tf.cast(width - 1, 'int32')
# max_y = tf.cast(height - 1, 'int32')
# zero = tf.zeros([], dtype='int32')
#
# # We have to flatten our tensors to vectorize the interpolation
# im_flat = tf.reshape(im, [-1, channels])
# flow_flat = tf.reshape(flow, [-1, 2])
#
# # Floor the flow, as the final indices are integers
# # The fractional part is used to control the bilinear interpolation.
# flow_floor = tf.to_int32(tf.floor(flow_flat))
# bilinear_weights = flow_flat - tf.floor(flow_flat)
#
# # Construct base indices which are displaced with the flow
# pos_x = tf.tile(tf.range(width), [height * num_batch])
# grid_y = tf.tile(tf.expand_dims(tf.range(height), 1), [1, width])
# pos_y = tf.tile(tf.reshape(grid_y, [-1]), [num_batch])
#
# x = flow_floor[:, 0]
# y = flow_floor[:, 1]
# xw = bilinear_weights[:, 0]
# yw = bilinear_weights[:, 1]
#
# # Compute interpolation weights for 4 adjacent pixels
# # expand to num_batch * height * width x 1 for broadcasting in add_n below
# wa = tf.expand_dims((1 - xw) * (1 - yw), 1) # top left pixel
# wb = tf.expand_dims((1 - xw) * yw, 1) # bottom left pixel
# wc = tf.expand_dims(xw * (1 - yw), 1) # top right pixel
# wd = tf.expand_dims(xw * yw, 1) # bottom right pixel
#
# x0 = pos_x + x
# x1 = x0 + 1
# y0 = pos_y + y
# y1 = y0 + 1
#
# x0 = tf.clip_by_value(x0, zero, max_x)
# x1 = tf.clip_by_value(x1, zero, max_x)
# y0 = tf.clip_by_value(y0, zero, max_y)
# y1 = tf.clip_by_value(y1, zero, max_y)
#
# dim1 = width * height
# batch_offsets = tf.range(num_batch) * dim1
# base_grid = tf.tile(tf.expand_dims(batch_offsets, 1), [1, dim1])
# base = tf.reshape(base_grid, [-1])
#
# base_y0 = base + y0 * width
# base_y1 = base + y1 * width
# idx_a = base_y0 + x0
# idx_b = base_y1 + x0
# idx_c = base_y0 + x1
# idx_d = base_y1 + x1
#
# Ia = tf.gather(im_flat, idx_a)
# Ib = tf.gather(im_flat, idx_b)
# Ic = tf.gather(im_flat, idx_c)
# Id = tf.gather(im_flat, idx_d)
#
# warped_flat = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])
# warped = tf.reshape(warped_flat, [num_batch, height, width, channels])
#
# return warped
. Output only the next line. | im2_warped = image_warp(im2, flow_fw) |
Predict the next line after this snippet: <|code_start|>
class ImageWarpTest(tf.test.TestCase):
def _warp_test(self, first, second, flow, debug=False):
num_batch, height, width, channels = second.shape
second_ = tf.placeholder(tf.float32, shape=second.shape, name='im')
flow_ = tf.placeholder(tf.float32, shape=flow.shape, name='flow')
<|code_end|>
using the current file's imports:
import numpy as np
import tensorflow as tf
from ..core.image_warp import image_warp
and any relevant context from other files:
# Path: src/e2eflow/core/image_warp.py
# def image_warp(im, flow):
# """Performs a backward warp of an image using the predicted flow.
#
# Args:
# im: Batch of images. [num_batch, height, width, channels]
# flow: Batch of flow vectors. [num_batch, height, width, 2]
# Returns:
# warped: transformed image of the same shape as the input image.
# """
# with tf.variable_scope('image_warp'):
#
# num_batch, height, width, channels = tf.unstack(tf.shape(im))
# max_x = tf.cast(width - 1, 'int32')
# max_y = tf.cast(height - 1, 'int32')
# zero = tf.zeros([], dtype='int32')
#
# # We have to flatten our tensors to vectorize the interpolation
# im_flat = tf.reshape(im, [-1, channels])
# flow_flat = tf.reshape(flow, [-1, 2])
#
# # Floor the flow, as the final indices are integers
# # The fractional part is used to control the bilinear interpolation.
# flow_floor = tf.to_int32(tf.floor(flow_flat))
# bilinear_weights = flow_flat - tf.floor(flow_flat)
#
# # Construct base indices which are displaced with the flow
# pos_x = tf.tile(tf.range(width), [height * num_batch])
# grid_y = tf.tile(tf.expand_dims(tf.range(height), 1), [1, width])
# pos_y = tf.tile(tf.reshape(grid_y, [-1]), [num_batch])
#
# x = flow_floor[:, 0]
# y = flow_floor[:, 1]
# xw = bilinear_weights[:, 0]
# yw = bilinear_weights[:, 1]
#
# # Compute interpolation weights for 4 adjacent pixels
# # expand to num_batch * height * width x 1 for broadcasting in add_n below
# wa = tf.expand_dims((1 - xw) * (1 - yw), 1) # top left pixel
# wb = tf.expand_dims((1 - xw) * yw, 1) # bottom left pixel
# wc = tf.expand_dims(xw * (1 - yw), 1) # top right pixel
# wd = tf.expand_dims(xw * yw, 1) # bottom right pixel
#
# x0 = pos_x + x
# x1 = x0 + 1
# y0 = pos_y + y
# y1 = y0 + 1
#
# x0 = tf.clip_by_value(x0, zero, max_x)
# x1 = tf.clip_by_value(x1, zero, max_x)
# y0 = tf.clip_by_value(y0, zero, max_y)
# y1 = tf.clip_by_value(y1, zero, max_y)
#
# dim1 = width * height
# batch_offsets = tf.range(num_batch) * dim1
# base_grid = tf.tile(tf.expand_dims(batch_offsets, 1), [1, dim1])
# base = tf.reshape(base_grid, [-1])
#
# base_y0 = base + y0 * width
# base_y1 = base + y1 * width
# idx_a = base_y0 + x0
# idx_b = base_y1 + x0
# idx_c = base_y0 + x1
# idx_d = base_y1 + x1
#
# Ia = tf.gather(im_flat, idx_a)
# Ib = tf.gather(im_flat, idx_b)
# Ic = tf.gather(im_flat, idx_c)
# Id = tf.gather(im_flat, idx_d)
#
# warped_flat = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])
# warped = tf.reshape(warped_flat, [num_batch, height, width, channels])
#
# return warped
. Output only the next line. | inv_warped_second = image_warp(second_, flow_) |
Predict the next line after this snippet: <|code_start|> fn2 = os.path.join(dir_path, files[i + 1])
filenames.append((fn1, fn2))
random.seed(seed)
random.shuffle(filenames)
print("Training on {} frame pairs.".format(len(filenames)))
filenames_extended = []
for fn1, fn2 in filenames:
filenames_extended.append((fn1, fn2))
if swap_images:
filenames_extended.append((fn2, fn1))
shift = shift % len(filenames_extended)
filenames_extended = list(np.roll(filenames_extended, shift))
filenames_1, filenames_2 = zip(*filenames_extended)
filenames_1 = list(filenames_1)
filenames_2 = list(filenames_2)
with tf.variable_scope('train_inputs'):
image_1 = read_png_image(filenames_1)
image_2 = read_png_image(filenames_2)
if needs_crop:
#if center_crop:
# image_1 = tf.image.resize_image_with_crop_or_pad(image_1, height, width)
# image_2 = tf.image.resize_image_with_crop_or_pad(image_1, height, width)
#else:
<|code_end|>
using the current file's imports:
import os
import random
import numpy as np
import tensorflow as tf
from .augment import random_crop
and any relevant context from other files:
# Path: src/e2eflow/core/augment.py
# def random_crop(tensors, size, seed=None, name=None):
# """Randomly crops multiple tensors (of the same shape) to a given size.
#
# Each tensor is cropped in the same way."""
# with tf.name_scope(name, "random_crop", [size]) as name:
# size = tf.convert_to_tensor(size, dtype=tf.int32, name="size")
# if len(tensors) == 2:
# shape = tf.minimum(tf.shape(tensors[0]), tf.shape(tensors[1]))
# else:
# shape = tf.shape(tensors[0])
#
# limit = shape - size + 1
# offset = tf.random_uniform(
# tf.shape(shape),
# dtype=size.dtype,
# maxval=size.dtype.max,
# seed=seed) % limit
# results = []
# for tensor in tensors:
# result = tf.slice(tensor, offset, size)
# results.append(result)
# return results
. Output only the next line. | image_1, image_2 = random_crop([image_1, image_2], [height, width, 3]) |
Continue the code snippet: <|code_start|> eigenvalues = self.get_eig_array()
plt.clf()
if window is not None:
plt.ylim(window[0], window[1])
if self.get_number_of_spins() == 1:
for i in range(self.nbands):
band_i = eigenvalues[i, :] - self.get_fermi_level()
plt.plot(self.band_xs, band_i)
else:
for i in range(self.nbands):
band_i = eigenvalues[i, :, spin] - self.get_fermi_level()
plt.plot(self.band_xs, band_i)
plt.xlabel('K-points')
plt.ylabel('$Energy-E_{fermi} (eV)$')
plt.ylim(yrange)
plt.axhline(0, color='black', linestyle='--')
if self.special_kpts_names is not None:
plt.xticks(self.band_special_xs, self.special_kpts_names)
if output_filename is not None:
plt.savefig(output_filename)
if show:
plt.show()
def read_contcar(self, atoms, filename='CONTCAR'):
"""
read from contcar and set the positions and cellpars. Note that in vasp, "sort" is True. so read and !!!!unsort!!!!.
"""
<|code_end|>
. Use current file imports:
from pyDFTutils.vasp.vasp_utils import read_poscar_and_unsort
from ase.calculators.vasp import Vasp, Vasp2
from ase.dft.kpoints import get_bandpath
from os.path import join
from ase.utils import devnull, basestring
from pyDFTutils.ase_utils.symbol import symbol_number
from shutil import copyfile, move
import ase.calculators.vasp.create_input
import matplotlib.pyplot as plt
import os
import sys
import numpy as np
import tempfile
import ase.io
import socket
and context (classes, functions, or code) from other files:
# Path: pyDFTutils/vasp/vasp_utils.py
# def read_poscar_and_unsort(filename='CONTCAR'):
# """
# read poscar and unsort. return the symbols,positions and cell in unsorted order.
# """
# atoms = read_vasp(filename)
# symbols = get_unsorted(atoms.get_chemical_symbols())
# positions = get_unsorted(atoms.get_positions())
# cell = atoms.get_cell()
# return symbols, positions, cell
#
# Path: pyDFTutils/ase_utils/symbol.py
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
. Output only the next line. | symbols, positions, cell = read_poscar_and_unsort(filename=filename) |
Based on the snippet: <|code_start|>def read_OUTCAR_energy(outcar='./OUTCAR'):
"""
read energy with out entropy from OUTCAR
"""
[energy_free, energy_zero] = [0, 0]
if all:
energy_free = []
energy_zero = []
for line in open(outcar, 'r'):
# Free energy
if line.lower().startswith(' free energy toten'):
if all:
energy_free.append(float(line.split()[-2]))
else:
energy_free = float(line.split()[-2])
# Extrapolated zero point energy
if line.startswith(' energy without entropy'):
if all:
energy_zero.append(float(line.split()[-1]))
else:
energy_zero = float(line.split()[-1])
return energy_free
def read_OUTCAR_charges(poscar=None,
outcar='./OUTCAR',
orbital=None,
symnum=None):
poscar = os.path.join(os.path.split(outcar)[0], 'POSCAR')
atoms = read(poscar)
<|code_end|>
, predict the immediate next line with the help of imports:
from pyDFTutils.vasp.vasp_utils import read_poscar_and_unsort
from ase.calculators.vasp import Vasp, Vasp2
from ase.dft.kpoints import get_bandpath
from os.path import join
from ase.utils import devnull, basestring
from pyDFTutils.ase_utils.symbol import symbol_number
from shutil import copyfile, move
import ase.calculators.vasp.create_input
import matplotlib.pyplot as plt
import os
import sys
import numpy as np
import tempfile
import ase.io
import socket
and context (classes, functions, sometimes code) from other files:
# Path: pyDFTutils/vasp/vasp_utils.py
# def read_poscar_and_unsort(filename='CONTCAR'):
# """
# read poscar and unsort. return the symbols,positions and cell in unsorted order.
# """
# atoms = read_vasp(filename)
# symbols = get_unsorted(atoms.get_chemical_symbols())
# positions = get_unsorted(atoms.get_positions())
# cell = atoms.get_cell()
# return symbols, positions, cell
#
# Path: pyDFTutils/ase_utils/symbol.py
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
. Output only the next line. | sdict = symbol_number(atoms) |
Next line prediction: <|code_start|>
#!/usr/bin/env python
from __future__ import division, print_function, unicode_literals
def build_structure(name, mag='PM'):
return gen_primitive(name=name, latticeconstant=4, mag_order='PM')
def make_scf_input(atoms,
ecut=26,
xc='LDA',
is_metal=True,
spin_mode='PM',
pp_family='gbrv',
pp_labels={},
ldau_type=0,
Hubbard_U_dict={},
**kwargs):
"""
structure: ase atoms object.
"""
spin_mode_dict = {'PM': 'unpolarized', 'FM': 'polarized', 'AFM': 'afm'}
if spin_mode in spin_mode_dict:
spin_mode = spin_mode_dict[spin_mode]
<|code_end|>
. Use current file imports:
(import os
import abipy.data as abidata
import abipy.abilab as abilab
import abipy.flowtk as flowapi
from abipy.abilab import AbinitInput
from abipy.abilab import Structure
from ase.units import eV, Ha
from abipy.abio.factories import scf_input, ebands_input, dos_from_gsinput, ioncell_relax_from_gsinput, scf_for_phonons, phonons_from_gsinput, piezo_elastic_inputs_from_gsinput, scf_piezo_elastic_inputs, ebands_from_gsinput
from abipy.abio.inputs import AbinitInput
from flow import myAbinitInput
from pyDFTutils.abipy.input_utils import find_all_pp, set_Hubbard_U, set_spinat, to_abi_structure
from ase_utils3.cubic_perovskite import gen_primitive)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/abipy/input_utils.py
# def find_all_pp(obj, xc, family, label_dict={},pp_path=pp_path):
# symbols = []
# if isinstance(obj, collections.Iterable) and (
# not isinstance(obj, str)) and isinstance(obj[0], str):
# symbols = obj
# elif isinstance(obj, str) and os.path.isfile(obj):
# structure = Structure.as_structure(obj)
# symbols = set(structure.symbol_set)
# elif isinstance(obj, Structure):
# symbols = obj.symbol_set
# elif isinstance(obj, Atoms):
# for elem in obj.get_chemical_symbols():
# if elem not in symbols:
# symbols.append(elem)
# else:
# raise ValueError(
# 'obj should be one of these: list of chemical symbols| abipy structure file name| abipy structure| ase atoms.'
# )
# ppdict = OrderedDict()
# for elem in symbols:
# if elem not in ppdict:
# if elem in label_dict:
# label = label_dict
# else:
# label = ''
# ppdict[elem] = find_pp(elem, xc, family, label,pp_path=pp_path)
# return list(ppdict.values())
#
# def set_Hubbard_U(abi_inp, ldau_dict={}, ldau_type=1, unit='eV'):
# """
# set DFT+U parameters.
# """
# structure = abi_inp.structure
# symbols = structure.symbol_set
# luj_params = LdauParams(ldau_type, structure)
# for symbol in ldau_dict:
# if symbol in symbols:
# luj_params.luj_for_symbol(
# symbol,
# l=ldau_dict[symbol]['L'],
# u=ldau_dict[symbol]['U'],
# j=ldau_dict[symbol]['J'],
# unit=unit)
# u_vars = luj_params.to_abivars()
# abi_inp.set_vars(u_vars)
# return abi_inp
#
# def set_spinat(abi_inp, magmoms):
# """
# set initial spin configuration
# """
# sdict = None
# if len(magmoms) == 0:
# return abi_inp
# elif isinstance(magmoms[0], collections.Iterable):
# if len(magmoms[0]) == 3:
# sdict = {'spinat': magmoms}
# else:
# sdict = {'spinat': [[0, 0, m] for m in magmoms]}
# if sdict is None:
# raise ValueError('magmoms should be 1D array or 3d array')
# abi_inp.set_vars(sdict)
# return abi_inp
#
# def to_abi_structure(obj,magmoms=False):
# ms=None
# if isinstance(obj, str) and os.path.isfile(obj):
# structure = Structure.as_structure(obj)
# elif isinstance(obj, Structure):
# structure = obj
# elif isinstance(obj, Atoms):
# #cell=obj.get_cell()
# #acell0=np.linalg.norm(cell[0])
# #acell1=np.linalg.norm(cell[1])
# #acell2=np.linalg.norm(cell[2])
# #cell0=cell[0]/acell0
# #cell1=cell[1]/acell1
# #cell2=cell[2]/acell2
# #acell=[acell0, acell1, acell2]
# #rprim=[cell0, cell1, cell2]
# #xred=obj.get_scaled_positions()
# #znucl=list(set(obj.get_atomic_numbers()))
# #ntypat=len(znucl)
# #typat=[]
# #for z in obj.get_atomic_numbers():
# # for i,n in enumerate(znucl):
# # if z==n:
# # typat.append(i)
# #structure = Structure.from_abivars(acell=acell, rprim=rprim, typat=typat, xred=xred, ntypat=ntypat, znucl=znucl)
# structure = Structure.from_ase_atoms(obj)
# if magmoms:
# ms=obj.get_initial_magnetic_moments()
# else:
# raise ValueError(
# 'obj should be one of these: abipy structure file name| abipy structure| ase atoms.'
# )
# if magmoms:
# return structure,ms
# else:
# return structure
. Output only the next line. | structure, magmoms = to_abi_structure(atoms, magmoms=True) |
Given snippet: <|code_start|> freq = evals[i][j]
if label:
mode = label_Gamma(
evec=evec, masses=self.atoms.get_masses())
Gamma_mode_names.append(mode)
else:
Gamma_mode_names.append('')
Gamma_mode_freqs.append(freq)
Gamma_mode_evecs.append(np.real(evec))
return Gamma_mode_freqs, Gamma_mode_names, Gamma_mode_evecs
if Gamma_mode_names == []:
print("Warning: No Gamma point found in qpoints.\n")
return Gamma_mode_freqs, Gamma_mode_names, Gamma_mode_evecs
def label_zone_boundary_all(self, qpoints, evals, evecs, label=True):
mode_dict = {}
qdict = {'X': (0, 0.5, 0.0), 'M': (0.5, 0.5, 0), 'R': (0.5, 0.5, 0.5)}
for i, qpt in enumerate(qpoints):
for qname in qdict:
if np.isclose(qpt, qdict[qname], rtol=1e-5, atol=1e-3).all():
mode_freqs = []
mode_names = []
mode_evecs = []
#print "===================================="
#print qname
evecq = evecs[i]
for j, evec in enumerate(evecq.T):
freq = evals[i][j]
mode_freqs.append(freq)
if label:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import matplotlib.pyplot as plt
from ase.data import chemical_symbols
from abipy.abilab import abiopen
from pyDFTutils.perovskite.perovskite_mode import label_zone_boundary, label_Gamma
from ase.units import Ha
from spglib import spglib
and context:
# Path: pyDFTutils/perovskite/perovskite_mode.py
# def label_zone_boundary(qname,
# phdisp=None,
# masses=None,
# evec=None,
# notation='IR'):
# IR_translation = {}
#
# IR_translation['Gamma'] = {
# '$\Delta_1$': r'$\Gamma_4^-$',
# '$\Delta_2$': r'',
# '$\Delta_5$': r'',
# }
#
# IR_translation['R'] = {
# r'$\Gamma_2\prime$': '$R_2^-$',
# r'$\Gamma_{12}\prime$': '$R_3^-$',
# r'$\Gamma_{25}$': '$R_5^-$',
# r'$\Gamma_{25}\prime$': '$R_5^+$',
# r'$\Gamma_{15}$': '$R_4^-$',
# }
#
# IR_translation['X'] = {
# '$M_1$': '$X_1^+$',
# '$M_2\prime$': '$X_3^-$',
# '$M_3$': '$X_2^+$',
# '$M_5$': '$X_5^+$',
# '$M_5\prime$': '$X_5^-$',
# }
#
# IR_translation['M'] = {
# '$M_1$': '$M_1^+$',
# '$M_2$': '$M_3^+$',
# '$M_3$': '$M_2^+$',
# '$M_4$': '$M_4^+$',
# '$M_2\prime$': '$M_3^-$',
# '$M_3\prime$': '$M_2^-$',
# '$M_5$': '$M_5^+$',
# '$M_5\prime$': '$M_5^-$',
# }
#
# if phdisp is not None or masses is not None:
# evec = np.array(phdisp) * np.sqrt(np.kron(masses, [1, 1, 1]))
# evec = np.real(evec) / np.linalg.norm(evec)
#
# mode = None
# for m in IR_dict[qname]:
# mvec = np.real(m)
# mvec = mvec / np.linalg.norm(mvec)
# evec = evec / np.linalg.norm(evec)
# p = np.abs(np.dot(np.real(evec), mvec))
# if p > 0.4: #1.0 / np.sqrt(2):
# print("-------------")
# #print("Found! p= %s" % p)
# #print("eigen vector: ", nmode._make(mvec))
# if notation.lower() == 'cowley':
# mode = IR_dict[qname][m]
# elif notation.upper() == 'IR':
# #print(IR_translation[qname])
# mode = IR_translation[qname][IR_dict[qname][m]]
# elif notation.lower() == 'both':
# mode = (IR_dict[qname][m],
# IR_translation[qname][IR_dict[qname][m]])
# else:
# raise ValueError('notation should be Cowley|IR|both')
# #print("mode: ", mode, m)
# if mode is None:
# print("==============")
# print("eigen vector: ", nmode._make(evec))
# return mode
#
# def label_Gamma(phdisp=None, masses=None, evec=None):
# if phdisp is not None and masses is not None:
# evec = np.array(phdisp) * np.sqrt(np.kron(masses, [1, 1, 1]))
# evec = np.real(evec) / np.linalg.norm(evec)
#
# basis_dict = mass_to_Gamma_basis_3d(masses, eigen_type='eigen_vector')
# mode = None
#
# for m in basis_dict:
# mvec = np.real(m)
# mvec = mvec / np.linalg.norm(mvec)
# evec = evec / np.linalg.norm(evec)
# p = np.abs(np.dot(np.real(evec), mvec))
# if p > 0.5: #1.0 / np.sqrt(2):
# mode = basis_dict[m]
# if mode is None:
# print("==============")
# print("eigen vector: ", nmode._make(evec))
# return mode
which might include code, classes, or functions. Output only the next line. | mode = label_zone_boundary(qname, evec=evec) |
Predict the next line after this snippet: <|code_start|> def get_gamma_modes(self):
"""
return (Freqs, names, evecs)
"""
return self.phonon_mode_freqs['Gamma'], self.phonon_mode_names['Gamma'], self.phonon_mode_evecs['Gamma'],
def get_gamma_mode(self, mode_name):
"""
return the frequencies of mode name.
"""
ibranches = []
freqs = []
for imode, mode in enumerate(zip(self.phonon_mode_freqs['Gamma'], self.phonon_mode_names['Gamma'])):
freq, mname = mode
if mname == mode_name:
ibranches.append(imode)
freqs.append(freq)
return ibranches, freqs
def label_Gamma_all(self, qpoints, evals, evecs, label=True):
Gamma_mode_freqs = []
Gamma_mode_names = []
Gamma_mode_evecs = []
for i, qpt in enumerate(qpoints):
if np.isclose(qpt, [0, 0, 0], rtol=1e-5, atol=1e-3).all():
evecq = evecs[i]
for j, evec in enumerate(evecq.T):
freq = evals[i][j]
if label:
<|code_end|>
using the current file's imports:
import os
import numpy as np
import matplotlib.pyplot as plt
from ase.data import chemical_symbols
from abipy.abilab import abiopen
from pyDFTutils.perovskite.perovskite_mode import label_zone_boundary, label_Gamma
from ase.units import Ha
from spglib import spglib
and any relevant context from other files:
# Path: pyDFTutils/perovskite/perovskite_mode.py
# def label_zone_boundary(qname,
# phdisp=None,
# masses=None,
# evec=None,
# notation='IR'):
# IR_translation = {}
#
# IR_translation['Gamma'] = {
# '$\Delta_1$': r'$\Gamma_4^-$',
# '$\Delta_2$': r'',
# '$\Delta_5$': r'',
# }
#
# IR_translation['R'] = {
# r'$\Gamma_2\prime$': '$R_2^-$',
# r'$\Gamma_{12}\prime$': '$R_3^-$',
# r'$\Gamma_{25}$': '$R_5^-$',
# r'$\Gamma_{25}\prime$': '$R_5^+$',
# r'$\Gamma_{15}$': '$R_4^-$',
# }
#
# IR_translation['X'] = {
# '$M_1$': '$X_1^+$',
# '$M_2\prime$': '$X_3^-$',
# '$M_3$': '$X_2^+$',
# '$M_5$': '$X_5^+$',
# '$M_5\prime$': '$X_5^-$',
# }
#
# IR_translation['M'] = {
# '$M_1$': '$M_1^+$',
# '$M_2$': '$M_3^+$',
# '$M_3$': '$M_2^+$',
# '$M_4$': '$M_4^+$',
# '$M_2\prime$': '$M_3^-$',
# '$M_3\prime$': '$M_2^-$',
# '$M_5$': '$M_5^+$',
# '$M_5\prime$': '$M_5^-$',
# }
#
# if phdisp is not None or masses is not None:
# evec = np.array(phdisp) * np.sqrt(np.kron(masses, [1, 1, 1]))
# evec = np.real(evec) / np.linalg.norm(evec)
#
# mode = None
# for m in IR_dict[qname]:
# mvec = np.real(m)
# mvec = mvec / np.linalg.norm(mvec)
# evec = evec / np.linalg.norm(evec)
# p = np.abs(np.dot(np.real(evec), mvec))
# if p > 0.4: #1.0 / np.sqrt(2):
# print("-------------")
# #print("Found! p= %s" % p)
# #print("eigen vector: ", nmode._make(mvec))
# if notation.lower() == 'cowley':
# mode = IR_dict[qname][m]
# elif notation.upper() == 'IR':
# #print(IR_translation[qname])
# mode = IR_translation[qname][IR_dict[qname][m]]
# elif notation.lower() == 'both':
# mode = (IR_dict[qname][m],
# IR_translation[qname][IR_dict[qname][m]])
# else:
# raise ValueError('notation should be Cowley|IR|both')
# #print("mode: ", mode, m)
# if mode is None:
# print("==============")
# print("eigen vector: ", nmode._make(evec))
# return mode
#
# def label_Gamma(phdisp=None, masses=None, evec=None):
# if phdisp is not None and masses is not None:
# evec = np.array(phdisp) * np.sqrt(np.kron(masses, [1, 1, 1]))
# evec = np.real(evec) / np.linalg.norm(evec)
#
# basis_dict = mass_to_Gamma_basis_3d(masses, eigen_type='eigen_vector')
# mode = None
#
# for m in basis_dict:
# mvec = np.real(m)
# mvec = mvec / np.linalg.norm(mvec)
# evec = evec / np.linalg.norm(evec)
# p = np.abs(np.dot(np.real(evec), mvec))
# if p > 0.5: #1.0 / np.sqrt(2):
# mode = basis_dict[m]
# if mode is None:
# print("==============")
# print("eigen vector: ", nmode._make(evec))
# return mode
. Output only the next line. | mode = label_Gamma( |
Given the code snippet: <|code_start|> )
#phbst.plot_phbands()
qpoints = phbst.qpoints.frac_coords
print qpoints
nqpts = len(qpoints)
nbranch = 3 * len(numbers)
evals = np.zeros([nqpts, nbranch])
evecs = np.zeros([nqpts, nbranch, nbranch], dtype='complex128')
m = np.sqrt(np.kron(masses,[1,1,1]))
#positions=np.kron(scaled_positions,[1,1,1])
for iqpt, qpt in enumerate(qpoints):
for ibranch in range(nbranch):
phmode = phbst.get_phmode(qpt, ibranch)
evals[iqpt, ibranch] = phmode.freq
evec=phmode.displ_cart *m
phase = [np.exp(-2j*np.pi*np.dot(pos,qpt)) for pos in scaled_positions]
phase = np.kron(phase,[1,1,1])
evec*=phase
evec /= np.linalg.norm(evec)
evecs[iqpt,:,ibranch] = evec
uf = phonon_unfolder(atoms,sc_mat,evecs,qpoints,phase=False)
weights = uf.get_weights()
print weights.min(), weights.max()
x=np.arange(nqpts)
freqs=evals
names = ['$\Gamma$', 'X', 'W', '$\Gamma$', 'L']
#ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*33.356,weights[:,:].T*0.98+0.01,xticks=[names,X],axis=ax)
<|code_end|>
, generate the next line using the imports in this file:
import abipy.abilab as abilab
import numpy as np
import matplotlib.pyplot as plt
from ase.build import bulk
from ase.dft.kpoints import get_special_points, bandpath
from pyDFTutils.unfolding.phonon_unfolder import phonon_unfolder
from pyDFTutils.phonon.plotphon import plot_band_weight
and context (functions, classes, or occasionally code) from other files:
# Path: pyDFTutils/phonon/plotphon.py
# def plot_band_weight(kslist,
# ekslist,
# wkslist=None,
# efermi=0,
# yrange=None,
# output=None,
# style='alpha',
# color='blue',
# axis=None,
# width=2,
# xticks=None,
# title=None):
# if axis is None:
# fig, a = plt.subplots()
# plt.tight_layout(pad=2.19)
# plt.axis('tight')
# plt.gcf().subplots_adjust(left=0.17)
# else:
# a = axis
# if title is not None:
# a.set_title(title)
#
# xmax = max(kslist[0])
# if yrange is None:
# yrange = (np.array(ekslist).flatten().min() - 66,
# np.array(ekslist).flatten().max() + 66)
#
# if wkslist is not None:
# for i in range(len(kslist)):
# x = kslist[i]
# y = ekslist[i]
# lwidths = np.array(wkslist[i]) * width
# #lwidths=np.ones(len(x))
# points = np.array([x, y]).T.reshape(-1, 1, 2)
# segments = np.concatenate([points[:-1], points[1:]], axis=1)
# if style == 'width':
# lc = LineCollection(segments, linewidths=lwidths, colors=color)
# elif style == 'alpha':
# lc = LineCollection(
# segments,
# linewidths=[2] * len(x),
# colors=[
# colorConverter.to_rgba(
# color, alpha=np.abs(lwidth / (width + 0.001)))
# for lwidth in lwidths
# ])
#
# a.add_collection(lc)
# plt.ylabel('Frequency (cm$^{-1}$)')
# if axis is None:
# for ks, eks in zip(kslist, ekslist):
# plt.plot(ks, eks, color='gray', linewidth=0.001)
# a.set_xlim(0, xmax)
# a.set_ylim(yrange)
# if xticks is not None:
# plt.xticks(xticks[1], xticks[0])
# for x in xticks[1]:
# plt.axvline(x, color='gray', linewidth=0.5)
# if efermi is not None:
# plt.axhline(linestyle='--', color='black')
# return a
. Output only the next line. | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*27*33.356,weights[:,:].T*0.98+0.01,xticks=[names,[1,2,3,4,5]],style='alpha') |
Predict the next line for this snippet: <|code_start|> # DDK
self.add_dataset(
iscf=-3,
getwfk=1,
kptopt=2,
rfelfd=2,
nqpt=1,
rfphon=0,
tolvrs=0,
tolwfr=tolwfr * 10,
qpt='0 0 0')
# Gamma, efield and/or strain and phonon
self.add_dataset(
getwfk=1,
getddk=self.ndtset,
kptopt=2,
rfelfd=3 * int(efield),
rfstrs=3 * strain,
nqpt=1,
iscf=7,
qpt='0 0 0',
rfphon=1,
rfatpol="%s %s" % (1, len(atoms)),
rfdir='1 1 1',
tolvrs=tolvrs,
toldfe=0,
prtwf=prtwf,
prtbbb=prtbbb)
# phonon
if isinstance(qpts[0], int):
<|code_end|>
with the help of current file imports:
import os
import shutil
import copy
import numpy as np
import subprocess
import json
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
from pyDFTutils.abinit.abinit_io import get_efermi, GSR, get_kpoints
and context from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
#
# Path: pyDFTutils/abinit/abinit_io.py
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# class GSR(object):
# def __init__(self,fname):
# self._fname=fname
# self._file = netcdf_file(self._fname)
# self._variables=self._file.variables
#
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
, which may contain function names, class names, or code. Output only the next line. | qpoints = get_ir_kpts(atoms, qpts) |
Continue the code snippet: <|code_start|> if 'nspden' in self.parameters and self.parameters['nspden']==2:
wannier_input.write_input(prefix=self.prefix, spin=True)
else:
wannier_input.write_input(prefix=self.prefix, spin=False)
self.calculate(atoms=atoms)
wann_dir=join(self.workdir, 'Wannier')
if not os.path.exists(wann_dir):
os.mkdir(wann_dir)
for fname in [
'abinit.in', 'abinit.txt', 'abinit.log', 'abinit.ase',
'abinito_DOS'
]:
if os.path.exists(join(self.workdir, fname)):
shutil.copy(fname, wann_dir)
return atoms
def calculate_phonon(self,
atoms,
ddk=True,
efield=True,
strain=True,
qpts=[2, 2, 2],
tolwfr=1e-23,
tolvrs=1e-12,
prtwf=0,
postproc=True,
ifcout=10240,
rfasr=1,
plot_band=True,
<|code_end|>
. Use current file imports:
import os
import shutil
import copy
import numpy as np
import subprocess
import json
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
from pyDFTutils.abinit.abinit_io import get_efermi, GSR, get_kpoints
and context (classes, functions, or code) from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
#
# Path: pyDFTutils/abinit/abinit_io.py
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# class GSR(object):
# def __init__(self,fname):
# self._fname=fname
# self._file = netcdf_file(self._fname)
# self._variables=self._file.variables
#
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
. Output only the next line. | kpath=cubic_kpath()[0], |
Predict the next line after this snippet: <|code_start|> if not self.get_spin_polarized():
magmom = 0.0
else: # only for spinpolarized system Magnetisation is printed
for line in open(join(self.workdir,self.label + '.txt')):
if line.find('Magnetisation') != -1: # last one
magmom = float(line.split('=')[-1].strip())
return magmom
def get_fermi_level(self):
return self.read_fermi()
def get_eigenvalues(self, kpt=0, spin=0):
return self.get_kpts_info(kpt, spin, 'eigenvalues')
def get_occupations(self, kpt=0, spin=0):
return self.get_kpts_info(kpt, spin, 'occupations')
def read_fermi(self):
"""Method that reads Fermi energy in Hartree from the output file
and returns it in eV"""
E_f = None
filename = join(self.workdir, self.label + '.txt')
text = open(filename).read().lower()
assert 'error' not in text
for line in iter(text.split('\n')):
if line.rfind('fermi (or homo) energy (hartree) =') > -1:
E_f = float(line.split('=')[1].strip().split()[0])
return E_f * Hartree
<|code_end|>
using the current file's imports:
import os
import shutil
import copy
import numpy as np
import subprocess
import json
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
from pyDFTutils.abinit.abinit_io import get_efermi, GSR, get_kpoints
and any relevant context from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
#
# Path: pyDFTutils/abinit/abinit_io.py
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# class GSR(object):
# def __init__(self,fname):
# self._fname=fname
# self._file = netcdf_file(self._fname)
# self._variables=self._file.variables
#
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
. Output only the next line. | def get_efermi(self): |
Predict the next line for this snippet: <|code_start|> des = os.path.join(wdir[i], 'abiniti_WFK')
if os.path.exists(des):
os.remove(des)
os.symlink(src, des)
self.set(**relax_params)
self.set(
irdwfk=1,
berryopt=16,
red_dfield=' '.join(map(str, dfield[i])),
red_efield=' '.join(map(str, efield[i])))
atoms = self.relax_calculation(atoms)
os.chdir(cwd)
return atoms
def wannier_calculation(self, atoms, wannier_input, **kwargs):
nkpts = np.product(self.parameters['kpts'])
self.set(
ntime=0,
toldfe=0.0,
w90iniprj=2,
prtwant=2,
paral_kgb=0,
kptopt=3,
istwfk="%s*1" % nkpts)
self.set(**kwargs)
self.dry_run(atoms=atoms)
<|code_end|>
with the help of current file imports:
import os
import shutil
import copy
import numpy as np
import subprocess
import json
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
from pyDFTutils.abinit.abinit_io import get_efermi, GSR, get_kpoints
and context from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
#
# Path: pyDFTutils/abinit/abinit_io.py
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# class GSR(object):
# def __init__(self,fname):
# self._fname=fname
# self._file = netcdf_file(self._fname)
# self._variables=self._file.variables
#
# def get_efermi(self):
# return float(self._variables['e_fermie'].data)*Ha
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
#
# def get_kpoints(self):
# return self._variables['reduced_coordinates_of_kpoints'].data
, which may contain function names, class names, or code. Output only the next line. | kpts=self.get_kpoints() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
from __future__ import division, print_function, unicode_literals
def build_structure(name, mag='PM'):
return gen_primitive(name=name, latticeconstant=4, mag_order='PM')
def make_scf_input(atoms,
ecut=26,
xc='LDA',
is_metal=True,
spin_mode='PM',
pp_family='gbrv',
pp_labels={},
ldau_type=0,
Hubbard_U_dict={},
**kwargs):
"""
structure: ase atoms object.
"""
spin_mode_dict = {'PM': 'unpolarized', 'FM': 'polarized', 'AFM': 'afm'}
if spin_mode in spin_mode_dict:
spin_mode = spin_mode_dict[spin_mode]
<|code_end|>
, predict the next line using imports from the current file:
import os
import abipy.data as abidata
import abipy.abilab as abilab
import abipy.flowtk as flowapi
from abipy.abilab import AbinitInput
from abipy.abilab import Structure
from ase.units import eV, Ha
from abipy.abio.factories import scf_input, ebands_input, dos_from_gsinput, ioncell_relax_from_gsinput, scf_for_phonons, phonons_from_gsinput, piezo_elastic_inputs_from_gsinput, scf_piezo_elastic_inputs, ebands_from_gsinput
from pyDFTutils.abipy.input_utils import find_all_pp, set_Hubbard_U, set_spinat, to_abi_structure
from ase_utils3.cubic_perovskite import gen_primitive
and context including class names, function names, and sometimes code from other files:
# Path: pyDFTutils/abipy/input_utils.py
# def find_all_pp(obj, xc, family, label_dict={},pp_path=pp_path):
# symbols = []
# if isinstance(obj, collections.Iterable) and (
# not isinstance(obj, str)) and isinstance(obj[0], str):
# symbols = obj
# elif isinstance(obj, str) and os.path.isfile(obj):
# structure = Structure.as_structure(obj)
# symbols = set(structure.symbol_set)
# elif isinstance(obj, Structure):
# symbols = obj.symbol_set
# elif isinstance(obj, Atoms):
# for elem in obj.get_chemical_symbols():
# if elem not in symbols:
# symbols.append(elem)
# else:
# raise ValueError(
# 'obj should be one of these: list of chemical symbols| abipy structure file name| abipy structure| ase atoms.'
# )
# ppdict = OrderedDict()
# for elem in symbols:
# if elem not in ppdict:
# if elem in label_dict:
# label = label_dict
# else:
# label = ''
# ppdict[elem] = find_pp(elem, xc, family, label,pp_path=pp_path)
# return list(ppdict.values())
#
# def set_Hubbard_U(abi_inp, ldau_dict={}, ldau_type=1, unit='eV'):
# """
# set DFT+U parameters.
# """
# structure = abi_inp.structure
# symbols = structure.symbol_set
# luj_params = LdauParams(ldau_type, structure)
# for symbol in ldau_dict:
# if symbol in symbols:
# luj_params.luj_for_symbol(
# symbol,
# l=ldau_dict[symbol]['L'],
# u=ldau_dict[symbol]['U'],
# j=ldau_dict[symbol]['J'],
# unit=unit)
# u_vars = luj_params.to_abivars()
# abi_inp.set_vars(u_vars)
# return abi_inp
#
# def set_spinat(abi_inp, magmoms):
# """
# set initial spin configuration
# """
# sdict = None
# if len(magmoms) == 0:
# return abi_inp
# elif isinstance(magmoms[0], collections.Iterable):
# if len(magmoms[0]) == 3:
# sdict = {'spinat': magmoms}
# else:
# sdict = {'spinat': [[0, 0, m] for m in magmoms]}
# if sdict is None:
# raise ValueError('magmoms should be 1D array or 3d array')
# abi_inp.set_vars(sdict)
# return abi_inp
#
# def to_abi_structure(obj,magmoms=False):
# ms=None
# if isinstance(obj, str) and os.path.isfile(obj):
# structure = Structure.as_structure(obj)
# elif isinstance(obj, Structure):
# structure = obj
# elif isinstance(obj, Atoms):
# #cell=obj.get_cell()
# #acell0=np.linalg.norm(cell[0])
# #acell1=np.linalg.norm(cell[1])
# #acell2=np.linalg.norm(cell[2])
# #cell0=cell[0]/acell0
# #cell1=cell[1]/acell1
# #cell2=cell[2]/acell2
# #acell=[acell0, acell1, acell2]
# #rprim=[cell0, cell1, cell2]
# #xred=obj.get_scaled_positions()
# #znucl=list(set(obj.get_atomic_numbers()))
# #ntypat=len(znucl)
# #typat=[]
# #for z in obj.get_atomic_numbers():
# # for i,n in enumerate(znucl):
# # if z==n:
# # typat.append(i)
# #structure = Structure.from_abivars(acell=acell, rprim=rprim, typat=typat, xred=xred, ntypat=ntypat, znucl=znucl)
# structure = Structure.from_ase_atoms(obj)
# if magmoms:
# ms=obj.get_initial_magnetic_moments()
# else:
# raise ValueError(
# 'obj should be one of these: abipy structure file name| abipy structure| ase atoms.'
# )
# if magmoms:
# return structure,ms
# else:
# return structure
. Output only the next line. | structure, magmoms = to_abi_structure(atoms, magmoms=True) |
Continue the code snippet: <|code_start|> #subplot_number=int(str(len(xs))+'1'+str(i+1))
nplot=len(xs)
if i==0:
axes.append(plt.subplot(nplot,1,i+1))
else:
axes.append(plt.subplot(nplot,1,i+1,sharex=axes[0]))
ys=yss[i]
label=labels[i]
for y in ys:
plt.xlabel('Energy (eV)')
plt.ylabel('%s'%label)
axes[i].plot(x,y)
axes[i]
plt.xlim(xmin,xmax)
try:
plt.ylim(ymin[i],ymax[i])
plt.yticks(np.arange(ymin[i],ymax[i],(ymax[i]-ymin[i])/3.0))
except Exception:
plt.ylim(ymin,ymax)
plt.yticks(np.arange(ymin,ymax,(ymax-ymin)/3.0))
plt.legend()
plt.show()
def plot_all_ldos(filename='DOSCAR',ispin=2,ymin=-2.0,ymax=2.0,xmin=-15.0,xmax=5.0,element_types=None, has_f=False):
"""
plot the local dos of all atoms.
"""
symdict=get_symdict()
if element_types is not None:
<|code_end|>
. Use current file imports:
from ase.io import read
from ase.calculators.vasp import VaspDos
from os.path import join
from shutil import copyfile
from scipy import trapz,integrate
from pyDFTutils.ase_utils.symbol import symnum_to_sym
from .vasp_utils import get_symdict
from matplotlib.ticker import FormatStrFormatter
from collections import OrderedDict,Iterable
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
import os
import copy
and context (classes, functions, or code) from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
#
# Path: pyDFTutils/vasp/vasp_utils.py
# def get_symdict(filename='POSCAR', atoms=None):
# """
# get a symbol_number: index dict.
# """
# if filename is None and atoms is not None:
# syms = atoms.get_chemical_symbols()
# elif filename is not None and atoms is None:
# syms = read(filename).get_chemical_symbols()
#
# symdict = symbol_number(syms)
# return symdict
. Output only the next line. | atom_nums=[x for x in list(symdict.keys()) if symnum_to_sym(x) in element_types] |
Next line prediction: <|code_start|> line_num=6
for line in dos_text:
line_num +=1
if line_num >= nbands+6:
break
e,dos_up,dos_down,idos_up,idos_down=[float(fstr) for fstr in line.split()]
e_norm=e-efermi
if e_norm< epmax and e_norm > epmin:
e_array.append(e_norm)
dos_up_array.append(dos_up)
dos_down_array.append(-dos_down)
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
fig=plt.figure()
tspin_splt=fig.add_subplot(111)
tspin_splt.axvline(0,color='black')
tspin_splt.grid(True)
plt.plot(e_array,dos_up_array,label="Spin up")
plt.plot(e_array,dos_down_array,label="Spin down")
plt.legend()
if output is None:
plt.show()
else:
plt.savefig(output)
plt.close()
def write_all_sum_dos(output='sum_dos.txt',nospin_output='sum_dos_nospin.txt',eg_polar_output='eg_polor.txt',erange=None):
mydos=MyVaspDos()
orbs=mydos.get_orbital_names()
<|code_end|>
. Use current file imports:
(from ase.io import read
from ase.calculators.vasp import VaspDos
from os.path import join
from shutil import copyfile
from scipy import trapz,integrate
from pyDFTutils.ase_utils.symbol import symnum_to_sym
from .vasp_utils import get_symdict
from matplotlib.ticker import FormatStrFormatter
from collections import OrderedDict,Iterable
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
import os
import copy)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
#
# Path: pyDFTutils/vasp/vasp_utils.py
# def get_symdict(filename='POSCAR', atoms=None):
# """
# get a symbol_number: index dict.
# """
# if filename is None and atoms is not None:
# syms = atoms.get_chemical_symbols()
# elif filename is not None and atoms is None:
# syms = read(filename).get_chemical_symbols()
#
# symdict = symbol_number(syms)
# return symdict
. Output only the next line. | symdict=get_symdict() |
Continue the code snippet: <|code_start|> # DDK
self.add_dataset(
iscf=-3,
getwfk=1,
kptopt=2,
rfelfd=2,
nqpt=1,
rfphon=0,
tolvrs=0,
tolwfr=tolwfr * 10,
qpt='0 0 0')
# Gamma, efield and/or strain and phonon
self.add_dataset(
getwfk=1,
getddk=self.ndtset,
kptopt=2,
rfelfd=3 * int(efield),
rfstrs=3 * strain,
nqpt=1,
iscf=7,
qpt='0 0 0',
rfphon=1,
rfatpol="%s %s" % (1, len(atoms)),
rfdir='1 1 1',
tolvrs=tolvrs,
toldfe=0,
prtwf=prtwf,
prtbbb=prtbbb)
# phonon
if isinstance(qpts[0], int):
<|code_end|>
. Use current file imports:
import os
import shutil
import numpy as np
import subprocess
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
and context (classes, functions, or code) from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
. Output only the next line. | qpoints = get_ir_kpts(atoms, qpts) |
Given the code snippet: <|code_start|> prtwant=2,
paral_kgb=0,
kptopt=3,
istwfk="%s*1" % nkpts)
self.set(**kwargs)
wannier_input.write_input()
self.calculate(atoms=atoms, )
if not os.path.exists('Wannier'):
os.mkdir('Wannier')
for fname in [
'abinit.in', 'abinit.txt', 'abinit.log', 'abinit.ase',
'abinito_DOS'
]:
if os.path.exists(fname):
shutil.copy(fname, 'Wannier')
return atoms
def calculate_phonon(self,
atoms,
ddk=True,
efield=True,
strain=True,
qpts=[2, 2, 2],
tolwfr=1e-23,
tolvrs=1e-12,
prtwf=0,
postproc=True,
ifcout=10240,
rfasr=1,
plot_band=True,
<|code_end|>
, generate the next line using the imports in this file:
import os
import shutil
import numpy as np
import subprocess
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
and context (functions, classes, or occasionally code) from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
. Output only the next line. | kpath=cubic_kpath()[0], |
Predict the next line after this snippet: <|code_start|> """
self.energy=(self._kweights*(self._occupations*self._eigenvals)).sum()
def get_free_energy(self):
pass
#raise NotImplementedError
def get_projection(self,orb,spin=0):
"""
get the projection to nth orb.
:param orb: the index of the orbital.
:param spin: if spin polarized, 0 or 1
:returns: eigenvecs[iband,ikpt]
"""
if self._nspin==2:
return self._eigenvecs[:,:,orb,spin]
else:
return self._eigenvecs[:,:,orb]
def plot_projection(self,orb,spin=0,color='blue',axis=None):
"""
plot the projection of the band to the basis
"""
kslist=[list(range(len(self._kpts)))]*self._norb
ekslist=self._eigenvals
wkslist=np.abs(self.get_projection(orb,spin=spin))
#fig,a = plt.subplots()
<|code_end|>
using the current file's imports:
from pythtb import tb_model,w90
from ase.calculators.interface import Calculator,DFTCalculator
from ase.dft.dos import DOS
from ase.dft.kpoints import monkhorst_pack
from occupations import Occupations
from pyDFTutils.wannier90.band_plot import plot_band_weight
import numpy as np
import matplotlib.pyplot as plt
and any relevant context from other files:
# Path: pyDFTutils/wannier90/band_plot.py
# def plot_band_weight(kslist,ekslist,wkslist=None,efermi=None,yrange=None,output=None,style='alpha',color='blue',axis=None,width=10,xticks=None):
# if axis is None:
# fig,a = plt.subplots()
# else:
# a=axis
#
# xmax=max(kslist[0])
# if yrange is None:
# yrange=(np.array(ekslist).flatten().min()-0.66,np.array(ekslist).flatten().max()+0.66)
#
# if wkslist is not None:
# for i in range(len(kslist)):
# x=kslist[i]
# y=ekslist[i]
# lwidths=np.array(wkslist[i])*width
# #lwidths=np.ones(len(x))
# points = np.array([x, y]).T.reshape(-1, 1, 2)
# segments = np.concatenate([points[:-1], points[1:]], axis=1)
# if style=='width':
# lc = LineCollection(segments, linewidths=lwidths,colors=color)
# elif style=='alpha':
# lc = LineCollection(segments,linewidths=[4]*len(x), colors=[colorConverter.to_rgba(color,alpha=lwidth/(width+0.001)) for lwidth in lwidths])
#
# a.add_collection(lc)
# if axis is None:
# for ks , eks in zip(kslist,ekslist):
# plt.plot(ks,eks,color='gray')
# a.set_xlim(0,xmax)
# a.set_ylim(yrange)
# if xticks is not None:
# plt.xticks(xticks[1],xticks[0])
# if efermi is not None:
# plt.axhline(linestyle='--',color='black')
# return a
. Output only the next line. | return plot_band_weight(kslist,ekslist,wkslist=wkslist,efermi=None,yrange=None,output=None,style='alpha',color=color,axis=axis,width=10,xticks=None) |
Using the snippet: <|code_start|> qptbounds=kpath_bounds,
)
#phbst.plot_phbands()
qpoints = phbst.qpoints.frac_coords
nqpts = len(qpoints)
nbranch = 3 * len(numbers)
evals = np.zeros([nqpts, nbranch])
evecs = np.zeros([nqpts, nbranch, nbranch], dtype='complex128')
m = np.sqrt(np.kron(masses,[1,1,1]))
#positions=np.kron(scaled_positions,[1,1,1])
for iqpt, qpt in enumerate(qpoints):
for ibranch in range(nbranch):
phmode = phbst.get_phmode(qpt, ibranch)
evals[iqpt, ibranch] = phmode.freq
#evec=phmode.displ_cart *m
#phase = [np.exp(-2j*np.pi*np.dot(pos,qpt)) for pos in scaled_positions]
#phase = np.kron(phase,[1,1,1])
#evec*=phase
#evec /= np.linalg.norm(evec)
evec=displacement_cart_to_evec(phmode.displ_cart, masses, scaled_positions, qpoint=qpt, add_phase=True)
evecs[iqpt,:,ibranch] = evec
uf = phonon_unfolder(atoms,sc_mat,evecs,qpoints,phase=False)
weights = uf.get_weights()
x=np.arange(nqpts)
freqs=evals
names = ['$\Gamma$', 'X', 'W', '$\Gamma$', 'L']
#ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*33.356,weights[:,:].T*0.98+0.01,xticks=[names,X],axis=ax)
<|code_end|>
, determine the next line of code. You have imports:
import abipy.abilab as abilab
import numpy as np
import matplotlib.pyplot as plt
from ase.build import bulk
from ase.dft.kpoints import get_special_points, bandpath
from pyDFTutils.unfolding.phonon_unfolder import phonon_unfolder
from pyDFTutils.phonon.plotphon import plot_band_weight
and context (class names, function names, or code) available:
# Path: pyDFTutils/phonon/plotphon.py
# def plot_band_weight(kslist,
# ekslist,
# wkslist=None,
# efermi=0,
# yrange=None,
# output=None,
# style='alpha',
# color='blue',
# axis=None,
# width=2,
# xticks=None,
# title=None):
# if axis is None:
# fig, a = plt.subplots()
# plt.tight_layout(pad=2.19)
# plt.axis('tight')
# plt.gcf().subplots_adjust(left=0.17)
# else:
# a = axis
# if title is not None:
# a.set_title(title)
#
# xmax = max(kslist[0])
# if yrange is None:
# yrange = (np.array(ekslist).flatten().min() - 66,
# np.array(ekslist).flatten().max() + 66)
#
# if wkslist is not None:
# for i in range(len(kslist)):
# x = kslist[i]
# y = ekslist[i]
# lwidths = np.array(wkslist[i]) * width
# #lwidths=np.ones(len(x))
# points = np.array([x, y]).T.reshape(-1, 1, 2)
# segments = np.concatenate([points[:-1], points[1:]], axis=1)
# if style == 'width':
# lc = LineCollection(segments, linewidths=lwidths, colors=color)
# elif style == 'alpha':
# lc = LineCollection(
# segments,
# linewidths=[2] * len(x),
# colors=[
# colorConverter.to_rgba(
# color, alpha=np.abs(lwidth / (width + 0.001)))
# for lwidth in lwidths
# ])
#
# a.add_collection(lc)
# plt.ylabel('Frequency (cm$^{-1}$)')
# if axis is None:
# for ks, eks in zip(kslist, ekslist):
# plt.plot(ks, eks, color='gray', linewidth=0.001)
# a.set_xlim(0, xmax)
# a.set_ylim(yrange)
# if xticks is not None:
# plt.xticks(xticks[1], xticks[0])
# for x in xticks[1]:
# plt.axvline(x, color='gray', linewidth=0.5)
# if efermi is not None:
# plt.axhline(linestyle='--', color='black')
# return a
. Output only the next line. | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*27*33.356,weights[:,:].T*0.98+0.01,xticks=[names,[1,2,3,4,5]],style='alpha') |
Given the code snippet: <|code_start|>
m = np.sqrt(np.kron(masses,[1,1,1]))
#positions=np.kron(scaled_positions,[1,1,1])
for iqpt, qpt in enumerate(qpoints):
for ibranch in range(nbranch):
phmode = phbst.get_phmode(qpt, ibranch)
evals[iqpt, ibranch] = phmode.freq
#evec=phmode.displ_cart *m
#phase = [np.exp(-2j*np.pi*np.dot(pos,qpt)) for pos in scaled_positions]
#phase = np.kron(phase,[1,1,1])
#evec*=phase
#evec /= np.linalg.norm(evec)
evec=displacement_cart_to_evec(phmode.displ_cart, masses, scaled_positions, qpoint=qpt, add_phase=True)
evecs[iqpt,:,ibranch] = evec
uf = phonon_unfolder(atoms,sc_mat,evecs,qpoints,phase=False)
weights = uf.get_weights()
x=np.arange(nqpts)
freqs=evals
xpts=[]
for ix, xx in enumerate(x):
for q in kpath_bounds:
if np.sum((np.array(qpoints[ix])-np.array(q))**2)<0.00001 and ix not in xpts:
xpts.append(ix)
if knames is None:
knames=[str(k) for k in kpath_bounds]
#names = ['$\Gamma$', 'X', 'W', '$\Gamma$', 'L']
#ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*33.356,weights[:,:].T*0.98+0.01,xticks=[names,X],axis=ax)
<|code_end|>
, generate the next line using the imports in this file:
import abipy.abilab as abilab
import numpy as np
import matplotlib.pyplot as plt
import sys
from ase.build import bulk
from ase.dft.kpoints import get_special_points, bandpath
from pyDFTutils.unfolding.phonon_unfolder import phonon_unfolder
from pyDFTutils.phonon.plotphon import plot_band_weight
and context (functions, classes, or occasionally code) from other files:
# Path: pyDFTutils/phonon/plotphon.py
# def plot_band_weight(kslist,
# ekslist,
# wkslist=None,
# efermi=0,
# yrange=None,
# output=None,
# style='alpha',
# color='blue',
# axis=None,
# width=2,
# xticks=None,
# title=None):
# if axis is None:
# fig, a = plt.subplots()
# plt.tight_layout(pad=2.19)
# plt.axis('tight')
# plt.gcf().subplots_adjust(left=0.17)
# else:
# a = axis
# if title is not None:
# a.set_title(title)
#
# xmax = max(kslist[0])
# if yrange is None:
# yrange = (np.array(ekslist).flatten().min() - 66,
# np.array(ekslist).flatten().max() + 66)
#
# if wkslist is not None:
# for i in range(len(kslist)):
# x = kslist[i]
# y = ekslist[i]
# lwidths = np.array(wkslist[i]) * width
# #lwidths=np.ones(len(x))
# points = np.array([x, y]).T.reshape(-1, 1, 2)
# segments = np.concatenate([points[:-1], points[1:]], axis=1)
# if style == 'width':
# lc = LineCollection(segments, linewidths=lwidths, colors=color)
# elif style == 'alpha':
# lc = LineCollection(
# segments,
# linewidths=[2] * len(x),
# colors=[
# colorConverter.to_rgba(
# color, alpha=np.abs(lwidth / (width + 0.001)))
# for lwidth in lwidths
# ])
#
# a.add_collection(lc)
# plt.ylabel('Frequency (cm$^{-1}$)')
# if axis is None:
# for ks, eks in zip(kslist, ekslist):
# plt.plot(ks, eks, color='gray', linewidth=0.001)
# a.set_xlim(0, xmax)
# a.set_ylim(yrange)
# if xticks is not None:
# plt.xticks(xticks[1], xticks[0])
# for x in xticks[1]:
# plt.axvline(x, color='gray', linewidth=0.5)
# if efermi is not None:
# plt.axhline(linestyle='--', color='black')
# return a
. Output only the next line. | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*8065.6,weights[:,:].T*0.98+0.01,xticks=[knames,xpts],style='alpha') |
Given snippet: <|code_start|>#!/usr/bin/env python
def plot_pdos():
parser=argparse.ArgumentParser(description='Plot the partial dos')
parser.add_argument('-f','--filename',type=str,help='DOSCAR filename',default='DOSCAR')
parser.add_argument('-n','--ispin',type=int,help='number os spins, 1 or 2',default=2)
parser.add_argument('-o','--output',type=str,help='output dir',default='PDOS')
parser.add_argument('--xmin',type=float,help='xmin',default=-15.0)
parser.add_argument('--xmax',type=float,help='xmax',default=5.0)
parser.add_argument('--ymin',type=float,help='ymin',default=-2.0)
parser.add_argument('--ymax',type=float,help='xmax',default=2.0)
parser.add_argument('-s','--sites',type=str,help='sites',default=['s','p','eg','t2g'],nargs='+')
parser.add_argument('-e','--element',type=str,help='element',default=None,nargs='+')
args=parser.parse_args()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pyDFTutils.vasp.vasp_dos import plot_all_pdos
import argparse
and context:
# Path: pyDFTutils/vasp/vasp_dos.py
# def plot_all_pdos(element_types=None,filename='DOSCAR',ispin=2,ymin=-2.0,ymax=2.0,xmin=-15.0,xmax=5.0,output_dir='PDOS',orbs=['s','p','eg','t2g']):
# for site in orbs:
# plot_pdos(sites=site,element_types=element_types,filename=filename,ispin=ispin,ymin=ymin,ymax=ymax,xmin=xmin,xmax=xmax,output_dir=output_dir)
which might include code, classes, or functions. Output only the next line. | plot_all_pdos(element_types=args.element,filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax,output_dir=args.output,orbs=args.sites) |
Next line prediction: <|code_start|>#!/usr/bin/env python
if __name__=='__main__':
parser=ArgumentParser(description='sum the DOSCAR valence dos')
parser.add_argument('-o','--output',help='output file name',default='sum_dos.txt')
args=parser.parse_args()
<|code_end|>
. Use current file imports:
(from pyDFTutils.vasp.vasp_dos import write_all_sum_dos
from argparse import ArgumentParser)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/vasp/vasp_dos.py
# def write_all_sum_dos(output='sum_dos.txt',nospin_output='sum_dos_nospin.txt',eg_polar_output='eg_polor.txt',erange=None):
# mydos=MyVaspDos()
# orbs=mydos.get_orbital_names()
# symdict=get_symdict()
# with open(output,'w') as myfile:
# myfile.write('symnum '+'\t'.join([x.ljust(5) for x in orbs])+'\n')
# for symnum in symdict:
# sdoss=list(mydos.sum_dos_all(symdict[symnum],erange=erange).values())
# myfile.write('%s\t%s\n'%(symnum.ljust(6),'\t'.join(["%.3f"%s for s in sdoss])))
#
# orbs=mydos.get_orbital_names_nospin()
# with open(nospin_output,'w') as myfile:
# myfile.write('symnum '+'\t'.join([x.ljust(5) for x in orbs])+'\n')
# for symnum in symdict:
# sdoss=list(mydos.sum_dos_all_nospin(symdict[symnum],erange=erange).values())
# myfile.write('%s\t%s\n'%(symnum.ljust(6),'\t'.join(["%.3f"%s for s in sdoss])))
#
# try:
# if eg_polar_output is not None:
# with open(eg_polar_output,'w') as myfile:
# myfile.write('symnum '+'\t'.join(['dx2+','dx2-','dz2+','dz2-','dx2','dz2','rate'])+'\n')
# for symnum in symdict:
# dx2_up=mydos.sum_dos(symdict[symnum],'dx2+',erange=erange)
# dx2_down=mydos.sum_dos(symdict[symnum],'dx2-',erange=erange)
# dz2_up=mydos.sum_dos(symdict[symnum],'dz2+',erange=erange)
# dz2_down=mydos.sum_dos(symdict[symnum],'dz2-',erange=erange)
#
# dx2=mydos.sum_dos_nospin(symdict[symnum],'dx2',erange=erange)
# dz2=mydos.sum_dos_nospin(symdict[symnum],'dz2',erange=erange)
# if dx2+dz2<0.0001: #no eg
# porlar_rate=0
# else:
# porlar_rate=(dx2-dz2)/(dx2+dz2)
#
# myfile.write('%s\t%s\n'%(symnum.ljust(6),'\t'.join(["%.3f"%s for s in [dx2_up,dx2_down,dz2_up,dz2_down,dx2,dz2,porlar_rate]])))
# except Exception as exc:
# print(("Warning: This is not a good DOSCAR for calculating eg polarization. \n %s"%exc))
. Output only the next line. | write_all_sum_dos(output=args.output) |
Given the following code snippet before the placeholder: <|code_start|>#! /usr/bin/env python
def get_potential():
if not os.path.exists('./vplanar.txt'):
raise IOError('No data vplanar.txt found. Please run work_function')
data=np.loadtxt('vplanar.txt',skiprows=1)
pos=data[:,0]
pot=data[:,1]
return pos,pot
def periodic_average(data,step):
l=len(data)
avg=data.copy()
data=np.reshape(data,[1,l])
tri_data=np.repeat(data,3,axis=0).flatten()
for i in range(l):
print(i)
l1=-step/2+i+l
l2=step/2+i+l
avg[i]=np.average(tri_data[l1:l2])
return avg
def periodic_average_dynamic(data):
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
import sys
import matplotlib.pyplot as plt
from numpy import maximum,minimum,NaN,Inf,arange,isscalar,array
from pyDFTutils.math.peakdetect import peakdetect
from numpy import *
from functools import reduce
and context including class names, function names, and sometimes code from other files:
# Path: pyDFTutils/math/peakdetect.py
# def peakdetect(y_axis, x_axis = None, lookahead = 300, delta=0):
# """
# Converted from/based on a MATLAB script at:
# http://billauer.co.il/peakdet.html
#
# function for detecting local maximas and minmias in a signal.
# Discovers peaks by searching for values which are surrounded by lower
# or larger values for maximas and minimas respectively
#
# keyword arguments:
# y_axis -- A list containg the signal over which to find peaks
# x_axis -- (optional) A x-axis whose values correspond to the y_axis list
# and is used in the return to specify the postion of the peaks. If
# omitted an index of the y_axis is used. (default: None)
# lookahead -- (optional) distance to look ahead from a peak candidate to
# determine if it is the actual peak (default: 200)
# '(sample / period) / f' where '4 >= f >= 1.25' might be a good value
# delta -- (optional) this specifies a minimum difference between a peak and
# the following points, before a peak may be considered a peak. Useful
# to hinder the function from picking up false peaks towards to end of
# the signal. To work well delta should be set to delta >= RMSnoise * 5.
# (default: 0)
# delta function causes a 20% decrease in speed, when omitted
# Correctly used it can double the speed of the function
#
# return -- two lists [max_peaks, min_peaks] containing the positive and
# negative peaks respectively. Each cell of the lists contains a tupple
# of: (position, peak_value)
# to get the average peak value do: np.mean(max_peaks, 0)[1] on the
# results to unpack one of the lists into x, y coordinates do:
# x, y = zip(*tab)
# """
# max_peaks = []
# min_peaks = []
# dump = [] #Used to pop the first hit which almost always is false
#
# # check input data
# x_axis, y_axis = _datacheck_peakdetect(x_axis, y_axis)
# # store data length for later use
# length = len(y_axis)
#
#
# #perform some checks
# if lookahead < 1:
# raise ValueError("Lookahead must be '1' or above in value")
# if not (np.isscalar(delta) and delta >= 0):
# raise ValueError("delta must be a positive number")
#
# #maxima and minima candidates are temporarily stored in
# #mx and mn respectively
# mn, mx = np.Inf, -np.Inf
#
# #Only detect peak if there is 'lookahead' amount of points after it
# for index, (x, y) in enumerate(zip(x_axis[:-lookahead],
# y_axis[:-lookahead])):
# if y > mx:
# mx = y
# mxpos = x
# if y < mn:
# mn = y
# mnpos = x
#
# ####look for max####
# if y < mx-delta and mx != np.Inf:
# #Maxima peak candidate found
# #look ahead in signal to ensure that this is a peak and not jitter
# if y_axis[index:index+lookahead].max() < mx:
# max_peaks.append([mxpos, mx])
# dump.append(True)
# #set algorithm to only find minima now
# mx = np.Inf
# mn = np.Inf
# if index+lookahead >= length:
# #end is within lookahead no more peaks can be found
# break
# continue
# #else: #slows shit down this does
# # mx = ahead
# # mxpos = x_axis[np.where(y_axis[index:index+lookahead]==mx)]
#
# ####look for min####
# if y > mn+delta and mn != -np.Inf:
# #Minima peak candidate found
# #look ahead in signal to ensure that this is a peak and not jitter
# if y_axis[index:index+lookahead].min() > mn:
# min_peaks.append([mnpos, mn])
# dump.append(False)
# #set algorithm to only find maxima now
# mn = -np.Inf
# mx = -np.Inf
# if index+lookahead >= length:
# #end is within lookahead no more peaks can be found
# break
# #else: #slows shit down this does
# # mn = ahead
# # mnpos = x_axis[np.where(y_axis[index:index+lookahead]==mn)]
#
#
# #Remove the false hit on the first value of the y_axis
# try:
# if dump[0]:
# max_peaks.pop(0)
# else:
# min_peaks.pop(0)
# del dump
# except IndexError:
# #no peaks were found, should the function return empty lists?
# pass
#
# return array([array(max_peaks),array( min_peaks)])
. Output only the next line. | p=array(peakdetect(data,lookahead=5,delta=0.01)) |
Given the following code snippet before the placeholder: <|code_start|> phfreqs = ds.variables['phfreqs'][:] * 8065.6
phdisps = ds.variables['phdispl_cart'][:]
masses = ds.variables['atomic_mass_units'][:]
masses = list(masses) + [masses[-1]] * 2
IR_modes = label_all(qpoints, phfreqs, phdisps, masses)
#return
print((phdisps[0, 0, :, :] / Bohr))
print((phdisps[0, 0, :, 0] / Bohr))
print((get_weight(phdisps[0, 0, :, :], masses)))
phfreqs = fix_gamma(qpoints, phfreqs)
weights_A = np.empty_like(phfreqs)
weights_B = np.empty_like(phfreqs)
weights_C = np.empty_like(phfreqs)
nk, nm = phfreqs.shape
for i in range(nk):
for j in range(nm):
weights_A[i, j], weights_B[i, j], weights_C[i, j] = get_weight(
phdisps[i, j, :, :], masses)
#for i in range(1):
# plt.plot(weights_B[:, i], linewidth=0.1, color='gray')
#plt.plot(weights_A[:, i], linewidth=0.1, color='gray')
#plt.show()
#return
axis = None
<|code_end|>
, predict the next line using imports from the current file:
from netCDF4 import Dataset
from matplotlib.collections import LineCollection
from matplotlib.colors import colorConverter
from ase.units import Bohr
from pyDFTutils.ase_utils.kpoints import cubic_kpath
from collections import namedtuple
import numpy as np
import matplotlib.pyplot as plt
import os.path
and context including class names, function names, and sometimes code from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
. Output only the next line. | kpath = cubic_kpath() |
Based on the snippet: <|code_start|>
def get_vertex(self,direction):
return self.__dict__[direction]
def set_axis(self,x=(1,0,0), y=(0,1,0),z=(0,0,1),axis_type=None):
"""
axis_type: default None, if not None: 'rotate45_xy': means x,y are 45 degree rotated about z
"""
if axis_type is None:
self.x=np.array(x)
self.y=np.array(y)
self.z=np.array(z)
elif axis_type=='rotate45_xy':
self.x=np.array([1,-1,0])
self.y=np.array([1,1,0])
self.z=np.array([0,0,1])
else:
raise ValueError('axis_type %s invalid.'%axis_type)
def get_octahedra(self,atoms,center_atom,atom_symbol,max_distance,var_distance=False,do_force_near_0=True,repeat=True):
"""
atoms: the atoms
center_atom: a atom object, or sym_num
atoms_symbol: symbol of atom in the vertexes
max_distance: max distance
var_distance: variable distance.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from ase.utils.geometry import rotate
from ase.io import read
from ase.geometry.cell import cellpar_to_cell, cell_to_cellpar
from pyDFTutils.ase_utils.symbol import get_symdict,symbol_number,symnum_to_sym
from pyDFTutils.ase_utils.ase_utils import scaled_pos_to_pos,force_near_0,pos_to_scaled_pos
from collections import OrderedDict,Iterable
from ase.calculators.neighborlist import NeighborList
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra
import numpy as np
import argparse
and context (classes, functions, sometimes code) from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def get_symdict(filename='POSCAR',atoms=None):
# """
# get a symbol_number: index dict.
# """
# if atoms is not None:
# syms=atoms.get_chemical_symbols()
# elif filename is not None and atoms is None:
# syms=read(filename).get_chemical_symbols()
#
# symdict=symbol_number(syms)
# return symdict
#
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
#
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
. Output only the next line. | self.sym_dict=get_symdict(filename=None,atoms=atoms) |
Given the following code snippet before the placeholder: <|code_start|>
def vec_ang(a,b):
"""angle of two vectors, 0 ~ 180"""
return np.arccos(np.inner(a,b)/(np.linalg.norm(a)*np.linalg.norm(b)))/np.pi*180
def atom_angle(a1,a2,a3):
"""
angle a1-a2-a3
a1 a2 a3 are atom objects
"""
vec1=a2.position-a1.position
vec2=a2.position-a3.position
return vec_ang(vec1,vec2)
def even_or_odd_path(atoms,from_symnum,node_sym_list,to_symnum_list=None,first_neighbor_min=2.5,first_neighbor_max=4.5):
"""
Find whether the distance of the atoms with symnum in to_list to the atom(from_symnum) is even or odd.
The distance to the first neighbor is 1. The 1st neighbor's 1st neighbor is 2. etc....
Args:
atoms:
from_symnum
to_sym_list: The symbol of the atoms, eg:['Fe','Ni' ], Note the from_symnum should be start with the symbol in this list
to_symnum_list: The symbol_number of the atoms, eg:['Fe1','Fe2','Ni1'].Only one of the to_sym_list and to_symnum_list should should be specified.
first_neighbor_min/max: The min/max distance to the first neighbor
Returns:
a dict. The values are 1/-1. 1 is odd, -1: even eg {'Fe1':1,'Ni1':-1}
"""
#1. Get the first neighbor list
<|code_end|>
, predict the next line using imports from the current file:
from ase.utils.geometry import rotate
from ase.io import read
from ase.geometry.cell import cellpar_to_cell, cell_to_cellpar
from pyDFTutils.ase_utils.symbol import get_symdict,symbol_number,symnum_to_sym
from pyDFTutils.ase_utils.ase_utils import scaled_pos_to_pos,force_near_0,pos_to_scaled_pos
from collections import OrderedDict,Iterable
from ase.calculators.neighborlist import NeighborList
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra
import numpy as np
import argparse
and context including class names, function names, and sometimes code from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def get_symdict(filename='POSCAR',atoms=None):
# """
# get a symbol_number: index dict.
# """
# if atoms is not None:
# syms=atoms.get_chemical_symbols()
# elif filename is not None and atoms is None:
# syms=read(filename).get_chemical_symbols()
#
# symdict=symbol_number(syms)
# return symdict
#
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
#
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
. Output only the next line. | symdict=symbol_number(atoms) |
Continue the code snippet: <|code_start|>
def atom_angle(a1,a2,a3):
"""
angle a1-a2-a3
a1 a2 a3 are atom objects
"""
vec1=a2.position-a1.position
vec2=a2.position-a3.position
return vec_ang(vec1,vec2)
def even_or_odd_path(atoms,from_symnum,node_sym_list,to_symnum_list=None,first_neighbor_min=2.5,first_neighbor_max=4.5):
"""
Find whether the distance of the atoms with symnum in to_list to the atom(from_symnum) is even or odd.
The distance to the first neighbor is 1. The 1st neighbor's 1st neighbor is 2. etc....
Args:
atoms:
from_symnum
to_sym_list: The symbol of the atoms, eg:['Fe','Ni' ], Note the from_symnum should be start with the symbol in this list
to_symnum_list: The symbol_number of the atoms, eg:['Fe1','Fe2','Ni1'].Only one of the to_sym_list and to_symnum_list should should be specified.
first_neighbor_min/max: The min/max distance to the first neighbor
Returns:
a dict. The values are 1/-1. 1 is odd, -1: even eg {'Fe1':1,'Ni1':-1}
"""
#1. Get the first neighbor list
symdict=symbol_number(atoms)
symnums=list(symdict.keys())
node_list=[]
for s in symnums:
#print s
<|code_end|>
. Use current file imports:
from ase.utils.geometry import rotate
from ase.io import read
from ase.geometry.cell import cellpar_to_cell, cell_to_cellpar
from pyDFTutils.ase_utils.symbol import get_symdict,symbol_number,symnum_to_sym
from pyDFTutils.ase_utils.ase_utils import scaled_pos_to_pos,force_near_0,pos_to_scaled_pos
from collections import OrderedDict,Iterable
from ase.calculators.neighborlist import NeighborList
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra
import numpy as np
import argparse
and context (classes, functions, or code) from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def get_symdict(filename='POSCAR',atoms=None):
# """
# get a symbol_number: index dict.
# """
# if atoms is not None:
# syms=atoms.get_chemical_symbols()
# elif filename is not None and atoms is None:
# syms=read(filename).get_chemical_symbols()
#
# symdict=symbol_number(syms)
# return symdict
#
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
#
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
. Output only the next line. | if symnum_to_sym(s) in node_sym_list: |
Given the code snippet: <|code_start|>#!/usr/bin/env python
if __name__=='__main__':
if len(sys.argv)==2:
spin = sys.argv[1]
else:
spin=None
<|code_end|>
, generate the next line using the imports in this file:
from pyDFTutils.queue.commander import zenobe_run_wannier90
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: pyDFTutils/queue/commander.py
# def zenobe_run_wannier90(spin=None, **kwargs):
# if spin is None:
# command = '/home/acad/ulg-phythema/hexu/.local/bin/wannier90.x wannier90.win'
# elif spin == 'up':
# command = '/home/acad/ulg-phythema/hexu/.local/bin/wannier90.x wannier90.up.win'
# elif spin == 'dn' or spin == 'down':
# command = '/home/acad/ulg-phythema/hexu/.local/bin/wannier90.x wannier90.dn.win'
# else:
# raise NotImplementedError("spin should be None|up|dn")
# mycommander = zenobe_wannier90(command=command, **kwargs)
# mycommander.run()
. Output only the next line. | zenobe_run_wannier90(spin=spin) |
Here is a snippet: <|code_start|>#! /usr/bin/env python
def run_bader(filename='CHGCAR'):
if os.path.exists('AECCAR0') and os.path.exists('AECCAR2'):
if not os.path.exists('CHGCAR_sum'):
os.system('chgsum AECCAR0 AECCAR2')
os.system('bader %s -ref CHGCAR_sum'%filename)
else:
os.system('bader %s'%filename)
def bcf_parser(filename='ACF.dat'):
"""
parse the ACF.dat file and return the {iatom:charge} pairs.
iatom starts from 0
"""
text=open(filename,'r').readlines()
val_dict=dict()
for line in text[2:-4]:
i,x,y,z,val,min_dist,volume= [float(x) for x in line.strip().split()]
iatom=int(i)-1
val_dict[iatom]=val
return val_dict
def get_charge(filename='ACF.dat'):
"""
net charge of the ions.
"""
val_dict=bcf_parser(filename=filename)
atoms=read('POSCAR')
symbols=atoms.get_chemical_symbols()
<|code_end|>
. Write the next line using the current file imports:
from .vasp_utils import get_electrons
from pyDFTutils.ase_utils.chemsymbol import get_symdict
from ase.io import read
import matplotlib.pyplot as plt
import os
import numpy as np
import re
and context from other files:
# Path: pyDFTutils/vasp/vasp_utils.py
# def get_electrons(filename='POTCAR'):
# """
# get dict {symbol: valence} from POTCAR
# """
# nelect = dict()
# lines = open(filename).readlines()
# for n, line in enumerate(lines):
# if line.find('TITEL') != -1:
# symbol = line.split('=')[1].split()[1].split('_')[0].strip()
# valence = float(
# lines[n + 4].split(';')[1].split('=')[1].split()[0].strip())
# nelect[symbol] = valence
# return nelect
, which may include functions, classes, or code. Output only the next line. | elec_dict=get_electrons() |
Using the snippet: <|code_start|> #plt.show()
def phonon_unfold():
atoms = FaceCenteredCubic(size=(1, 1, 1), symbol="Cu", pbc=True)
symbols = atoms.get_chemical_symbols()
symbols[-1] = 'Ag'
atoms.set_chemical_symbols(symbols)
calc = EMT()
atoms.set_calculator(calc)
phonon = calculate_phonon(
atoms, calc, ndim=np.eye(3) * 2, primitive_matrix=np.eye(3)/1.0)
kpts, x, X, names = kpath()
kpts = [
np.dot(k,
np.linalg.inv(
(np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) / 2.0)))
for k in kpts
]
phonon.set_qpoints_phonon(kpts, is_eigenvectors=True)
freqs, eigvecs = phonon.get_qpoints_phonon()
sc=atoms
sc_mat = np.linalg.inv((np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) / 2.0))
spos=sc.get_scaled_positions()
uf = phonon_unfolder(atoms,sc_mat,eigvecs,kpts)
weights = uf.get_weights()
ax=None
<|code_end|>
, determine the next line of code. You have imports:
from ase.lattice.cubic import FaceCenteredCubic
from ase.calculators.emt import EMT
from ase.units import Bohr
from frozenphonon import calculate_phonon
from ase.dft.kpoints import *
from ase.build import bulk
from pyDFTutils.unfolding.phonon_unfolder import phonon_unfolder
from pyDFTutils.phonon.plotphon import plot_band_weight
import numpy as np
import matplotlib.pyplot as plt
and context (class names, function names, or code) available:
# Path: pyDFTutils/phonon/plotphon.py
# def plot_band_weight(kslist,
# ekslist,
# wkslist=None,
# efermi=0,
# yrange=None,
# output=None,
# style='alpha',
# color='blue',
# axis=None,
# width=2,
# xticks=None,
# title=None):
# if axis is None:
# fig, a = plt.subplots()
# plt.tight_layout(pad=2.19)
# plt.axis('tight')
# plt.gcf().subplots_adjust(left=0.17)
# else:
# a = axis
# if title is not None:
# a.set_title(title)
#
# xmax = max(kslist[0])
# if yrange is None:
# yrange = (np.array(ekslist).flatten().min() - 66,
# np.array(ekslist).flatten().max() + 66)
#
# if wkslist is not None:
# for i in range(len(kslist)):
# x = kslist[i]
# y = ekslist[i]
# lwidths = np.array(wkslist[i]) * width
# #lwidths=np.ones(len(x))
# points = np.array([x, y]).T.reshape(-1, 1, 2)
# segments = np.concatenate([points[:-1], points[1:]], axis=1)
# if style == 'width':
# lc = LineCollection(segments, linewidths=lwidths, colors=color)
# elif style == 'alpha':
# lc = LineCollection(
# segments,
# linewidths=[2] * len(x),
# colors=[
# colorConverter.to_rgba(
# color, alpha=np.abs(lwidth / (width + 0.001)))
# for lwidth in lwidths
# ])
#
# a.add_collection(lc)
# plt.ylabel('Frequency (cm$^{-1}$)')
# if axis is None:
# for ks, eks in zip(kslist, ekslist):
# plt.plot(ks, eks, color='gray', linewidth=0.001)
# a.set_xlim(0, xmax)
# a.set_ylim(yrange)
# if xticks is not None:
# plt.xticks(xticks[1], xticks[0])
# for x in xticks[1]:
# plt.axvline(x, color='gray', linewidth=0.5)
# if efermi is not None:
# plt.axhline(linestyle='--', color='black')
# return a
. Output only the next line. | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*33.356,weights[:,:].T*0.98+0.01,xticks=[names,X],axis=ax) |
Next line prediction: <|code_start|>def read_unsorted_poscar(filename='CONTCAR'):
s, p, c = read_poscar_and_unsort(filename=filename)
atoms = Atoms(symbols=s, positions=p, cell=c)
return atoms
def get_electrons(filename='POTCAR'):
"""
get dict {symbol: valence} from POTCAR
"""
nelect = dict()
lines = open(filename).readlines()
for n, line in enumerate(lines):
if line.find('TITEL') != -1:
symbol = line.split('=')[1].split()[1].split('_')[0].strip()
valence = float(
lines[n + 4].split(';')[1].split('=')[1].split()[0].strip())
nelect[symbol] = valence
return nelect
def get_symdict(filename='POSCAR', atoms=None):
"""
get a symbol_number: index dict.
"""
if filename is None and atoms is not None:
syms = atoms.get_chemical_symbols()
elif filename is not None and atoms is None:
syms = read(filename).get_chemical_symbols()
<|code_end|>
. Use current file imports:
(import numpy as np
import os.path
import re
from ase.io import read
from ase.io.vasp import read_vasp
from pyDFTutils.ase_utils.symbol import symbol_number, symnum_to_sym
from ase.atoms import Atoms)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
#
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
. Output only the next line. | symdict = symbol_number(syms) |
Next line prediction: <|code_start|> if line.startswith(' magnetization (x)'):
start = True
text = ''
if start:
text += line
if line.startswith('tot'):
start = False
return text
def check_converge(filename='log'):
"""
check the log file to see if the calculation is converged.
If converged, return the number of steps of iteration, else return False.
"""
nstep = 0
with open(filename) as myfile:
for line in myfile:
l = line
try:
nstep = int(line.strip().split()[0])
except Exception:
pass
if l.strip().startswith('writing'):
return nstep
else:
return False
if __name__ == '__main__':
<|code_end|>
. Use current file imports:
(import numpy as np
import os.path
import re
from ase.io import read
from ase.io.vasp import read_vasp
from pyDFTutils.ase_utils.symbol import symbol_number, symnum_to_sym
from ase.atoms import Atoms)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/ase_utils/symbol.py
# def symbol_number(symbols):
# """
# symbols can be also atoms. Thus the chemical symbols will be used.
# Fe Fe Fe O -> {Fe1:0 Fe2:1 Fe3:2 O1:3}
# """
# try:
# symbs=symbols.copy().get_chemical_symbols()
# except Exception:
# symbs=symbols
# symdict={}
# result=OrderedDict()
# for i,sym in enumerate(symbs):
# if sym in symdict:
# symdict[sym]=symdict[sym]+1
# else:
# symdict[sym]=1
# result[sym+str(symdict[sym])]=i
# return result
#
# def symnum_to_sym(symbol_number):
# """
# symnum-> sym. eg: Fe1-> Fe
# """
# try:
# a=re.search('[A-Za-z]+',symbol_number).group()
# return a
# except AttributeError:
# raise AttributeError('%s is not a good symbol_number'%symbol_number)
. Output only the next line. | print(symnum_to_sym('1')) |
Next line prediction: <|code_start|>#!/usr/bin/env python
def plot_ldos():
parser=argparse.ArgumentParser(description='Plot the local dos')
parser.add_argument('-f','--filename',type=str,help='DOSCAR filename',default='DOSCAR')
parser.add_argument('-n','--ispin',type=int,help='number os spins, 1 or 2',default=2)
parser.add_argument('-o','--output',type=str,help='output dir')
parser.add_argument('--xmin',type=float,help='xmin',default=-15.0)
parser.add_argument('--xmax',type=float,help='xmax',default=5.0)
parser.add_argument('--ymin',type=float,help='ymin',default=-2.0)
parser.add_argument('--ymax',type=float,help='xmax',default=2.0)
args=parser.parse_args()
<|code_end|>
. Use current file imports:
(from pyDFTutils.vasp.vasp_dos import plot_all_ldos
import argparse)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/vasp/vasp_dos.py
# def plot_all_ldos(filename='DOSCAR',ispin=2,ymin=-2.0,ymax=2.0,xmin=-15.0,xmax=5.0,element_types=None, has_f=False):
# """
# plot the local dos of all atoms.
# """
# symdict=get_symdict()
#
# if element_types is not None:
# atom_nums=[x for x in list(symdict.keys()) if symnum_to_sym(x) in element_types]
# else:
# atom_nums=list(symdict.keys())
#
# if ispin==2:
# if has_f:
# sites=['s+','p+','d+','s-','p-','d-', 'f+', 'f-']
# else:
# sites=['s+','p+','d+','s-','p-','d-']
# else:
# if has_f:
# sites=['s','p','d','f']
# else:
# sites=['s','p','d']
#
# if not os.path.exists('LDOS'):
# os.mkdir('LDOS')
# for atom_num in atom_nums:
# copyfile(filename,'LDOS/DOSCAR')
# plotldos_group([atom_num],sites,ymin=ymin,ymax=ymax,xmin=xmin,xmax=xmax,special_location=None,output='LDOS/%s_ldos.png'%atom_num)
. Output only the next line. | plot_all_ldos(filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax, has_f=False) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
def test():
parser=argparse.ArgumentParser(description='Decide AFM structure 1 -1')
parser.add_argument('-f','--filename',type=str,help='POSCAR filename',default='POSCAR.vasp')
parser.add_argument('-n','--nodes',type=str,help='symbol of element on the node',nargs='+')
parser.add_argument('-o','--origin',type=str,help='From which symbol_number')
parser.add_argument('--xmin',type=float,help='xmin',default=0.5)
parser.add_argument('--xmax',type=float,help='xmax',default=4.8)
args=parser.parse_args()
#plot_all_pdos(element_types=args.element,filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax,output_dir=args.output)
atoms=read_vasp(args.filename)
<|code_end|>
, predict the immediate next line with the help of imports:
from pyDFTutils.perovskite.octahedra import even_or_odd_path,symnum_to_sym
from ase.io.vasp import read_vasp
import argparse
and context (classes, functions, sometimes code) from other files:
# Path: pyDFTutils/perovskite/octahedra.py
# def distance(a1,a2):
# def vec_ang(a,b):
# def atom_angle(a1,a2,a3):
# def even_or_odd_path(atoms,from_symnum,node_sym_list,to_symnum_list=None,first_neighbor_min=2.5,first_neighbor_max=4.5):
# def even_odd(x):
# def rotation_angle_about_axis(vec0,from_vec,axis_vec):
# def __init__(self):
# def get_vertex(self,direction):
# def set_axis(self,x=(1,0,0), y=(0,1,0),z=(0,0,1),axis_type=None):
# def get_octahedra(self,atoms,center_atom,atom_symbol,max_distance,var_distance=False,do_force_near_0=True,repeat=True):
# def read_octahedra(self,filename,center_sym_number,vertex_symbol,max_distance,var_distance=False):
# def pair(self,ang_thr=20):
# def get_bond_lengths(self):
# def get_vertex_diag_length(self):
# def get_directions(self):
# def get_rotations(self):
# def get_avg_rotations(self):
# def get_distortion(self):
# def get_bond_info(self,show=True):
# def get_bond_angle(self):
# def find_neighbouring_octahedron(self,direction='upper',target_symbol_list=None,do_force_near_0=False):
# def get_vertex_angle(self,direction='upper',target_symbol_list=None,do_force_near_0=False):
# def get_vertex_angles(self,target_symbol_list=None,do_force_near_0=False):
# def get_octahedron(atoms,center_sym_number,vertex_symbol,max_distance, axis_type=None,x=(1,0,0),y=(0,1,0),z=(0,0,1), var_distance=False):
# def octa_chain(start_octahedron,direction='upper',target_symbol_list=None):
# def rotate_atoms_with_octahedra(atoms,octa):
# def rotate_atoms_with_octahedra_average(atoms,octahedras):
# def write_all_octahedra_info(atoms,center_symbol_list,vertex_symbol,max_distance,output='octa_info.csv',axis_type=None,x=(1,0,0),y=(0,1,0),z=(0,0,1), var_distance=False):
# def main():
# N=len(node_list)
# class octahedra():
. Output only the next line. | symnums,vals= even_or_odd_path(atoms,args.origin,args.nodes,first_neighbor_min=args.xmin,first_neighbor_max=args.xmax) |
Next line prediction: <|code_start|>#!/usr/bin/env python
def test():
parser=argparse.ArgumentParser(description='Decide AFM structure 1 -1')
parser.add_argument('-f','--filename',type=str,help='POSCAR filename',default='POSCAR.vasp')
parser.add_argument('-n','--nodes',type=str,help='symbol of element on the node',nargs='+')
parser.add_argument('-o','--origin',type=str,help='From which symbol_number')
parser.add_argument('--xmin',type=float,help='xmin',default=0.5)
parser.add_argument('--xmax',type=float,help='xmax',default=4.8)
args=parser.parse_args()
#plot_all_pdos(element_types=args.element,filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax,output_dir=args.output)
atoms=read_vasp(args.filename)
symnums,vals= even_or_odd_path(atoms,args.origin,args.nodes,first_neighbor_min=args.xmin,first_neighbor_max=args.xmax)
for sym in args.nodes:
vs=[]
for i,(s,v) in enumerate(zip(symnums,vals)):
<|code_end|>
. Use current file imports:
(from pyDFTutils.perovskite.octahedra import even_or_odd_path,symnum_to_sym
from ase.io.vasp import read_vasp
import argparse)
and context including class names, function names, or small code snippets from other files:
# Path: pyDFTutils/perovskite/octahedra.py
# def distance(a1,a2):
# def vec_ang(a,b):
# def atom_angle(a1,a2,a3):
# def even_or_odd_path(atoms,from_symnum,node_sym_list,to_symnum_list=None,first_neighbor_min=2.5,first_neighbor_max=4.5):
# def even_odd(x):
# def rotation_angle_about_axis(vec0,from_vec,axis_vec):
# def __init__(self):
# def get_vertex(self,direction):
# def set_axis(self,x=(1,0,0), y=(0,1,0),z=(0,0,1),axis_type=None):
# def get_octahedra(self,atoms,center_atom,atom_symbol,max_distance,var_distance=False,do_force_near_0=True,repeat=True):
# def read_octahedra(self,filename,center_sym_number,vertex_symbol,max_distance,var_distance=False):
# def pair(self,ang_thr=20):
# def get_bond_lengths(self):
# def get_vertex_diag_length(self):
# def get_directions(self):
# def get_rotations(self):
# def get_avg_rotations(self):
# def get_distortion(self):
# def get_bond_info(self,show=True):
# def get_bond_angle(self):
# def find_neighbouring_octahedron(self,direction='upper',target_symbol_list=None,do_force_near_0=False):
# def get_vertex_angle(self,direction='upper',target_symbol_list=None,do_force_near_0=False):
# def get_vertex_angles(self,target_symbol_list=None,do_force_near_0=False):
# def get_octahedron(atoms,center_sym_number,vertex_symbol,max_distance, axis_type=None,x=(1,0,0),y=(0,1,0),z=(0,0,1), var_distance=False):
# def octa_chain(start_octahedron,direction='upper',target_symbol_list=None):
# def rotate_atoms_with_octahedra(atoms,octa):
# def rotate_atoms_with_octahedra_average(atoms,octahedras):
# def write_all_octahedra_info(atoms,center_symbol_list,vertex_symbol,max_distance,output='octa_info.csv',axis_type=None,x=(1,0,0),y=(0,1,0),z=(0,0,1), var_distance=False):
# def main():
# N=len(node_list)
# class octahedra():
. Output only the next line. | if symnum_to_sym(s)==sym: |
Given the following code snippet before the placeholder: <|code_start|>
def cubic_kpath(npoints=500,name=True):
"""
return the kpoint path for cubic
Parameters:
----------------
npoints: int
number of points.
Returns:
-----------------
kpts:
kpoints
xs:
x cordinates for plot
xspecial:
x cordinates for special k points
"""
special_path = special_paths['cubic']
points = special_points['cubic']
paths = parse_path_string(special_path)
special_kpts = [points[k] for k in paths[0]]
kpts, xs, xspecial = bandpath(
special_kpts, cell=np.eye(3), npoints=npoints)
if not name:
return kpts, xs, xspecial
else:
return kpts, xs, xspecial,special_path
<|code_end|>
, predict the next line using imports from the current file:
import os
import shutil
import numpy as np
import subprocess
import spglib
from glob import glob
from os.path import join, isfile, islink
from ase.atoms import Atoms
from ase.data import atomic_numbers
from ase.units import Bohr, Hartree, fs, Ha, eV
from ase.data import chemical_symbols
from ase.io.abinit import read_abinit
from ase.io.vasp import write_vasp
from ase.calculators.calculator import FileIOCalculator, Parameters, kpts2mp, \
ReadError,all_changes,Calculator
from pyDFTutils.ase_utils.kpoints import get_ir_kpts, cubic_kpath
from string import Template
from ase.dft.kpoints import special_paths, special_points, parse_path_string, bandpath
from collections import Counter
and context including class names, function names, and sometimes code from other files:
# Path: pyDFTutils/ase_utils/kpoints.py
# def get_ir_kpts(atoms, mesh):
# """
# Gamma-centered IR kpoints. mesh : [nk1,nk2,nk3].
# """
# lattice = atoms.get_cell()
# positions = atoms.get_scaled_positions()
# numbers = atoms.get_atomic_numbers()
#
# cell = (lattice, positions, numbers)
# mapping, grid = spglib.get_ir_reciprocal_mesh(
# mesh, cell, is_shift=[0, 0, 0])
# #print("%3d ->%3d %s" % (1, mapping[0], grid[0].astype(float) / mesh))
# #print("Number of ir-kpoints: %d" % len(np.unique(mapping)))
# #print(grid[np.unique(mapping)] / np.array(mesh, dtype=float))
# return grid[np.unique(mapping)] / np.array(mesh, dtype=float)
#
# def cubic_kpath(npoints=500,name=True):
# """
# return the kpoint path for cubic
# Parameters:
# ----------------
# npoints: int
# number of points.
#
# Returns:
# -----------------
# kpts:
# kpoints
# xs:
# x cordinates for plot
# xspecial:
# x cordinates for special k points
# """
# special_path = special_paths['cubic']
# points = special_points['cubic']
# paths = parse_path_string(special_path)
# special_kpts = [points[k] for k in paths[0]]
# kpts, xs, xspecial = bandpath(
# special_kpts, cell=np.eye(3), npoints=npoints)
# if not name:
# return kpts, xs, xspecial
# else:
# return kpts, xs, xspecial,special_path
. Output only the next line. | def get_ir_kpts(atoms, mesh): |
Given the following code snippet before the placeholder: <|code_start|>
class NextEventsContent(models.Model):
count = models.IntegerField(default=5)
class Meta:
abstract = True
verbose_name = 'Next Events Content'
verbose_name_plural = 'Next Events Contents'
def render(self, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from django.template.loader import render_to_string
from woodstock.models import Event
and context including class names, function names, and sometimes code from other files:
# Path: woodstock/models/event.py
# class Event(models.Model, TranslatedObjectMixin, JobUnitMixin, ExtendableMixin):
# active = models.BooleanField(default=False)
# slug = models.SlugField(unique=True)
# date_start = models.DateTimeField(null=True)
# date_end = models.DateTimeField(null=True)
#
# objects = manager_instance
# default_manager = manager_instance
#
# class Meta:
# ordering = ('date_start',)
# verbose_name = "Event"
# verbose_name_plural = "Events"
# app_label = 'woodstock'
#
# def __unicode__(self):
# try:
# return self.translation.name
# except exceptions.ObjectDoesNotExist:
# return 'no name'
#
# def update_dates(self):
# first_part = self.parts.active().order_by('date_start')[0]
# self.date_start = first_part.date_start
# last_part = self.parts.active().order_by('-date_start')[0]
# self.date_end = last_part.date_end
# self.save()
#
# @models.permalink
# def get_absolute_url(self):
# return ('event_detail', (), {
# 'slug': self.slug,
# })
#
# @property
# def participant_count(self):
# return Participant.objects.filter(attendances__confirmed=True)\
# .filter(attendances__event_part__event=self)\
# .filter(attendances__event_part__active=True)\
# .distinct().count()
#
# def get_participant_count(self):
# return self.participant_count
# get_participant_count.short_description = "Participants"
#
# @property
# def available_places(self):
# return self.max_participants - self.participant_count
#
# @property
# def max_participants(self):
# if self.parts.active().filter(maximum_participants=0).count():
# return 0
# else:
# return self.parts.active().aggregate(models.Sum('maximum_participants'))['maximum_participants__sum']
#
# def get_max_participants(self):
# return self.max_participants or 'Unlimitiert'
# get_max_participants.short_description = "Maximum Participants"
#
# @property
# def signable(self):
# return self.is_signable()
#
# def is_signable(self):
# return self.parts.filter(signable=True).filter(date_start__gt=datetime.datetime.now()).count() > 0
#
# # newsletter functions
# def get_newsletter_receiver_collections(self):
# collections = tuple()
# for part in self.parts.all():
# collections += ((part.name, {'event_part': part.id}),)
# return collections
#
# def get_receiver_filtered_queryset(self, collections=None, **kwargs):
# from woodstock.models import Participant
#
# q = models.Q()
# all_collections = self.get_newsletter_receiver_collections()
# for collection in collections:
# event_part_id = all_collections[int(collection)][1]['event_part']
# q |= models.Q(attendances__event_part__pk=event_part_id)
# if kwargs['has_attended']:
# q &= models.Q(attendances__attended=True)
# if kwargs['has_not_attended']:
# q &= models.Q(attendances__attended=False)
# if kwargs['is_confirmed']:
# q &= models.Q(attendances__confirmed=True)
# if kwargs['is_not_confirmed']:
# q &= models.Q(attendances__confirmed=False)
# return Participant.objects.filter(q).distinct()
#
# def send_subscribe_mail(self, participant):
# if self.translation.subscribe_mail is None:
# return
# self.translation.subscribe_mail.send(participant, group=self)
#
# def send_unsubscribe_mail(self, participant):
# if self.translation.unsubscribe_mail is None:
# return
# self.translation.unsubscribe_mail.send(participant, group=self)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, EventAdmin, EventTranslation, EventTranslationInline, EventPart, EventPartInline)
. Output only the next line. | events = Event.objects.pending()[0:self.count] |
Predict the next line after this snippet: <|code_start|>
def invitation_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is an invitee.
"""
actual_decorator = user_passes_test(
lambda u: isinstance(u, Invitee) and u.is_active,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def registration_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is an invitee.
"""
actual_decorator = user_passes_test(
<|code_end|>
using the current file's imports:
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from woodstock.models import Participant, Invitee
and any relevant context from other files:
# Path: woodstock/models/participant.py
# class Participant(Person):
# event_parts = models.ManyToManyField('woodstock.EventPart', related_name="participants",
# blank=True, through="Attendance")
# invitee = models.ForeignKey('woodstock.Invitee', blank=True, null=True,
# default=None, related_name="participants")
#
# class Meta:
# ordering = ('surname',)
# verbose_name = 'Participant'
# verbose_name_plural = 'Participants'
# app_label = 'woodstock'
#
# def _attend_events(self, event_parts):
# """
# Attend events without callback and other functianlity.
# """
# attendances = []
# success = True
# for part in event_parts:
# success &= not part.fully_booked()
# attendances.append(Attendance.objects.create(participant=self,
# event_part=part, confirmed=True))
# if success:
# return attendances
# # remove confirmation if something didn't went well
# for attendance in attendances:
# attendance.confirmed = False
# attendance.save()
# return False
#
# @callback('attend_events')
# def attend_events(self, event_parts):
# """
# tries to attend all parts in event_parts
# """
# from woodstock.models import Event
# if settings.SUBSCRIPTION_CONSUMES_INVITATION and self.attendances.count():
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS or not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS:
# events = Event.objects.active().filter(
# models.Q(parts__attendances__confirmed=True, parts__attendances__participant=self)
# | models.Q(parts__in=event_parts)
# )
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS and events.distinct().count() > 1:
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS and events.distinct().count() != events.count():
# raise exceptions.PermissionDenied(_("You can only attend one eventpart per event."))
# attendances = self._attend_events(event_parts)
# if not attendances:
# return False
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def _cancel_events(self, event_parts, delete=True):
# """
# Cancels event attendances
# """
# if event_parts:
# queryset = self.attendances.filter(event_part__in=event_parts)
# else:
# queryset = self.attendances.all()
# attendances = []
# for attendance in queryset:
# attendances.append(attendance)
# if delete:
# attendance.delete()
# return attendances
#
# @callback('cancel_events')
# def cancel_events(self, event_parts=None):
# """
# Cancels all event attendances to events in event_parts. If event_parts
# is omited all attendances are cancled.
# """
# from woodstock.models import Event
# attendances = self._cancel_events(event_parts)
# # send emails
# for event in Event.objects.filter(parts__in=list(a.event_part for a in attendances)):
# event.send_unsubscribe_mail(self)
# return attendances
#
# @callback('change_events')
# def change_events(self, new_event_parts, old_event_parts=None):
# """
# Changes event attendances. If old_event_parts is omited all current
# attendances are deleted.
# """
# from woodstock.models import Event
#
# old_attendances = self._cancel_events(old_event_parts, delete=False)
# attendances = self._attend_events(new_event_parts)
# if not attendances:
# return False
# for attendance in old_attendances:
# attendance.delete()
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def save(self, *args, **kwargs):
# if settings.SUBSCRIPTION_NEEDS_INVITATION and self.invitee is None:
# raise exceptions.PermissionDenied(_("Only invited Persons can register."))
# super(Participant, self).save(*args, **kwargs)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, ParticipantAdmin)
#
# callback_functions = [] # empty array
#
# @classmethod
# def register_callback(cls, callback_fn, events):
# cls.callback_functions.append({'fn': callback_fn, 'events': events})
#
# Path: woodstock/models/invitee.py
# class Invitee(Person):
# groups = models.ManyToManyField('woodstock.Group', related_name="invitations", blank=True)
#
# class Meta:
# verbose_name = 'Einladung'
# verbose_name_plural = 'Einladungen'
# ordering = ('surname',)
# app_label = 'woodstock'
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, InviteeAdmin)
. Output only the next line. | lambda u: isinstance(u, Participant) and u.is_active, |
Here is a snippet: <|code_start|>
def invitation_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is an invitee.
"""
actual_decorator = user_passes_test(
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from woodstock.models import Participant, Invitee
and context from other files:
# Path: woodstock/models/participant.py
# class Participant(Person):
# event_parts = models.ManyToManyField('woodstock.EventPart', related_name="participants",
# blank=True, through="Attendance")
# invitee = models.ForeignKey('woodstock.Invitee', blank=True, null=True,
# default=None, related_name="participants")
#
# class Meta:
# ordering = ('surname',)
# verbose_name = 'Participant'
# verbose_name_plural = 'Participants'
# app_label = 'woodstock'
#
# def _attend_events(self, event_parts):
# """
# Attend events without callback and other functianlity.
# """
# attendances = []
# success = True
# for part in event_parts:
# success &= not part.fully_booked()
# attendances.append(Attendance.objects.create(participant=self,
# event_part=part, confirmed=True))
# if success:
# return attendances
# # remove confirmation if something didn't went well
# for attendance in attendances:
# attendance.confirmed = False
# attendance.save()
# return False
#
# @callback('attend_events')
# def attend_events(self, event_parts):
# """
# tries to attend all parts in event_parts
# """
# from woodstock.models import Event
# if settings.SUBSCRIPTION_CONSUMES_INVITATION and self.attendances.count():
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS or not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS:
# events = Event.objects.active().filter(
# models.Q(parts__attendances__confirmed=True, parts__attendances__participant=self)
# | models.Q(parts__in=event_parts)
# )
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS and events.distinct().count() > 1:
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS and events.distinct().count() != events.count():
# raise exceptions.PermissionDenied(_("You can only attend one eventpart per event."))
# attendances = self._attend_events(event_parts)
# if not attendances:
# return False
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def _cancel_events(self, event_parts, delete=True):
# """
# Cancels event attendances
# """
# if event_parts:
# queryset = self.attendances.filter(event_part__in=event_parts)
# else:
# queryset = self.attendances.all()
# attendances = []
# for attendance in queryset:
# attendances.append(attendance)
# if delete:
# attendance.delete()
# return attendances
#
# @callback('cancel_events')
# def cancel_events(self, event_parts=None):
# """
# Cancels all event attendances to events in event_parts. If event_parts
# is omited all attendances are cancled.
# """
# from woodstock.models import Event
# attendances = self._cancel_events(event_parts)
# # send emails
# for event in Event.objects.filter(parts__in=list(a.event_part for a in attendances)):
# event.send_unsubscribe_mail(self)
# return attendances
#
# @callback('change_events')
# def change_events(self, new_event_parts, old_event_parts=None):
# """
# Changes event attendances. If old_event_parts is omited all current
# attendances are deleted.
# """
# from woodstock.models import Event
#
# old_attendances = self._cancel_events(old_event_parts, delete=False)
# attendances = self._attend_events(new_event_parts)
# if not attendances:
# return False
# for attendance in old_attendances:
# attendance.delete()
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def save(self, *args, **kwargs):
# if settings.SUBSCRIPTION_NEEDS_INVITATION and self.invitee is None:
# raise exceptions.PermissionDenied(_("Only invited Persons can register."))
# super(Participant, self).save(*args, **kwargs)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, ParticipantAdmin)
#
# callback_functions = [] # empty array
#
# @classmethod
# def register_callback(cls, callback_fn, events):
# cls.callback_functions.append({'fn': callback_fn, 'events': events})
#
# Path: woodstock/models/invitee.py
# class Invitee(Person):
# groups = models.ManyToManyField('woodstock.Group', related_name="invitations", blank=True)
#
# class Meta:
# verbose_name = 'Einladung'
# verbose_name_plural = 'Einladungen'
# ordering = ('surname',)
# app_label = 'woodstock'
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, InviteeAdmin)
, which may include functions, classes, or code. Output only the next line. | lambda u: isinstance(u, Invitee) and u.is_active, |
Based on the snippet: <|code_start|>
register = template.Library()
class GetEventPartsNode(template.Node):
def __init__(self, variable_name=None):
self.variable_name = variable_name
def render(self, context):
if self.variable_name is None:
return u''
if 'person' not in context:
return u''
if 'group_object' not in context:
return u''
person = context['person']
event = context['group_object']
<|code_end|>
, predict the immediate next line with the help of imports:
from django import template
from woodstock.models import EventPart
and context (classes, functions, sometimes code) from other files:
# Path: woodstock/models/event_part.py
# class EventPart(models.Model):
# event = models.ForeignKey('woodstock.Event', related_name="parts")
# name = models.CharField(max_length=100)
# date_start = models.DateTimeField()
# date_end = models.DateTimeField()
# signable = models.BooleanField(default=False)
# active = models.BooleanField(default=True)
# maximum_participants = models.IntegerField(default=0,
# verbose_name="Maximum Participants",
# help_text="Number of maximum participants or 0 for no limit.")
#
# default_manager = event_part_manager
# objects = event_part_manager
#
# class Meta:
# ordering = ('date_start',)
# verbose_name = "Event Part"
# verbose_name_plural = "Event Parts"
# app_label = 'woodstock'
#
# def __unicode__(self):
# return self.name
#
# def save(self, *args, **kwargs):
# super(EventPart, self).save(*args, **kwargs)
# self.event.update_dates()
#
# def fully_booked(self):
# """Returns true if event is already fully booked"""
# return self.maximum_participants and self.get_participant_count() >= self.maximum_participants
#
# def get_participant_count(self, confirmed_only=True):
# """
# Returns the participant count.
# If confirmed_only is False the overall count is returned.
# """
# if confirmed_only:
# return self.attendances.confirmed().count()
# return self.attendances.all().count()
# get_participant_count.short_description = "Participants"
. Output only the next line. | event_parts = EventPart.objects.filter(event=event).filter(attendances__participant=person) |
Given the code snippet: <|code_start|>
class WoodstockView(object):
invitation_required = False
registration_required = False
def dispatch(self, request, *args, **kwargs):
if self.invitation_required and not isinstance(request.user, Invitee):
raise PermissionDenied
<|code_end|>
, generate the next line using the imports in this file:
from django.core.exceptions import PermissionDenied
from woodstock.models import Invitee, Participant
and context (functions, classes, or occasionally code) from other files:
# Path: woodstock/models/participant.py
# class Participant(Person):
# event_parts = models.ManyToManyField('woodstock.EventPart', related_name="participants",
# blank=True, through="Attendance")
# invitee = models.ForeignKey('woodstock.Invitee', blank=True, null=True,
# default=None, related_name="participants")
#
# class Meta:
# ordering = ('surname',)
# verbose_name = 'Participant'
# verbose_name_plural = 'Participants'
# app_label = 'woodstock'
#
# def _attend_events(self, event_parts):
# """
# Attend events without callback and other functianlity.
# """
# attendances = []
# success = True
# for part in event_parts:
# success &= not part.fully_booked()
# attendances.append(Attendance.objects.create(participant=self,
# event_part=part, confirmed=True))
# if success:
# return attendances
# # remove confirmation if something didn't went well
# for attendance in attendances:
# attendance.confirmed = False
# attendance.save()
# return False
#
# @callback('attend_events')
# def attend_events(self, event_parts):
# """
# tries to attend all parts in event_parts
# """
# from woodstock.models import Event
# if settings.SUBSCRIPTION_CONSUMES_INVITATION and self.attendances.count():
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS or not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS:
# events = Event.objects.active().filter(
# models.Q(parts__attendances__confirmed=True, parts__attendances__participant=self)
# | models.Q(parts__in=event_parts)
# )
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS and events.distinct().count() > 1:
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS and events.distinct().count() != events.count():
# raise exceptions.PermissionDenied(_("You can only attend one eventpart per event."))
# attendances = self._attend_events(event_parts)
# if not attendances:
# return False
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def _cancel_events(self, event_parts, delete=True):
# """
# Cancels event attendances
# """
# if event_parts:
# queryset = self.attendances.filter(event_part__in=event_parts)
# else:
# queryset = self.attendances.all()
# attendances = []
# for attendance in queryset:
# attendances.append(attendance)
# if delete:
# attendance.delete()
# return attendances
#
# @callback('cancel_events')
# def cancel_events(self, event_parts=None):
# """
# Cancels all event attendances to events in event_parts. If event_parts
# is omited all attendances are cancled.
# """
# from woodstock.models import Event
# attendances = self._cancel_events(event_parts)
# # send emails
# for event in Event.objects.filter(parts__in=list(a.event_part for a in attendances)):
# event.send_unsubscribe_mail(self)
# return attendances
#
# @callback('change_events')
# def change_events(self, new_event_parts, old_event_parts=None):
# """
# Changes event attendances. If old_event_parts is omited all current
# attendances are deleted.
# """
# from woodstock.models import Event
#
# old_attendances = self._cancel_events(old_event_parts, delete=False)
# attendances = self._attend_events(new_event_parts)
# if not attendances:
# return False
# for attendance in old_attendances:
# attendance.delete()
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def save(self, *args, **kwargs):
# if settings.SUBSCRIPTION_NEEDS_INVITATION and self.invitee is None:
# raise exceptions.PermissionDenied(_("Only invited Persons can register."))
# super(Participant, self).save(*args, **kwargs)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, ParticipantAdmin)
#
# callback_functions = [] # empty array
#
# @classmethod
# def register_callback(cls, callback_fn, events):
# cls.callback_functions.append({'fn': callback_fn, 'events': events})
#
# Path: woodstock/models/invitee.py
# class Invitee(Person):
# groups = models.ManyToManyField('woodstock.Group', related_name="invitations", blank=True)
#
# class Meta:
# verbose_name = 'Einladung'
# verbose_name_plural = 'Einladungen'
# ordering = ('surname',)
# app_label = 'woodstock'
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, InviteeAdmin)
. Output only the next line. | if self.registration_required and not isinstance(request.user, Participant): |
Using the snippet: <|code_start|>
class WoodstockView(object):
invitation_required = False
registration_required = False
def dispatch(self, request, *args, **kwargs):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.exceptions import PermissionDenied
from woodstock.models import Invitee, Participant
and context (class names, function names, or code) available:
# Path: woodstock/models/participant.py
# class Participant(Person):
# event_parts = models.ManyToManyField('woodstock.EventPart', related_name="participants",
# blank=True, through="Attendance")
# invitee = models.ForeignKey('woodstock.Invitee', blank=True, null=True,
# default=None, related_name="participants")
#
# class Meta:
# ordering = ('surname',)
# verbose_name = 'Participant'
# verbose_name_plural = 'Participants'
# app_label = 'woodstock'
#
# def _attend_events(self, event_parts):
# """
# Attend events without callback and other functianlity.
# """
# attendances = []
# success = True
# for part in event_parts:
# success &= not part.fully_booked()
# attendances.append(Attendance.objects.create(participant=self,
# event_part=part, confirmed=True))
# if success:
# return attendances
# # remove confirmation if something didn't went well
# for attendance in attendances:
# attendance.confirmed = False
# attendance.save()
# return False
#
# @callback('attend_events')
# def attend_events(self, event_parts):
# """
# tries to attend all parts in event_parts
# """
# from woodstock.models import Event
# if settings.SUBSCRIPTION_CONSUMES_INVITATION and self.attendances.count():
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS or not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS:
# events = Event.objects.active().filter(
# models.Q(parts__attendances__confirmed=True, parts__attendances__participant=self)
# | models.Q(parts__in=event_parts)
# )
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS and events.distinct().count() > 1:
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS and events.distinct().count() != events.count():
# raise exceptions.PermissionDenied(_("You can only attend one eventpart per event."))
# attendances = self._attend_events(event_parts)
# if not attendances:
# return False
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def _cancel_events(self, event_parts, delete=True):
# """
# Cancels event attendances
# """
# if event_parts:
# queryset = self.attendances.filter(event_part__in=event_parts)
# else:
# queryset = self.attendances.all()
# attendances = []
# for attendance in queryset:
# attendances.append(attendance)
# if delete:
# attendance.delete()
# return attendances
#
# @callback('cancel_events')
# def cancel_events(self, event_parts=None):
# """
# Cancels all event attendances to events in event_parts. If event_parts
# is omited all attendances are cancled.
# """
# from woodstock.models import Event
# attendances = self._cancel_events(event_parts)
# # send emails
# for event in Event.objects.filter(parts__in=list(a.event_part for a in attendances)):
# event.send_unsubscribe_mail(self)
# return attendances
#
# @callback('change_events')
# def change_events(self, new_event_parts, old_event_parts=None):
# """
# Changes event attendances. If old_event_parts is omited all current
# attendances are deleted.
# """
# from woodstock.models import Event
#
# old_attendances = self._cancel_events(old_event_parts, delete=False)
# attendances = self._attend_events(new_event_parts)
# if not attendances:
# return False
# for attendance in old_attendances:
# attendance.delete()
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def save(self, *args, **kwargs):
# if settings.SUBSCRIPTION_NEEDS_INVITATION and self.invitee is None:
# raise exceptions.PermissionDenied(_("Only invited Persons can register."))
# super(Participant, self).save(*args, **kwargs)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, ParticipantAdmin)
#
# callback_functions = [] # empty array
#
# @classmethod
# def register_callback(cls, callback_fn, events):
# cls.callback_functions.append({'fn': callback_fn, 'events': events})
#
# Path: woodstock/models/invitee.py
# class Invitee(Person):
# groups = models.ManyToManyField('woodstock.Group', related_name="invitations", blank=True)
#
# class Meta:
# verbose_name = 'Einladung'
# verbose_name_plural = 'Einladungen'
# ordering = ('surname',)
# app_label = 'woodstock'
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, InviteeAdmin)
. Output only the next line. | if self.invitation_required and not isinstance(request.user, Invitee): |
Predict the next line for this snippet: <|code_start|>
PAGE_PERMISSIONS = (
(0, 'Alle'),
(1, 'Teilnehmer'),
(2, 'Einladungen'),
(3, 'Teilnehmer oder Einladung'),
)
def check_permission_request_processor(self, request):
if self.woodstock_permissions in (1, 3):
<|code_end|>
with the help of current file imports:
from django.db import models
from django.http import HttpResponseRedirect
from woodstock.models import Participant, Invitee
and context from other files:
# Path: woodstock/models/participant.py
# class Participant(Person):
# event_parts = models.ManyToManyField('woodstock.EventPart', related_name="participants",
# blank=True, through="Attendance")
# invitee = models.ForeignKey('woodstock.Invitee', blank=True, null=True,
# default=None, related_name="participants")
#
# class Meta:
# ordering = ('surname',)
# verbose_name = 'Participant'
# verbose_name_plural = 'Participants'
# app_label = 'woodstock'
#
# def _attend_events(self, event_parts):
# """
# Attend events without callback and other functianlity.
# """
# attendances = []
# success = True
# for part in event_parts:
# success &= not part.fully_booked()
# attendances.append(Attendance.objects.create(participant=self,
# event_part=part, confirmed=True))
# if success:
# return attendances
# # remove confirmation if something didn't went well
# for attendance in attendances:
# attendance.confirmed = False
# attendance.save()
# return False
#
# @callback('attend_events')
# def attend_events(self, event_parts):
# """
# tries to attend all parts in event_parts
# """
# from woodstock.models import Event
# if settings.SUBSCRIPTION_CONSUMES_INVITATION and self.attendances.count():
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS or not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS:
# events = Event.objects.active().filter(
# models.Q(parts__attendances__confirmed=True, parts__attendances__participant=self)
# | models.Q(parts__in=event_parts)
# )
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS and events.distinct().count() > 1:
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS and events.distinct().count() != events.count():
# raise exceptions.PermissionDenied(_("You can only attend one eventpart per event."))
# attendances = self._attend_events(event_parts)
# if not attendances:
# return False
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def _cancel_events(self, event_parts, delete=True):
# """
# Cancels event attendances
# """
# if event_parts:
# queryset = self.attendances.filter(event_part__in=event_parts)
# else:
# queryset = self.attendances.all()
# attendances = []
# for attendance in queryset:
# attendances.append(attendance)
# if delete:
# attendance.delete()
# return attendances
#
# @callback('cancel_events')
# def cancel_events(self, event_parts=None):
# """
# Cancels all event attendances to events in event_parts. If event_parts
# is omited all attendances are cancled.
# """
# from woodstock.models import Event
# attendances = self._cancel_events(event_parts)
# # send emails
# for event in Event.objects.filter(parts__in=list(a.event_part for a in attendances)):
# event.send_unsubscribe_mail(self)
# return attendances
#
# @callback('change_events')
# def change_events(self, new_event_parts, old_event_parts=None):
# """
# Changes event attendances. If old_event_parts is omited all current
# attendances are deleted.
# """
# from woodstock.models import Event
#
# old_attendances = self._cancel_events(old_event_parts, delete=False)
# attendances = self._attend_events(new_event_parts)
# if not attendances:
# return False
# for attendance in old_attendances:
# attendance.delete()
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def save(self, *args, **kwargs):
# if settings.SUBSCRIPTION_NEEDS_INVITATION and self.invitee is None:
# raise exceptions.PermissionDenied(_("Only invited Persons can register."))
# super(Participant, self).save(*args, **kwargs)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, ParticipantAdmin)
#
# callback_functions = [] # empty array
#
# @classmethod
# def register_callback(cls, callback_fn, events):
# cls.callback_functions.append({'fn': callback_fn, 'events': events})
#
# Path: woodstock/models/invitee.py
# class Invitee(Person):
# groups = models.ManyToManyField('woodstock.Group', related_name="invitations", blank=True)
#
# class Meta:
# verbose_name = 'Einladung'
# verbose_name_plural = 'Einladungen'
# ordering = ('surname',)
# app_label = 'woodstock'
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, InviteeAdmin)
, which may contain function names, class names, or code. Output only the next line. | if isinstance(request.user, Participant): |
Using the snippet: <|code_start|>
PAGE_PERMISSIONS = (
(0, 'Alle'),
(1, 'Teilnehmer'),
(2, 'Einladungen'),
(3, 'Teilnehmer oder Einladung'),
)
def check_permission_request_processor(self, request):
if self.woodstock_permissions in (1, 3):
if isinstance(request.user, Participant):
return
if self.woodstock_permissions in (2, 3):
<|code_end|>
, determine the next line of code. You have imports:
from django.db import models
from django.http import HttpResponseRedirect
from woodstock.models import Participant, Invitee
and context (class names, function names, or code) available:
# Path: woodstock/models/participant.py
# class Participant(Person):
# event_parts = models.ManyToManyField('woodstock.EventPart', related_name="participants",
# blank=True, through="Attendance")
# invitee = models.ForeignKey('woodstock.Invitee', blank=True, null=True,
# default=None, related_name="participants")
#
# class Meta:
# ordering = ('surname',)
# verbose_name = 'Participant'
# verbose_name_plural = 'Participants'
# app_label = 'woodstock'
#
# def _attend_events(self, event_parts):
# """
# Attend events without callback and other functianlity.
# """
# attendances = []
# success = True
# for part in event_parts:
# success &= not part.fully_booked()
# attendances.append(Attendance.objects.create(participant=self,
# event_part=part, confirmed=True))
# if success:
# return attendances
# # remove confirmation if something didn't went well
# for attendance in attendances:
# attendance.confirmed = False
# attendance.save()
# return False
#
# @callback('attend_events')
# def attend_events(self, event_parts):
# """
# tries to attend all parts in event_parts
# """
# from woodstock.models import Event
# if settings.SUBSCRIPTION_CONSUMES_INVITATION and self.attendances.count():
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS or not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS:
# events = Event.objects.active().filter(
# models.Q(parts__attendances__confirmed=True, parts__attendances__participant=self)
# | models.Q(parts__in=event_parts)
# )
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTS and events.distinct().count() > 1:
# raise exceptions.PermissionDenied(_("You can only attend one event."))
# if not settings.SUBSCRIPTION_ALLOW_MULTIPLE_EVENTPARTS and events.distinct().count() != events.count():
# raise exceptions.PermissionDenied(_("You can only attend one eventpart per event."))
# attendances = self._attend_events(event_parts)
# if not attendances:
# return False
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def _cancel_events(self, event_parts, delete=True):
# """
# Cancels event attendances
# """
# if event_parts:
# queryset = self.attendances.filter(event_part__in=event_parts)
# else:
# queryset = self.attendances.all()
# attendances = []
# for attendance in queryset:
# attendances.append(attendance)
# if delete:
# attendance.delete()
# return attendances
#
# @callback('cancel_events')
# def cancel_events(self, event_parts=None):
# """
# Cancels all event attendances to events in event_parts. If event_parts
# is omited all attendances are cancled.
# """
# from woodstock.models import Event
# attendances = self._cancel_events(event_parts)
# # send emails
# for event in Event.objects.filter(parts__in=list(a.event_part for a in attendances)):
# event.send_unsubscribe_mail(self)
# return attendances
#
# @callback('change_events')
# def change_events(self, new_event_parts, old_event_parts=None):
# """
# Changes event attendances. If old_event_parts is omited all current
# attendances are deleted.
# """
# from woodstock.models import Event
#
# old_attendances = self._cancel_events(old_event_parts, delete=False)
# attendances = self._attend_events(new_event_parts)
# if not attendances:
# return False
# for attendance in old_attendances:
# attendance.delete()
# # send emails
# for event in Event.objects.for_attendances(attendances):
# event.send_subscribe_mail(self)
# return attendances
#
# def save(self, *args, **kwargs):
# if settings.SUBSCRIPTION_NEEDS_INVITATION and self.invitee is None:
# raise exceptions.PermissionDenied(_("Only invited Persons can register."))
# super(Participant, self).save(*args, **kwargs)
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, ParticipantAdmin)
#
# callback_functions = [] # empty array
#
# @classmethod
# def register_callback(cls, callback_fn, events):
# cls.callback_functions.append({'fn': callback_fn, 'events': events})
#
# Path: woodstock/models/invitee.py
# class Invitee(Person):
# groups = models.ManyToManyField('woodstock.Group', related_name="invitations", blank=True)
#
# class Meta:
# verbose_name = 'Einladung'
# verbose_name_plural = 'Einladungen'
# ordering = ('surname',)
# app_label = 'woodstock'
#
# @classmethod
# def register_extension(cls, register_fn):
# register_fn(cls, InviteeAdmin)
. Output only the next line. | if isinstance(request.user, Invitee): |
Here is a snippet: <|code_start|> account=account,
name=self.name.split('/')[-1],
) or self.name
tag = _tag or tag or self.tag
if use_digest:
name = '{name}@{digest}'.format(name=name, digest=tag)
tag = None
return self.__class__(name=name, tag=tag, registry=registry)
def get_field_name(self, owner_cls):
field_name = self.field_names.get(owner_cls)
if field_name is None:
for attr in dir(owner_cls):
if getattr(owner_cls, attr) is self:
if field_name is not None:
raise ValueError(
'Same instance of Image used for more than one '
'attribute of class {cls}'.format(
cls=owner_cls.__name__,
)
)
self.field_names[owner_cls] = field_name = attr
return field_name
@staticmethod
def parse_image_name(image):
if not image:
return None, None, None
<|code_end|>
. Write the next line using the current file imports:
import json
import warnings
import docker.auth
import docker.utils
import six
import fabricio
from functools import partial
from fabricio import utils
and context from other files:
# Path: fabricio/utils.py
# DEFAULT = object()
# def patch(obj, attr, value, default=DEFAULT, force_delete=False):
# def __init__(self, func=None, default=None):
# def __get__(self, instance, owner=None):
# def __call__(self, func):
# def make_option(self, option, value=None):
# def make_options(self):
# def __str__(self):
# def strtobool(value):
# def once_per_command(*args, **kwargs): # pragma: no cover
# def __init__(self, iterable=None, priority=None, **kwargs):
# def items(self):
# def __init__(self, iterable=None):
# def __len__(self):
# def __contains__(self, key):
# def add(self, key):
# def discard(self, key):
# def __iter__(self):
# def __reversed__(self):
# def pop(self, last=True):
# def __repr__(self):
# def __eq__(self, other):
# class default_property(object):
# class Options(collections.OrderedDict):
# class AttrDict(dict):
# class PriorityDict(dict):
# class OrderedSet(collections.MutableSet): # pragma: no cover
, which may include functions, classes, or code. Output only the next line. | repository, tag = docker.utils.parse_repository_tag(image) |
Continue the code snippet: <|code_start|> for part in re.split(r'(?<!\\),', string):
if not part.startswith(option + '='):
continue
value = shlex.split(part.split('=', 1)[-1])
return value and value[0] or None
class ServiceNotFoundError(ServiceError):
pass
class RemovableOption(Option):
path = NotImplemented
force_add = False
force_rm = False
def cast_rm(self, value):
return value
def __init__(self, func=None, path=None, force_add=None, force_rm=None, **kwargs): # noqa
super(RemovableOption, self).__init__(func=func, **kwargs)
self.path = path or self.path
self.force_add = force_add if force_add is not None else self.force_add
self.force_rm = force_rm if force_rm is not None else self.force_rm
def get_values_to_add(self, service, attr):
new_values = self.get_new_values(service, attr)
<|code_end|>
. Use current file imports:
import functools
import hashlib
import itertools
import json
import re
import shlex
import dpath
import six
import fabricio
from cached_property import cached_property
from frozendict import frozendict
from six.moves import map, shlex_quote, range
from fabricio import utils
from .base import ManagedService, Option, Attribute, ServiceError
and context (classes, functions, or code) from other files:
# Path: fabricio/utils.py
# DEFAULT = object()
# def patch(obj, attr, value, default=DEFAULT, force_delete=False):
# def __init__(self, func=None, default=None):
# def __get__(self, instance, owner=None):
# def __call__(self, func):
# def make_option(self, option, value=None):
# def make_options(self):
# def __str__(self):
# def strtobool(value):
# def once_per_command(*args, **kwargs): # pragma: no cover
# def __init__(self, iterable=None, priority=None, **kwargs):
# def items(self):
# def __init__(self, iterable=None):
# def __len__(self):
# def __contains__(self, key):
# def add(self, key):
# def discard(self, key):
# def __iter__(self):
# def __reversed__(self):
# def pop(self, last=True):
# def __repr__(self):
# def __eq__(self, other):
# class default_property(object):
# class Options(collections.OrderedDict):
# class AttrDict(dict):
# class PriorityDict(dict):
# class OrderedSet(collections.MutableSet): # pragma: no cover
#
# Path: fabricio/docker/base.py
# class ManagedService(BaseService):
#
# def __init__(self, *args, **kwargs):
# super(ManagedService, self).__init__(*args, **kwargs)
# self.managers = multiprocessing.Manager().dict()
#
# def _is_manager(self):
# command = 'docker info 2>&1 | grep "Is Manager:"'
# return fabricio.run(command).endswith('true')
#
# def is_manager(self, raise_manager_error=True):
# is_manager = self.managers.get(fab.env.host)
# try:
# if is_manager is None:
# is_manager = self.managers[fab.env.host] = self._is_manager()
# except fabricio.host_errors as error:
# is_manager = self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
# finally:
# if (
# raise_manager_error
# and len(self.managers) >= len(fab.env.all_hosts)
# and not any(self.managers.values())
# ):
# msg = 'service manager not found or it failed to pull image'
# raise ManagerNotFoundError(msg)
# return is_manager
#
# def pull_image(self, *args, **kwargs):
# try:
# return super(ManagedService, self).pull_image(*args, **kwargs)
# except fabricio.host_errors as error:
# self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
#
# def migrate(self, *args, **kwargs):
# if self.is_manager():
# super(ManagedService, self).migrate(*args, **kwargs)
#
# def migrate_back(self):
# if self.is_manager():
# super(ManagedService, self).migrate_back()
#
# def backup(self):
# if self.is_manager():
# super(ManagedService, self).backup()
#
# def restore(self, backup_name=None):
# if self.is_manager():
# super(ManagedService, self).restore(backup_name=backup_name)
#
# class Option(utils.default_property):
#
# def __init__(
# self,
# func=None,
# default=None,
# name=None,
# safe=False,
# safe_name=None,
# ):
# super(Option, self).__init__(func=func, default=default)
# self.name = name
# self.safe = safe
# self.safe_name = safe_name
#
# class Attribute(utils.default_property):
# pass
#
# class ServiceError(fabricio.Error):
# pass
. Output only the next line. | new_values = utils.OrderedSet(new_values) |
Next line prediction: <|code_start|>class HostOption(RemovableOption):
path = '/Spec/TaskTemplate/ContainerSpec/Hosts/*'
def get_current_values(self, *args, **kwargs):
values = super(HostOption, self).get_current_values(*args, **kwargs)
# 'ip host' => 'host:ip'
return map(lambda value: ':'.join(value.split(' ', 1)[::-1]), values)
class PlacementPrefOption(RemovableOption):
path = '/Spec/TaskTemplate/Placement/Preferences/*'
force_add = True
force_rm = True
def get_current_values(self, *args, **kwargs):
values = super(PlacementPrefOption, self).get_current_values(*args, **kwargs) # noqa
for value in values:
yield ','.join(
'{strategy}={descriptor}'.format(
strategy=strategy.lower(),
descriptor=shlex_quote(descriptor[strategy + 'Descriptor'])
)
for strategy, descriptor in value.items()
)
<|code_end|>
. Use current file imports:
(import functools
import hashlib
import itertools
import json
import re
import shlex
import dpath
import six
import fabricio
from cached_property import cached_property
from frozendict import frozendict
from six.moves import map, shlex_quote, range
from fabricio import utils
from .base import ManagedService, Option, Attribute, ServiceError)
and context including class names, function names, or small code snippets from other files:
# Path: fabricio/utils.py
# DEFAULT = object()
# def patch(obj, attr, value, default=DEFAULT, force_delete=False):
# def __init__(self, func=None, default=None):
# def __get__(self, instance, owner=None):
# def __call__(self, func):
# def make_option(self, option, value=None):
# def make_options(self):
# def __str__(self):
# def strtobool(value):
# def once_per_command(*args, **kwargs): # pragma: no cover
# def __init__(self, iterable=None, priority=None, **kwargs):
# def items(self):
# def __init__(self, iterable=None):
# def __len__(self):
# def __contains__(self, key):
# def add(self, key):
# def discard(self, key):
# def __iter__(self):
# def __reversed__(self):
# def pop(self, last=True):
# def __repr__(self):
# def __eq__(self, other):
# class default_property(object):
# class Options(collections.OrderedDict):
# class AttrDict(dict):
# class PriorityDict(dict):
# class OrderedSet(collections.MutableSet): # pragma: no cover
#
# Path: fabricio/docker/base.py
# class ManagedService(BaseService):
#
# def __init__(self, *args, **kwargs):
# super(ManagedService, self).__init__(*args, **kwargs)
# self.managers = multiprocessing.Manager().dict()
#
# def _is_manager(self):
# command = 'docker info 2>&1 | grep "Is Manager:"'
# return fabricio.run(command).endswith('true')
#
# def is_manager(self, raise_manager_error=True):
# is_manager = self.managers.get(fab.env.host)
# try:
# if is_manager is None:
# is_manager = self.managers[fab.env.host] = self._is_manager()
# except fabricio.host_errors as error:
# is_manager = self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
# finally:
# if (
# raise_manager_error
# and len(self.managers) >= len(fab.env.all_hosts)
# and not any(self.managers.values())
# ):
# msg = 'service manager not found or it failed to pull image'
# raise ManagerNotFoundError(msg)
# return is_manager
#
# def pull_image(self, *args, **kwargs):
# try:
# return super(ManagedService, self).pull_image(*args, **kwargs)
# except fabricio.host_errors as error:
# self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
#
# def migrate(self, *args, **kwargs):
# if self.is_manager():
# super(ManagedService, self).migrate(*args, **kwargs)
#
# def migrate_back(self):
# if self.is_manager():
# super(ManagedService, self).migrate_back()
#
# def backup(self):
# if self.is_manager():
# super(ManagedService, self).backup()
#
# def restore(self, backup_name=None):
# if self.is_manager():
# super(ManagedService, self).restore(backup_name=backup_name)
#
# class Option(utils.default_property):
#
# def __init__(
# self,
# func=None,
# default=None,
# name=None,
# safe=False,
# safe_name=None,
# ):
# super(Option, self).__init__(func=func, default=default)
# self.name = name
# self.safe = safe
# self.safe_name = safe_name
#
# class Attribute(utils.default_property):
# pass
#
# class ServiceError(fabricio.Error):
# pass
. Output only the next line. | class Service(ManagedService): |
Given the following code snippet before the placeholder: <|code_start|>
def get_option_value(string, option):
"""
get option value from string with nested options
such as "source=from,destination=to"
"""
for part in re.split(r'(?<!\\),', string):
if not part.startswith(option + '='):
continue
value = shlex.split(part.split('=', 1)[-1])
return value and value[0] or None
class ServiceNotFoundError(ServiceError):
pass
<|code_end|>
, predict the next line using imports from the current file:
import functools
import hashlib
import itertools
import json
import re
import shlex
import dpath
import six
import fabricio
from cached_property import cached_property
from frozendict import frozendict
from six.moves import map, shlex_quote, range
from fabricio import utils
from .base import ManagedService, Option, Attribute, ServiceError
and context including class names, function names, and sometimes code from other files:
# Path: fabricio/utils.py
# DEFAULT = object()
# def patch(obj, attr, value, default=DEFAULT, force_delete=False):
# def __init__(self, func=None, default=None):
# def __get__(self, instance, owner=None):
# def __call__(self, func):
# def make_option(self, option, value=None):
# def make_options(self):
# def __str__(self):
# def strtobool(value):
# def once_per_command(*args, **kwargs): # pragma: no cover
# def __init__(self, iterable=None, priority=None, **kwargs):
# def items(self):
# def __init__(self, iterable=None):
# def __len__(self):
# def __contains__(self, key):
# def add(self, key):
# def discard(self, key):
# def __iter__(self):
# def __reversed__(self):
# def pop(self, last=True):
# def __repr__(self):
# def __eq__(self, other):
# class default_property(object):
# class Options(collections.OrderedDict):
# class AttrDict(dict):
# class PriorityDict(dict):
# class OrderedSet(collections.MutableSet): # pragma: no cover
#
# Path: fabricio/docker/base.py
# class ManagedService(BaseService):
#
# def __init__(self, *args, **kwargs):
# super(ManagedService, self).__init__(*args, **kwargs)
# self.managers = multiprocessing.Manager().dict()
#
# def _is_manager(self):
# command = 'docker info 2>&1 | grep "Is Manager:"'
# return fabricio.run(command).endswith('true')
#
# def is_manager(self, raise_manager_error=True):
# is_manager = self.managers.get(fab.env.host)
# try:
# if is_manager is None:
# is_manager = self.managers[fab.env.host] = self._is_manager()
# except fabricio.host_errors as error:
# is_manager = self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
# finally:
# if (
# raise_manager_error
# and len(self.managers) >= len(fab.env.all_hosts)
# and not any(self.managers.values())
# ):
# msg = 'service manager not found or it failed to pull image'
# raise ManagerNotFoundError(msg)
# return is_manager
#
# def pull_image(self, *args, **kwargs):
# try:
# return super(ManagedService, self).pull_image(*args, **kwargs)
# except fabricio.host_errors as error:
# self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
#
# def migrate(self, *args, **kwargs):
# if self.is_manager():
# super(ManagedService, self).migrate(*args, **kwargs)
#
# def migrate_back(self):
# if self.is_manager():
# super(ManagedService, self).migrate_back()
#
# def backup(self):
# if self.is_manager():
# super(ManagedService, self).backup()
#
# def restore(self, backup_name=None):
# if self.is_manager():
# super(ManagedService, self).restore(backup_name=backup_name)
#
# class Option(utils.default_property):
#
# def __init__(
# self,
# func=None,
# default=None,
# name=None,
# safe=False,
# safe_name=None,
# ):
# super(Option, self).__init__(func=func, default=default)
# self.name = name
# self.safe = safe
# self.safe_name = safe_name
#
# class Attribute(utils.default_property):
# pass
#
# class ServiceError(fabricio.Error):
# pass
. Output only the next line. | class RemovableOption(Option): |
Given snippet: <|code_start|> def get_current_values(self, *args, **kwargs):
values = super(HostOption, self).get_current_values(*args, **kwargs)
# 'ip host' => 'host:ip'
return map(lambda value: ':'.join(value.split(' ', 1)[::-1]), values)
class PlacementPrefOption(RemovableOption):
path = '/Spec/TaskTemplate/Placement/Preferences/*'
force_add = True
force_rm = True
def get_current_values(self, *args, **kwargs):
values = super(PlacementPrefOption, self).get_current_values(*args, **kwargs) # noqa
for value in values:
yield ','.join(
'{strategy}={descriptor}'.format(
strategy=strategy.lower(),
descriptor=shlex_quote(descriptor[strategy + 'Descriptor'])
)
for strategy, descriptor in value.items()
)
class Service(ManagedService):
options_label_name = 'fabricio.service.options'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import hashlib
import itertools
import json
import re
import shlex
import dpath
import six
import fabricio
from cached_property import cached_property
from frozendict import frozendict
from six.moves import map, shlex_quote, range
from fabricio import utils
from .base import ManagedService, Option, Attribute, ServiceError
and context:
# Path: fabricio/utils.py
# DEFAULT = object()
# def patch(obj, attr, value, default=DEFAULT, force_delete=False):
# def __init__(self, func=None, default=None):
# def __get__(self, instance, owner=None):
# def __call__(self, func):
# def make_option(self, option, value=None):
# def make_options(self):
# def __str__(self):
# def strtobool(value):
# def once_per_command(*args, **kwargs): # pragma: no cover
# def __init__(self, iterable=None, priority=None, **kwargs):
# def items(self):
# def __init__(self, iterable=None):
# def __len__(self):
# def __contains__(self, key):
# def add(self, key):
# def discard(self, key):
# def __iter__(self):
# def __reversed__(self):
# def pop(self, last=True):
# def __repr__(self):
# def __eq__(self, other):
# class default_property(object):
# class Options(collections.OrderedDict):
# class AttrDict(dict):
# class PriorityDict(dict):
# class OrderedSet(collections.MutableSet): # pragma: no cover
#
# Path: fabricio/docker/base.py
# class ManagedService(BaseService):
#
# def __init__(self, *args, **kwargs):
# super(ManagedService, self).__init__(*args, **kwargs)
# self.managers = multiprocessing.Manager().dict()
#
# def _is_manager(self):
# command = 'docker info 2>&1 | grep "Is Manager:"'
# return fabricio.run(command).endswith('true')
#
# def is_manager(self, raise_manager_error=True):
# is_manager = self.managers.get(fab.env.host)
# try:
# if is_manager is None:
# is_manager = self.managers[fab.env.host] = self._is_manager()
# except fabricio.host_errors as error:
# is_manager = self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
# finally:
# if (
# raise_manager_error
# and len(self.managers) >= len(fab.env.all_hosts)
# and not any(self.managers.values())
# ):
# msg = 'service manager not found or it failed to pull image'
# raise ManagerNotFoundError(msg)
# return is_manager
#
# def pull_image(self, *args, **kwargs):
# try:
# return super(ManagedService, self).pull_image(*args, **kwargs)
# except fabricio.host_errors as error:
# self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
#
# def migrate(self, *args, **kwargs):
# if self.is_manager():
# super(ManagedService, self).migrate(*args, **kwargs)
#
# def migrate_back(self):
# if self.is_manager():
# super(ManagedService, self).migrate_back()
#
# def backup(self):
# if self.is_manager():
# super(ManagedService, self).backup()
#
# def restore(self, backup_name=None):
# if self.is_manager():
# super(ManagedService, self).restore(backup_name=backup_name)
#
# class Option(utils.default_property):
#
# def __init__(
# self,
# func=None,
# default=None,
# name=None,
# safe=False,
# safe_name=None,
# ):
# super(Option, self).__init__(func=func, default=default)
# self.name = name
# self.safe = safe
# self.safe_name = safe_name
#
# class Attribute(utils.default_property):
# pass
#
# class ServiceError(fabricio.Error):
# pass
which might include code, classes, or functions. Output only the next line. | command = Attribute() |
Here is a snippet: <|code_start|>
def get_option_value(string, option):
"""
get option value from string with nested options
such as "source=from,destination=to"
"""
for part in re.split(r'(?<!\\),', string):
if not part.startswith(option + '='):
continue
value = shlex.split(part.split('=', 1)[-1])
return value and value[0] or None
<|code_end|>
. Write the next line using the current file imports:
import functools
import hashlib
import itertools
import json
import re
import shlex
import dpath
import six
import fabricio
from cached_property import cached_property
from frozendict import frozendict
from six.moves import map, shlex_quote, range
from fabricio import utils
from .base import ManagedService, Option, Attribute, ServiceError
and context from other files:
# Path: fabricio/utils.py
# DEFAULT = object()
# def patch(obj, attr, value, default=DEFAULT, force_delete=False):
# def __init__(self, func=None, default=None):
# def __get__(self, instance, owner=None):
# def __call__(self, func):
# def make_option(self, option, value=None):
# def make_options(self):
# def __str__(self):
# def strtobool(value):
# def once_per_command(*args, **kwargs): # pragma: no cover
# def __init__(self, iterable=None, priority=None, **kwargs):
# def items(self):
# def __init__(self, iterable=None):
# def __len__(self):
# def __contains__(self, key):
# def add(self, key):
# def discard(self, key):
# def __iter__(self):
# def __reversed__(self):
# def pop(self, last=True):
# def __repr__(self):
# def __eq__(self, other):
# class default_property(object):
# class Options(collections.OrderedDict):
# class AttrDict(dict):
# class PriorityDict(dict):
# class OrderedSet(collections.MutableSet): # pragma: no cover
#
# Path: fabricio/docker/base.py
# class ManagedService(BaseService):
#
# def __init__(self, *args, **kwargs):
# super(ManagedService, self).__init__(*args, **kwargs)
# self.managers = multiprocessing.Manager().dict()
#
# def _is_manager(self):
# command = 'docker info 2>&1 | grep "Is Manager:"'
# return fabricio.run(command).endswith('true')
#
# def is_manager(self, raise_manager_error=True):
# is_manager = self.managers.get(fab.env.host)
# try:
# if is_manager is None:
# is_manager = self.managers[fab.env.host] = self._is_manager()
# except fabricio.host_errors as error:
# is_manager = self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
# finally:
# if (
# raise_manager_error
# and len(self.managers) >= len(fab.env.all_hosts)
# and not any(self.managers.values())
# ):
# msg = 'service manager not found or it failed to pull image'
# raise ManagerNotFoundError(msg)
# return is_manager
#
# def pull_image(self, *args, **kwargs):
# try:
# return super(ManagedService, self).pull_image(*args, **kwargs)
# except fabricio.host_errors as error:
# self.managers[fab.env.host] = False
# fabricio.log(
# 'WARNING: {error}'.format(error=error),
# output=sys.stderr,
# color=colors.red,
# )
#
# def migrate(self, *args, **kwargs):
# if self.is_manager():
# super(ManagedService, self).migrate(*args, **kwargs)
#
# def migrate_back(self):
# if self.is_manager():
# super(ManagedService, self).migrate_back()
#
# def backup(self):
# if self.is_manager():
# super(ManagedService, self).backup()
#
# def restore(self, backup_name=None):
# if self.is_manager():
# super(ManagedService, self).restore(backup_name=backup_name)
#
# class Option(utils.default_property):
#
# def __init__(
# self,
# func=None,
# default=None,
# name=None,
# safe=False,
# safe_name=None,
# ):
# super(Option, self).__init__(func=func, default=default)
# self.name = name
# self.safe = safe
# self.safe_name = safe_name
#
# class Attribute(utils.default_property):
# pass
#
# class ServiceError(fabricio.Error):
# pass
, which may include functions, classes, or code. Output only the next line. | class ServiceNotFoundError(ServiceError): |
Given the code snippet: <|code_start|># through RabbitMQ. This may be slightly faster than it's twisted-based cousin.
sys.path.append(os.path.dirname(__file__))
if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
logger = pygowave_rpc.logger.setupLogging()
if pygowave_rpc.logger.logMode() == "verbose":
amqplogger = logging.getLogger("amqplib")
amqplogger.setLevel(logging.DEBUG)
amqplogger.addHandler(logging.StreamHandler())
logger.info("=> PyGoWave RPC Server starting <=")
# Python Ctrl-C handler
signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
amqpconn = AMQPConnection(
hostname=getattr(settings, "RPC_SERVER", "localhost"),
userid=getattr(settings, "RPC_USER", "pygowave_server"),
password=getattr(settings, "RPC_PASSWORD", "pygowave_server"),
virtual_host=getattr(settings, "AMQP_VHOST", "/"),
port=getattr(settings, "AMQP_PORT", 5672)
)
<|code_end|>
, generate the next line using the imports in this file:
import sys, os, logging
import pygowave_rpc.logger
import signal
import traceback
from carrot.connection import AMQPConnection
from pygowave_rpc.amqp_client import AmqpMessageProcessor
from django.conf import settings
and context (functions, classes, or occasionally code) from other files:
# Path: pygowave_rpc/amqp_client.py
# class AmqpMessageProcessor(object):
# purge_every = datetime.timedelta(minutes=10)
# conn_lifetime = datetime.timedelta(minutes=getattr(settings, "ACCESS_KEY_TIMEOUT_MINUTES", 2))
#
# def __init__(self, connection):
# self.pygo_mp = PyGoWaveClientMessageProcessor()
# self.consumer = Consumer(
# connection,
# queue="wavelet_rpc_singlethread",
# exchange="wavelet.topic",
# routing_key="#.#.clientop",
# exchange_type="topic",
# serializer="json",
# auto_ack=True,
# )
# self.consumer.register_callback(self.receive)
# self.publisher = Publisher(
# connection,
# exchange="wavelet.direct",
# exchange_type="direct",
# delivery_mode=1,
# serializer="json",
# )
#
# self.pygo_mp.purge_connections()
# self.next_purge = datetime.datetime.now() + self.purge_every
#
# def wait(self, limit=None):
# self.consumer.wait(limit)
#
# def send(self, routing_key, message_data):
# self.publisher.send(message_data, routing_key=routing_key, delivery_mode=1)
#
# def receive(self, message_data, message):
# routing_key = message.amqp_message.routing_key
#
# msg_dict = self.pygo_mp.process(routing_key, message_data)
#
# for out_rkey, messages in msg_dict.iteritems():
# self.send(out_rkey, messages)
#
# # Cleanup time?
# if datetime.datetime.now() > self.next_purge:
# self.pygo_mp.purge_connections()
# self.next_purge = datetime.datetime.now() + self.purge_every
. Output only the next line. | omc = AmqpMessageProcessor(amqpconn) |
Continue the code snippet: <|code_start|>
class MyRegistrationForm(RegistrationForm):
def clean_username(self):
"""
Validate that the username is at least three characters long.
"""
username = super(MyRegistrationForm, self).clean_username()
if len(username) < 3:
raise forms.ValidationError(_(u'Your desired username is too short. Please enter at least three characters.'))
return username
class AvatarWidget(widgets.FileInput):
def __init__(self, size=(40, 40), prefix="", attrs=None):
super(AvatarWidget, self).__init__(attrs)
self.size = tuple(size)
self.hidden_input = widgets.HiddenInput()
self.prefix = prefix
def value_from_datadict(self, data, files, name):
v = files.get(name, None)
if v == None: # Nothing uploaded, look for already uploaded file
oldfile = self.prefix + data.get(name + "_old", None)
if oldfile.startswith(settings.AVATAR_URL):
oldfile = oldfile[len(settings.AVATAR_URL):]
path = settings.AVATAR_ROOT + oldfile
open("/tmp/test", "w").write(path+"\n")
if os.path.exists(path):
<|code_end|>
. Use current file imports:
from django import forms
from django.forms import widgets
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.core.files.uploadedfile import UploadedFile
from django.utils.hashcompat import sha_constructor
from random import random
from pygowave_server.utils import AlreadyUploadedFile, get_profile_model
from pygowave_server.models import Gadget
from registration.forms import RegistrationForm
from PIL import Image
from lxml.etree import XMLSyntaxError
from pygowave_server.engine import GadgetLoader
import os, urllib2
and context (classes, functions, or code) from other files:
# Path: pygowave_server/utils.py
# class AlreadyUploadedFile(UploadedFile):
# """
# This class is used to mark files, which have already been uploaded and
# stored. It still can be opened and read.
#
# """
# def __init__(self, path, name, size):
# super(AlreadyUploadedFile, self).__init__(name, size=size)
# self.path = path
# self._file = None
#
# def open(self):
# self._file = open(path, "r")
#
# def seek(self, pos):
# if self._file != None:
# self._file.seek(pos)
#
# def tell(self):
# if self._file == None: return 0
# return self._file.tell()
#
# def read(self, num_bytes=None):
# if self._file == None: self.open()
# if num_bytes == None:
# return self._file.read()
# else:
# return self._file.read(num_bytes)
#
# def reset(self):
# self._file.reset()
#
# def close(self):
# self._file.close()
#
# def temporary_file_path(self):
# """
# Emulate behaviour of temporary uploaded files.
#
# """
# return self.path
#
# def get_profile_model():
# """
# Return the user profile model class as defined by the AUTH_PROFILE_MODULE
# setting. If that setting is missing SiteProfileNotAvailable is raised.
#
# """
# if not hasattr(settings, 'AUTH_PROFILE_MODULE') or settings.AUTH_PROFILE_MODULE == None:
# raise SiteProfileNotAvailable
#
# profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
# if profile_mod is None:
# raise SiteProfileNotAvailable
#
# return profile_mod
#
# Path: pygowave_server/models.py
# class Gadget(models.Model):
# """
# A gadget that has been uploaded or is referenced on this server.
# Users can register their gadgets on this server to conveniently add them
# to a Wave.
#
# Note: A uploaded gadget is never deleted from disk as it may be used by
# other waves. An exception to this are Gadget marked as "devel" versions.
# Those Gadgets can be simply overwritten and thus replace already running
# instances.
#
# """
#
# by_user = models.ForeignKey(User, related_name="my_gadgets")
# title = models.CharField(max_length=255, unique=True, verbose_name=_(u'Title'))
# description = models.CharField(max_length=255, blank=True, verbose_name=_(u'Description'))
# url = models.URLField(blank=True, verbose_name=_(u'URL'))
# hosted_filename = models.CharField(max_length=255, blank=True, verbose_name=_(u'Hosted filename'))
# devel = models.BooleanField(default=False, verbose_name=_(u'Development version'))
#
# def is_hosted(self):
# return len(self.hosted_filename) > 0
#
# def instantiate(self):
# """
# Create a GadgetElement from this Gadget.
#
# """
# return GadgetElement(url=self.url)
#
# def __unicode__(self):
# return u"Gadget '%s' by '%s'" % (self.title, self.by_user.username)
. Output only the next line. | return AlreadyUploadedFile(path, oldfile, os.path.getsize(path)) |
Given the following code snippet before the placeholder: <|code_start|> if not isinstance(value, AlreadyUploadedFile):
# Add prefix to avoid overwriting of files with the same name
prefix = sha_constructor(str(random())).hexdigest()[:4] + "_"
filename = settings.AVATAR_ROOT + prefix + value.name
destination = open(filename, 'wb')
for chunk in value.chunks():
destination.write(chunk)
destination.close()
if isinstance(self.widget, AvatarWidget):
# Resize
img = Image.open(filename)
size = self.widget.size
if img.size[0] < size[0] or img.size[1] < size[1]:
img.resize(self.widget.size, Image.CUBIC).save(filename)
elif img.size != size:
img.resize(self.widget.size, Image.ANTIALIAS).save(filename)
# Set prefix
self.widget.prefix = prefix
return settings.AVATAR_URL + prefix + value.name
return settings.AVATAR_URL + value.name
class ParticipantProfileForm(forms.ModelForm):
avatar = AvatarField(required=False)
profile = forms.CharField(max_length=200, required=False, label=_(u'Profile URL'))
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from django.forms import widgets
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.core.files.uploadedfile import UploadedFile
from django.utils.hashcompat import sha_constructor
from random import random
from pygowave_server.utils import AlreadyUploadedFile, get_profile_model
from pygowave_server.models import Gadget
from registration.forms import RegistrationForm
from PIL import Image
from lxml.etree import XMLSyntaxError
from pygowave_server.engine import GadgetLoader
import os, urllib2
and context including class names, function names, and sometimes code from other files:
# Path: pygowave_server/utils.py
# class AlreadyUploadedFile(UploadedFile):
# """
# This class is used to mark files, which have already been uploaded and
# stored. It still can be opened and read.
#
# """
# def __init__(self, path, name, size):
# super(AlreadyUploadedFile, self).__init__(name, size=size)
# self.path = path
# self._file = None
#
# def open(self):
# self._file = open(path, "r")
#
# def seek(self, pos):
# if self._file != None:
# self._file.seek(pos)
#
# def tell(self):
# if self._file == None: return 0
# return self._file.tell()
#
# def read(self, num_bytes=None):
# if self._file == None: self.open()
# if num_bytes == None:
# return self._file.read()
# else:
# return self._file.read(num_bytes)
#
# def reset(self):
# self._file.reset()
#
# def close(self):
# self._file.close()
#
# def temporary_file_path(self):
# """
# Emulate behaviour of temporary uploaded files.
#
# """
# return self.path
#
# def get_profile_model():
# """
# Return the user profile model class as defined by the AUTH_PROFILE_MODULE
# setting. If that setting is missing SiteProfileNotAvailable is raised.
#
# """
# if not hasattr(settings, 'AUTH_PROFILE_MODULE') or settings.AUTH_PROFILE_MODULE == None:
# raise SiteProfileNotAvailable
#
# profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
# if profile_mod is None:
# raise SiteProfileNotAvailable
#
# return profile_mod
#
# Path: pygowave_server/models.py
# class Gadget(models.Model):
# """
# A gadget that has been uploaded or is referenced on this server.
# Users can register their gadgets on this server to conveniently add them
# to a Wave.
#
# Note: A uploaded gadget is never deleted from disk as it may be used by
# other waves. An exception to this are Gadget marked as "devel" versions.
# Those Gadgets can be simply overwritten and thus replace already running
# instances.
#
# """
#
# by_user = models.ForeignKey(User, related_name="my_gadgets")
# title = models.CharField(max_length=255, unique=True, verbose_name=_(u'Title'))
# description = models.CharField(max_length=255, blank=True, verbose_name=_(u'Description'))
# url = models.URLField(blank=True, verbose_name=_(u'URL'))
# hosted_filename = models.CharField(max_length=255, blank=True, verbose_name=_(u'Hosted filename'))
# devel = models.BooleanField(default=False, verbose_name=_(u'Development version'))
#
# def is_hosted(self):
# return len(self.hosted_filename) > 0
#
# def instantiate(self):
# """
# Create a GadgetElement from this Gadget.
#
# """
# return GadgetElement(url=self.url)
#
# def __unicode__(self):
# return u"Gadget '%s' by '%s'" % (self.title, self.by_user.username)
. Output only the next line. | model = get_profile_model() |
Predict the next line for this snippet: <|code_start|> if self.cleaned_data["upload"] == "":
raise forms.ValidationError(_(u'You must upload a file or choose "External URL" and enter an URL.'))
# Set URL by uploaded file
self.cleaned_data["url"] = settings.GADGET_URL + self.cleaned_data["upload"]
# Local path
url = "file://" + settings.GADGET_ROOT + self.cleaned_data["upload"]
# Check Gadget
try:
gadget = GadgetLoader(url)
except urllib2.HTTPError:
raise forms.ValidationError(_(u'Gadget could not be downloaded.'))
except XMLSyntaxError:
if not self.external_url():
os.remove(settings.GADGET_ROOT + self.cleaned_data["upload"])
raise forms.ValidationError(_(u'Gadget quick-check failed: Bad XML format.'))
except ValueError, e:
if not self.external_url():
os.remove(settings.GADGET_ROOT + self.cleaned_data["upload"])
raise forms.ValidationError(_(u'Gadget quick-check failed: %s.') % (e.args[0]))
# Get title
if self.cleaned_data["title"] == "":
self.cleaned_data["title"] = gadget.title
return self.cleaned_data
class Meta:
<|code_end|>
with the help of current file imports:
from django import forms
from django.forms import widgets
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.core.files.uploadedfile import UploadedFile
from django.utils.hashcompat import sha_constructor
from random import random
from pygowave_server.utils import AlreadyUploadedFile, get_profile_model
from pygowave_server.models import Gadget
from registration.forms import RegistrationForm
from PIL import Image
from lxml.etree import XMLSyntaxError
from pygowave_server.engine import GadgetLoader
import os, urllib2
and context from other files:
# Path: pygowave_server/utils.py
# class AlreadyUploadedFile(UploadedFile):
# """
# This class is used to mark files, which have already been uploaded and
# stored. It still can be opened and read.
#
# """
# def __init__(self, path, name, size):
# super(AlreadyUploadedFile, self).__init__(name, size=size)
# self.path = path
# self._file = None
#
# def open(self):
# self._file = open(path, "r")
#
# def seek(self, pos):
# if self._file != None:
# self._file.seek(pos)
#
# def tell(self):
# if self._file == None: return 0
# return self._file.tell()
#
# def read(self, num_bytes=None):
# if self._file == None: self.open()
# if num_bytes == None:
# return self._file.read()
# else:
# return self._file.read(num_bytes)
#
# def reset(self):
# self._file.reset()
#
# def close(self):
# self._file.close()
#
# def temporary_file_path(self):
# """
# Emulate behaviour of temporary uploaded files.
#
# """
# return self.path
#
# def get_profile_model():
# """
# Return the user profile model class as defined by the AUTH_PROFILE_MODULE
# setting. If that setting is missing SiteProfileNotAvailable is raised.
#
# """
# if not hasattr(settings, 'AUTH_PROFILE_MODULE') or settings.AUTH_PROFILE_MODULE == None:
# raise SiteProfileNotAvailable
#
# profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
# if profile_mod is None:
# raise SiteProfileNotAvailable
#
# return profile_mod
#
# Path: pygowave_server/models.py
# class Gadget(models.Model):
# """
# A gadget that has been uploaded or is referenced on this server.
# Users can register their gadgets on this server to conveniently add them
# to a Wave.
#
# Note: A uploaded gadget is never deleted from disk as it may be used by
# other waves. An exception to this are Gadget marked as "devel" versions.
# Those Gadgets can be simply overwritten and thus replace already running
# instances.
#
# """
#
# by_user = models.ForeignKey(User, related_name="my_gadgets")
# title = models.CharField(max_length=255, unique=True, verbose_name=_(u'Title'))
# description = models.CharField(max_length=255, blank=True, verbose_name=_(u'Description'))
# url = models.URLField(blank=True, verbose_name=_(u'URL'))
# hosted_filename = models.CharField(max_length=255, blank=True, verbose_name=_(u'Hosted filename'))
# devel = models.BooleanField(default=False, verbose_name=_(u'Development version'))
#
# def is_hosted(self):
# return len(self.hosted_filename) > 0
#
# def instantiate(self):
# """
# Create a GadgetElement from this Gadget.
#
# """
# return GadgetElement(url=self.url)
#
# def __unicode__(self):
# return u"Gadget '%s' by '%s'" % (self.title, self.by_user.username)
, which may contain function names, class names, or code. Output only the next line. | model = Gadget |
Given snippet: <|code_start|>
#
# PyGoWave Server - The Python Google Wave Server
# Copyright 2009 Patrick Schneider <patrick.p2k.schneider@gmail.com>
#
# 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.
#
admin.autodiscover()
js_info_dict = {
'packages': ('pygowave_client',),
}
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
url(r'^accounts/register/$', register, name='registration_register', kwargs={
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls.defaults import *
from django.contrib import admin
from registration.views import register
from pygowave_server.forms import MyRegistrationForm
and context:
# Path: pygowave_server/forms.py
# class MyRegistrationForm(RegistrationForm):
#
# def clean_username(self):
# """
# Validate that the username is at least three characters long.
#
# """
# username = super(MyRegistrationForm, self).clean_username()
# if len(username) < 3:
# raise forms.ValidationError(_(u'Your desired username is too short. Please enter at least three characters.'))
# return username
which might include code, classes, or functions. Output only the next line. | "form_class": MyRegistrationForm, |
Based on the snippet: <|code_start|>
class UserOnlineMiddleware:
"""
Update the last_contact field of the user's participant object. Used to
determine how many users are online. This also creates a participant object
if it is missing.
"""
def process_request(self, request):
if request.user.is_authenticated():
try:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from datetime import datetime
from pygowave_server.models import Participant
and context (classes, functions, sometimes code) from other files:
# Path: pygowave_server/models.py
# class Participant(models.Model):
# """
# Represents participant information. It contains id, display name, avatar's
# URL, and an external URL to view the participant's profile page. The
# instances may be coming from external Wave servers (not yet).
#
# Note: This model also serves as user profile on this server.
#
# """
#
# objects = ParticipantManager()
#
# id = models.CharField(max_length=255, primary_key=True)
# user = models.ForeignKey(User, blank=True, null=True, unique=True, related_name="participants")
# is_bot = models.BooleanField()
# last_contact = models.DateTimeField(auto_now_add=True)
#
# name = models.CharField(max_length=255, blank=True)
# avatar = models.URLField(verify_exists=False, blank=True)
# profile = models.URLField(verify_exists=False, blank=True)
#
# def create_new_connection(self):
# """
# Creates a new connection object for this participant and returns it.
# This generates the participant's new access keys.
#
# """
# new_conn = ParticipantConn(participant=self)
# new_conn.save()
# return new_conn
#
# def serialize(self):
# """
# Serialize participant into Google's format (taken from Gadgets API).
#
# """
# return {
# "id": self.id,
# "displayName": self.name,
# "thumbnailUrl": self.avatar,
# "profileUrl": self.profile,
# "isBot": self.is_bot
# }
#
# def __unicode__(self):
# return u"Participant '%s'" % (self.id)
. Output only the next line. | profile_obj = Participant.objects.get(user__id=request.user.id) |
Based on the snippet: <|code_start|> @transaction.commit_on_success
def create_and_init_new_wave(self, creator, title):
wave = self.create()
wavelet = Wavelet(wave=wave, creator=creator, title=title, is_root=True)
wavelet.save()
wavelet.participants.add(creator)
blip = Blip(wavelet=wavelet, creator=creator)
blip.save()
wavelet.root_blip = blip
wavelet.save()
return wave
class Wave(models.Model):
"""
Models wave instances. These are the core of Google Wave.
A single wave is composed of its id and any wavelets that belong to it.
"""
objects = WaveManager()
id = models.CharField(max_length=42, primary_key=True) # Don't panic :P
def root_wavelet(self):
return self.wavelets.get(is_root=True)
def save(self, force_insert=False, force_update=False):
if not self.id:
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime, timedelta
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist
from django.utils.hashcompat import sha_constructor as sha1
from django.utils import simplejson
from pygowave_server.utils import find_random_id, gen_random_id, datetime2milliseconds
from pygowave_server.common.operations import *
import uuid
and context (classes, functions, sometimes code) from other files:
# Path: pygowave_server/utils.py
# def find_random_id(manager, length, suffix="", prefix=""):
# """
# Generates a random id for obj, checks if it exists and retries in
# case of collision. Returns the found number.
#
# """
# rnd_id = prefix + gen_random_id(length) + suffix
# while manager.filter(id=rnd_id).count() > 0:
# rnd_id = prefix + gen_random_id(length) + suffix
# return rnd_id
#
# def gen_random_id(length):
# """
# Generate a random string with the given length.
# Characters are taken from RANDOM_ID_BASE.
#
# """
# return "".join([random.choice(RANDOM_ID_BASE) for x in xrange(length)])
#
# def datetime2milliseconds(dt):
# """
# Convert a python datetime instance to milliseconds since the epoc.
#
# """
# return int(time.mktime(dt.timetuple())) * 1000 + dt.microsecond / 1000
. Output only the next line. | self.id = find_random_id(Wave.objects, 10) |
Predict the next line after this snippet: <|code_start|> participant_conns = models.ManyToManyField(ParticipantConn, blank=True, related_name="wavelets", verbose_name=_(u'connections'))
def blipById(self, id):
"""
Returns the Blip object with the given id, if the Blip resides on this
Wavelet. Returns None otherwise.
"""
try:
return self.blips.get(id=id)
except ObjectDoesNotExist:
return None
def save(self, force_insert=False, force_update=False):
if not self.id:
if self.is_root:
self.id = self.wave.id + ROOT_WAVELET_ID_SUFFIX
else:
self.id = find_random_id(Wavelet.objects, 10, prefix=self.wave.id+"!")
super(Wavelet, self).save(True)
else:
super(Wavelet, self).save(force_insert, force_update)
def creationTimeMs(self):
"""
Returns the time of creation of this Wavelet in milliseconds since
the epoc.
"""
<|code_end|>
using the current file's imports:
from datetime import datetime, timedelta
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist
from django.utils.hashcompat import sha_constructor as sha1
from django.utils import simplejson
from pygowave_server.utils import find_random_id, gen_random_id, datetime2milliseconds
from pygowave_server.common.operations import *
import uuid
and any relevant context from other files:
# Path: pygowave_server/utils.py
# def find_random_id(manager, length, suffix="", prefix=""):
# """
# Generates a random id for obj, checks if it exists and retries in
# case of collision. Returns the found number.
#
# """
# rnd_id = prefix + gen_random_id(length) + suffix
# while manager.filter(id=rnd_id).count() > 0:
# rnd_id = prefix + gen_random_id(length) + suffix
# return rnd_id
#
# def gen_random_id(length):
# """
# Generate a random string with the given length.
# Characters are taken from RANDOM_ID_BASE.
#
# """
# return "".join([random.choice(RANDOM_ID_BASE) for x in xrange(length)])
#
# def datetime2milliseconds(dt):
# """
# Convert a python datetime instance to milliseconds since the epoc.
#
# """
# return int(time.mktime(dt.timetuple())) * 1000 + dt.microsecond / 1000
. Output only the next line. | return datetime2milliseconds(self.created) |
Using the snippet: <|code_start|> # ET = (Qet / (rho_w * Lv))
#------------------------------------------
# rho_w = 1000d ;[kg/m^3]
# Lv = -2500000d ;[J/kg]
# So (rho_w * Lv) = -2.5e+9 [J/m^3]
#-------------------------------------
ET = (Qet / np.float64(2.5E+9)) #[m/s] (A loss, but returned as positive.)
self.ET = np.maximum(ET, np.float64(0))
##########################################
# THIS MAY BE COSTLY. BETTER WAY OR
# ALLOW ET TO BE A SCALAR ??
##########################################
if (np.size(self.ET) == 1):
self.ET += np.zeros((self.ny, self.nx), dtype='Float64')
# update_ET_rate()
#-------------------------------------------------------------------
def open_input_files(self):
#----------------------------------------------------
# Note: Priestley-Taylor method needs alpha but the
# energy balance method doesn't. (2/5/13)
#----------------------------------------------------
self.alpha_file = self.in_directory + self.alpha_file
self.K_soil_file = self.in_directory + self.K_soil_file
self.soil_x_file = self.in_directory + self.soil_x_file
self.T_soil_x_file = self.in_directory + self.T_soil_x_file
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import os
from topoflow.components import evap_base
from topoflow.utils import model_input
and context (class names, function names, or code) available:
# Path: topoflow/components/evap_base.py
# class evap_component( BMI_base.BMI_component):
# def set_constants(self):
# def latent_heat_of_evaporation(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def initialize_computed_vars(self):
# def update_Qc(self):
# def update_ET_rate(self):
# def update_ET_integral(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# T = self.T_air
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
. Output only the next line. | self.alpha_unit = model_input.open_file(self.alpha_type, self.alpha_file) |
Predict the next line after this snippet: <|code_start|> 'var1, var2 = ${var1}, ${var2}\n',
'More lines\n']
template_unit.writelines( lines )
template_unit.close()
# make_test_template()
#-------------------------------------------------------------------------
def test1( method='RE' ):
#-----------------------------
# Change to a test directory
#-----------------------------
test_dir = '/Users/peckhams/Documents'
os.chdir( test_dir )
#---------------------------------------------------
# Get dictionary of replacements (values for vars)
#---------------------------------------------------
dictionary = get_replacement_dictionary( method=method )
#-----------------------------------------
# Make a fake model config file template
#-----------------------------------------
cfg_template_file = 'Model_config_file_template.cfg.in'
make_test_template( cfg_template_file )
#-----------------------------------------------------
# Make replacements to create fake model config file
#-----------------------------------------------------
new_cfg_file = 'Model_config_file.cfg'
<|code_end|>
using the current file's imports:
import os
from topoflow.utils import template_files
and any relevant context from other files:
# Path: topoflow/utils/template_files.py
# def get_replacements( var_names=None, values=None, method='RE'):
# def replace( cfg_template_file, new_cfg_file, dictionary=None,
# method='RE'):
# RE_METHOD = (method == 'RE')
# STRING_METHOD = not(RE_METHOD)
. Output only the next line. | template_files.replace( cfg_template_file, new_cfg_file, |
Given the code snippet: <|code_start|> # (2/18/13) Previous version of framework class initialized
# and then connected the components in the comp_set using
# embedded references. In this version we will call a
# "get_required_vars()" method within the time loop, which
# will in turn call the get_values() and set_values()
# methods. But we still need to initialize the comp set.
#------------------------------------------------------------
## OK = self.initialize_comp_set( REPORT=True )
OK = self.initialize_comp_set( REPORT=False )
if not(OK):
return
#---------------------------------------
# Set mode of the driver component.
# Note: Must happen before next block.
#---------------------------------------
driver = self.comp_set[ driver_comp_name ]
driver.mode = 'driver'
print 'Driver component name =', driver_comp_name
print ' '
#-----------------------------------
# Initialize all time-related vars
#-----------------------------------
self.initialize_time_vars()
self.initialize_framework_dt()
#------------------------------------
# Instantiate a "time_interpolator"
#------------------------------------
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import os
import time
import xml.dom.minidom
import sys #### for testing
from topoflow.framework import time_interpolation # (time_interpolator class)
from cfunits import Units
and context (functions, classes, or occasionally code) from other files:
# Path: topoflow/framework/time_interpolation.py
# class time_interp_data():
# class time_interpolator():
# def __init__( self, v1=None, t1=None, long_var_name=None ):
# def update( self, v2=None, t2=None ):
# def __init__( self, comp_set, comp_names, vars_provided,
# method='Linear' ):
# def initialize( self ):
# def update2( self, comp_name ):
# def update_all( self, time ):
# def get_values( self, long_var_name, comp_name, time ):
# def convert_time_units( self, in_time, in_units ):
# DEBUG = False
. Output only the next line. | time_interpolator = time_interpolation.time_interpolator( |
Given snippet: <|code_start|> # needed to convert snowmelt to snow water
# equivalent (swe) in update_swe() in "snow_base.py".
#-------------------------------------------------------------
T_air = self.T_air # (2/3/13, new framework)
#------------------------------
# Compute degree-day meltrate
#------------------------------
M = (self.c0 / np.float64(8.64E7)) * (T_air - self.T0) #[m/s]
# This is really an "enforce_min_meltrate()"
self.SM = np.maximum(M, np.float64(0))
#-------------------------------------------------------
# Note: enforce_max_meltrate() method is always called
# by the base class to make sure that meltrate
# does not exceed the max possible.
#-------------------------------------------------------
# self.enforce_max_meltrate()
# update_meltrate()
#-------------------------------------------------------------------
def open_input_files(self):
self.c0_file = self.in_directory + self.c0_file
self.T0_file = self.in_directory + self.T0_file
self.rho_snow_file = self.in_directory + self.rho_snow_file
self.h0_snow_file = self.in_directory + self.h0_snow_file
self.h0_swe_file = self.in_directory + self.h0_swe_file
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from topoflow.utils import model_input
from topoflow.components import snow_base
and context:
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/components/snow_base.py
# class snow_component( BMI_base.BMI_component ):
# def set_constants(self):
# def latent_heat_of_sublimation(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def initialize_computed_vars(self):
# def update_meltrate(self):
# def enforce_max_meltrate(self):
# def update_SM_integral(self):
# def update_swe(self):
# def update_depth(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# T = self.T_air
# T_IS_GRID = self.is_grid('T_air')
# P_IS_GRID = self.is_grid('P_snow')
# H0_SNOW_IS_SCALAR = self.is_scalar('h0_snow')
# H0_SWE_IS_SCALAR = self.is_scalar('h0_swe')
which might include code, classes, or functions. Output only the next line. | self.c0_unit = model_input.open_file(self.c0_type, self.c0_file) |
Given snippet: <|code_start|> # ALLOW ET TO BE A SCALAR ??
##########################################
## if (size(self.ET) == 1):
## self.ET += np.zeros((self.ny, self.nx), dtype='Float64')
# update_ET_rate()
#-------------------------------------------------------------------
def update_water_balance(self):
#----------------------------------------------------------
# Notes: Return without modifying the surface water depth
# or soil moisture in the top soil layer.
# Depending on how the model is run, this may
# lead to an inconsistent result where the mass
# of water in the system is not conserved.
#----------------------------------------------------------
print '-----------------------------------------------------'
print 'WARNING: ET_read_file component assumes that the'
print ' ET rates read from files are actual vs.'
print ' potential rates. It does not consume'
print ' surface or subsurface water.'
print '-----------------------------------------------------'
return
# update_water_balance()
#-------------------------------------------------------------------
def open_input_files(self):
self.ET_file = self.in_directory + self.ET_file
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import os
import glob
import os.path
import numpy
import rti_files
from topoflow.components import evap_base
from topoflow.utils import model_input
from topoflow.utils import tf_utils
and context:
# Path: topoflow/components/evap_base.py
# class evap_component( BMI_base.BMI_component):
# def set_constants(self):
# def latent_heat_of_evaporation(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def initialize_computed_vars(self):
# def update_Qc(self):
# def update_ET_rate(self):
# def update_ET_integral(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# T = self.T_air
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Use_CCA():
# def TF_Set_Test_Info(self):
# def TF_Test_Directory():
# def TF_Test_Site_Prefix():
# def TF_Test_Case_Prefix():
# def TF_Build_Date():
# def TF_Version_Number():
# def TF_Version():
# def TF_Print(string):
# def TF_String(number, FORMAT=None):
# def file_exists(filename):
# def Count_Lines(filename, SILENT=False):
# def Current_Directory():
# def Resize(array, factor, REDUCE, new_ncols, new_nrows, SAMP_TYPE=None):
# def Make_Savefile():
# def Get_Site_Prefix(filepath):
# def Get_Case_Prefix():
# def Not_Same_Byte_Order(byte_order):
# def Courant_Condition_OK(dx, dt, vmax):
# def Stable_Timestep(dx, vmax):
# def TF_Tan(angle):
# def Convert_Flow_Grid(infile, outfile, itype, otype, byte_order, \
# icodes=None, ocodes=None, REPORT=False):
# SAMP_TYPE = int16(0)
# NOT_SAME = (machine_byte_order != byte_order)
# OK = ((vmax * dt * factor) <= dx)
# SWAP_ENDIAN = Not_Same_Byte_Order(byte_order)
which might include code, classes, or functions. Output only the next line. | self.ET_unit = model_input.open_file(self.ET_type, \ |
Predict the next line after this snippet: <|code_start|> # (2/18/13) Previous version of framework class initialized
# and then connected the components in the comp_set using
# embedded references. In this version we will call a
# "get_required_vars()" method within the time loop, which
# will in turn call the get_values() and set_values()
# methods. But we still need to initialize the comp set.
#------------------------------------------------------------
## OK = self.initialize_comp_set( REPORT=True )
OK = self.initialize_comp_set( REPORT=False )
if not(OK):
return
#---------------------------------------
# Set mode of the driver component.
# Note: Must happen before next block.
#---------------------------------------
driver = self.comp_set[ driver_comp_name ]
driver.mode = 'driver'
print 'Driver component name =', driver_comp_name
print ' '
#-----------------------------------
# Initialize all time-related vars
#-----------------------------------
self.initialize_time_vars()
self.initialize_framework_dt()
#------------------------------------
# Instantiate a "time_interpolator"
#------------------------------------
<|code_end|>
using the current file's imports:
import numpy as np
import os
import time
import xml.dom.minidom
import sys #### for testing
from topoflow.framework import time_interpolation # (time_interpolator class)
and any relevant context from other files:
# Path: topoflow/framework/time_interpolation.py
# class time_interp_data():
# class time_interpolator():
# def __init__( self, v1=None, t1=None, long_var_name=None ):
# def update( self, v2=None, t2=None ):
# def __init__( self, comp_set, comp_names, vars_provided,
# method='Linear' ):
# def initialize( self ):
# def update2( self, comp_name ):
# def update_all( self, time ):
# def get_values( self, long_var_name, comp_name, time ):
# def convert_time_units( self, in_time, in_units ):
# DEBUG = False
. Output only the next line. | time_interpolator = time_interpolation.time_interpolator( |
Here is a snippet: <|code_start|> ################################################
#------------------------------------------
# Lf = latent heat of fusion [J/kg]
# Lv = latent heat of vaporization [J/kg]
# ET = (Qet / (rho_w * Lv))
#------------------------------------------
# rho_w = 1000d ;[kg/m^3]
# Lv = -2500000d ;[J/kg]
# So (rho_w * Lv) = -2.5e+9 [J/m^3]
#------------------------------------------
# ET is a loss, but returned as positive.
#------------------------------------------
ET = (Qet / np.float64(2.5E+9)) # [m/s]
self.ET = np.maximum(ET, np.float64(0))
# update_ET_rate()
#-------------------------------------------------------------------
def open_input_files(self):
#----------------------------------------------------
# Note: Priestley-Taylor method needs alpha but the
# energy balance method doesn't. (2/5/13)
#----------------------------------------------------
## self.alpha_file = self.in_directory + self.alpha_file
self.K_soil_file = self.in_directory + self.K_soil_file
self.soil_x_file = self.in_directory + self.soil_x_file
self.T_soil_x_file = self.in_directory + self.T_soil_x_file
## self.alpha_unit = model_input.open_file(self.alpha_type, self.alpha_file)
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import os
from topoflow.components import evap_base
from topoflow.utils import model_input
and context from other files:
# Path: topoflow/components/evap_base.py
# class evap_component( BMI_base.BMI_component):
# def set_constants(self):
# def latent_heat_of_evaporation(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def initialize_computed_vars(self):
# def update_Qc(self):
# def update_ET_rate(self):
# def update_ET_integral(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# T = self.T_air
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
, which may include functions, classes, or code. Output only the next line. | self.K_soil_unit = model_input.open_file(self.K_soil_type, self.K_soil_file) |
Here is a snippet: <|code_start|># bobs_erode_test() # Use framework to run Erode.
#
#-----------------------------------------------------------------------
def topoflow_test( driver_comp_name ='topoflow_driver',
cfg_prefix=None, cfg_directory=None,
time_interp_method='Linear'):
#----------------------------------------------------------
# Note: The "driver_comp_name " defaults to using a
# component of "topoflow_driver" type as the driver.
# The component of this type specified in the
# provider_file will be the driver component.
#
# Any other component in the provider_file can
# also be used as the driver. Examples are:
# meteorology
# channels
# snow
# satzone
# evap
# infil
# diversions
# ice
#-----------------------------------------------------
#-------------------------------------------------------
# (2/6/13) Since the framework runs the clock now, do
# we still need to specify a "driver_comp" ??
# Might still be necessary for use in CSDMS framework.
#-------------------------------------------------------
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import os
import tempfile
import random
from topoflow.framework import emeli ###########
and context from other files:
# Path: topoflow/framework/emeli.py
# SILENT = False
# DEBUG = True
# OK = self.initialize_comp_set( REPORT=False )
# OK = True
# OK = False
# OK = False
# OK = self.check_var_users_and_providers()
# REPORT = False
# class comp_data():
# class framework():
# def __init__(self, comp_name=None, module_path=None,
# module_name=None, class_name=None,
# model_name=None, version=None,
# language=None, author=None,
# help_url=None, cfg_template=None,
# time_step_type=None, time_units=None,
# grid_type=None, description=None,
# comp_type=None, uses_types=None):
# def read_repository( self, SILENT=True ):
# def read_provider_file(self, SILENT=False):
# def comp_name_valid( self, comp_name ):
# def instantiate( self, comp_name, SILENT=True ):
# def remove( self, comp_name, SILENT=True ):
# def connect( self, provider_name, user_name,
# long_var_name, REPORT=False ):
# def disconnect( self, provider_name, user_name,
# long_var_name ):
# def get_values( self, long_var_name, comp_name ):
# def set_values( self, long_var_name, values, comp_name):
# def get_values_at_indices( self, long_var_name, indices,
# comp_name ):
# def set_values_at_indices( self, long_var_name, indices, values,
# comp_name ):
# def initialize( self, comp_name, cfg_file=None,
# mode='nondriver'):
# def update( self, comp_name ):
# def finalize( self, comp_name ):
# def get_cfg_filename( self, bmi ): ###################
# def initialize_all( self, cfg_prefix=None, mode='nondriver'):
# def update_all( self ):
# def finalize_all0( self ):
# def finalize_all( self ):
# def run_model( self, driver_comp_name='hydro_model',
# cfg_directory=None, cfg_prefix=None,
# time_interp_method='Linear'):
# def run_rc_script( self ):
# def initialize_time_vars(self, units='seconds'):
# def convert_time_units( self, in_time, in_units ):
# def initialize_framework_dt( self ):
# def update_time(self, dt=-1):
# def find_var_users_and_providers( self, REPORT=False ):
# def check_var_users_and_providers( self ):
# def initialize_comp_set( self, REPORT=False ):
# def get_required_vars( self, user_name, bmi_time ):
, which may include functions, classes, or code. Output only the next line. | f = emeli.framework() |
Next line prediction: <|code_start|># get_input_var_names() # (5/15/12)
# get_output_var_names() # (5/15/12)
# get_var_name() # (5/15/12)
# get_var_units() # (5/15/12)
# -------------------------
# initialize_layer_vars() # (5/11/10)
# set_computed_input_vars()
# check_input_types()
# update_infil_rate()
# -------------------------
# open_input_files()
# read_input_files()
# close_input_files()
# ----------------------
# update_outfile_names()
# Functions:
# Green_Ampt_Infil_Rate_v1
# Green_Ampt_Infil_Rate_1D
# Green_Ampt_Infil_Rate_3D
# Green_Ampt_Infil_Rate_v2
#-----------------------------------------------------------------------
# import os
#-----------------------------------------------------------------------
<|code_end|>
. Use current file imports:
(import numpy as np
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String)
and context including class names, function names, or small code snippets from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | class infil_component( infil_base.infil_component ): |
Given the code snippet: <|code_start|> ## n = self.time_index
## Green_Ampt_Infil_Rate_v2(self, r, r_last, n)
# update_infil_rate()
#-------------------------------------------------------------------
def open_input_files(self):
#-------------------------------------------------------
# NB! Green-Ampt and Smith-Parlange currently only
# support ONE layer (n_layers == 1).
#-------------------------------------------------------
self.Ks_unit = [] # (empty lists to hold file objects)
self.Ki_unit = []
self.qs_unit = []
self.qi_unit = []
self.G_unit = []
for k in xrange(self.n_layers):
#-------------------------------------------------------------
# If (var_type == 'Scalar'), then the filenames here will be
# a null string, prepended with in_directory. But note that
# model_input.open_file() returns None if type is "Scalar".
# So None will then be appended to the "unit list".
#-------------------------------------------------------------
self.Ks_file[k] = self.in_directory + self.Ks_file[k]
self.Ki_file[k] = self.in_directory + self.Ki_file[k]
self.qs_file[k] = self.in_directory + self.qs_file[k]
self.qi_file[k] = self.in_directory + self.qi_file[k]
self.G_file[k] = self.in_directory + self.G_file[k]
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context (functions, classes, or occasionally code) from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | self.Ks_unit.append( model_input.open_file(self.Ks_type[k], self.Ks_file[k]) ) |
Based on the snippet: <|code_start|> #--------------------------------------------
MID_PONDING = ((dIp > 0) and (dIp < (r * self.dt)))
if (MID_PONDING):
print 'MID_PONDING occurred.'
#--------------------------
# For this case: Ip = Ip2
#--------------------------
self.tp = t_start + (dIp / r) #(r gt Ks, above)
self.fp = r
#------------------------------------------
# Does ponding occur at end of timestep ?
#------------------------------------------
# Ip(r_n) < Ia(n-1) < Ip(r_{n-1})
# [Ip(r_n) - Ia(n-1)] < 0 AND
# Ia(n-1) < Ip(r_{n-1})
#------------------------------------------
END_PONDING = ((dIp < 0) and (self.I < Ip1) and not(MID_PONDING))
if (END_PONDING):
print 'END_PONDING occurred.'
#-----------------------------
# For this case: Ip = self.I
#-----------------------------
self.tp = t_end
self.fp = (top / self.I) + Ks
#--------------------------
# For debugging & testing
#--------------------------
if (MID_PONDING or END_PONDING):
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context (classes, functions, sometimes code) from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | TF_Print('tp = ' + str(self.tp)) |
Predict the next line for this snippet: <|code_start|> # reduce dt_too_small.
#-----------------------------------------------------
dt_grid_min = np.nanmin(self.dt_grid)
if (dt_grid_min < dt_too_small):
print '******************************************'
print ' Aborting: Stable dt is too small.'
print ' Computed dt = ' + str(dt_grid_min)
print '******************************************'
print ' '
sys.exit()
#------------------
# Optional report
#------------------
if (REPORT):
# dt_grid_min = np.nanmin(self.dt_grid)
dt_grid_max = np.nanmax(self.dt_grid)
dt_str = str(dt_grid_min) + ', ' + str(dt_grid_max)
del_z_str = str(del_z.min()) + ', ' + str(del_z.max())
del_Qs_str = str(del_Qs.min()) + ', ' + str(del_Qs.max())
print ' min(dt), max(dt) = ' + dt_str + ' [yrs]'
print ' min(del_z), max(del_z) = ' + del_z_str
print ' min(del_Qs), max(del_Qs) = ' + del_Qs_str
print ' '
#-----------------------------
# Save grid as an RTG file ?
#-----------------------------
if (SAVE_RTG):
RTG_file = (self.case_prefix + '_dt.rtg')
<|code_end|>
with the help of current file imports:
import numpy as np
import os.path
import time
import d8_global ### (9/19/14. Attempt to fix issue.)
import erode_base
from topoflow.utils import rtg_files
and context from other files:
# Path: topoflow/utils/rtg_files.py
# def unit_test(nx=4, ny=5, VERBOSE=False,
# file_name="TEST_FILE.rtg"):
# def __init__(self):
# def open_file(self, file_name=None, UPDATE=False):
# def check_and_store_info(self, file_name, info=None,
# var_name='UNKNOWN',
# dtype='float32',
# MAKE_RTI=True, MAKE_BOV=False):
# def add_index_to_file_name(self, file_name):
# def open_new_file(self, file_name, info=None,
# var_name='UNKNOWN', dtype='float32',
# VERBOSE=False, ADD_INDEX=False,
# MAKE_RTI=True, MAKE_BOV=False):
# def write_grid(self, grid, VERBOSE=False):
# def add_grid(self, grid):
# def read_grid(self, dtype='float32', rtg_type=None,
# REPORT=False, VERBOSE=False):
# def get_grid(self, grid):
# def close_file(self):
# def close(self):
# def byte_swap_needed(self):
# def read_grid( RTG_file, rti, RTG_type='FLOAT',
# REPORT=False, SILENT=True ):
# def write_grid( grid, RTG_file, rti, RTG_type='FLOAT',
# REPORT=False, SILENT=True ):
# def read_xyz_as_grid(XYZ_file, RTG_file):
# OK = rtg.open_new_file( file_name, info, ADD_INDEX=True )
# OK = rtg.open_file()
# OK = rtg.open_new_file( file_name, info, ADD_INDEX=True)
# NEW_INFO = True
# NEW_INFO = False
# SWAP = (machine_byte_order != self.info.byte_order)
# SWAP_ENDIAN = tf_utils.Not_Same_Byte_Order(byte_order)
# class rtg_file():
, which may contain function names, class names, or code. Output only the next line. | rtg_files.write_grid( self.dt_grid, RTG_file, self.rti )
|
Next line prediction: <|code_start|> # followed by "n_sources" blocks of the form:
#
# source_ID: (source pixel ID as long integer)
# nt: (number of discharge (Q) values)
# Q: (vector of discharges in m^3/s)
#------------------------------------------------------------
if (self.comp_status == 'Disabled'): return
if not(self.use_sources):
self.sources_x = self.initialize_scalar( 0, dtype='float64')
self.sources_y = self.initialize_scalar( 0, dtype='float64')
self.sources_Q = self.initialize_scalar( 0, dtype='float64')
return
#-----------------------------
# Can source_file be found ?
#-----------------------------
FOUND = tf_utils.file_exists( self.source_file )
if not(FOUND):
self.use_sources = False
return
#-------------------------
# Open the "source_file"
#-------------------------
file_unit = open(self.source_file, 'r')
#----------------------------------------------------
# Read number of sources, max number of timesteps
# for any source and the common timestep, source_dt
#----------------------------------------------------
<|code_end|>
. Use current file imports:
(import numpy as np
import glob
import os
from topoflow.components import diversions_base
from topoflow.utils import cfg_files as cfg
from topoflow.utils import tf_utils)
and context including class names, function names, or small code snippets from other files:
# Path: topoflow/components/diversions_base.py
# class diversions_component( BMI_base.BMI_component ):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def set_computed_input_vars(self):
# def read_input_files(self):
# def read_source_data(self):
# def read_sink_data(self):
# def read_canal_data(self):
#
# Path: topoflow/utils/cfg_files.py
# def unit_test():
# def skip_header(file_unit, n_lines=4):
# def get_yes_words():
# def read_words(file_unit, word_delim=None):
# def read_list(file_unit, dtype_list=None, dtype='string',
# word_delim=None):
# def read_key_value_pair(file_unit, key_delim=':', SILENT=True):
# def read_line_after_key(file_unit, key_delim=':'):
# def read_words_after_key(file_unit, key_delim=':',
# word_delim=None, n_words=None):
# def read_list_after_key(file_unit, dtype_list=None, dtype='string',
# key_delim=':', word_delim=None):
# def read_value(file_unit, dtype='string', key_delim=':'):
# def var_type_code(var_type):
# def read_input_option(file_unit, key_delim=':', word_delim=None):
# def read_output_option(file_unit, key_delim=':', word_delim=None):
#
# Path: topoflow/utils/tf_utils.py
# def TF_Use_CCA():
# def TF_Set_Test_Info(self):
# def TF_Test_Directory():
# def TF_Test_Site_Prefix():
# def TF_Test_Case_Prefix():
# def TF_Build_Date():
# def TF_Version_Number():
# def TF_Version():
# def TF_Print(string):
# def TF_String(number, FORMAT=None):
# def file_exists(filename):
# def Count_Lines(filename, SILENT=False):
# def Current_Directory():
# def Resize(array, factor, REDUCE, new_ncols, new_nrows, SAMP_TYPE=None):
# def Make_Savefile():
# def Get_Site_Prefix(filepath):
# def Get_Case_Prefix():
# def Not_Same_Byte_Order(byte_order):
# def Courant_Condition_OK(dx, dt, vmax):
# def Stable_Timestep(dx, vmax):
# def TF_Tan(angle):
# def Convert_Flow_Grid(infile, outfile, itype, otype, byte_order, \
# icodes=None, ocodes=None, REPORT=False):
# SAMP_TYPE = int16(0)
# NOT_SAME = (machine_byte_order != byte_order)
# OK = ((vmax * dt * factor) <= dx)
# SWAP_ENDIAN = Not_Same_Byte_Order(byte_order)
. Output only the next line. | n_sources = cfg.read_value(file_unit, dtype='Int32') |
Given the code snippet: <|code_start|> #------------------------
# Update internal clock
#------------------------
# print '#### Calling update_time()...'
self.update_time()
self.status = 'updated' # (OpenMI 2.0 convention)
# update()
#--------------------------------------------------------------------------
def read_source_data(self):
#------------------------------------------------------------
# Notes: Assume that source_file contains key-value pairs,
# starting with "n_sources:", "nt_max" and "dt:",
# followed by "n_sources" blocks of the form:
#
# source_ID: (source pixel ID as long integer)
# nt: (number of discharge (Q) values)
# Q: (vector of discharges in m^3/s)
#------------------------------------------------------------
if (self.comp_status == 'Disabled'): return
if not(self.use_sources):
self.sources_x = self.initialize_scalar( 0, dtype='float64')
self.sources_y = self.initialize_scalar( 0, dtype='float64')
self.sources_Q = self.initialize_scalar( 0, dtype='float64')
return
#-----------------------------
# Can source_file be found ?
#-----------------------------
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import glob
import os
from topoflow.components import diversions_base
from topoflow.utils import cfg_files as cfg
from topoflow.utils import tf_utils
and context (functions, classes, or occasionally code) from other files:
# Path: topoflow/components/diversions_base.py
# class diversions_component( BMI_base.BMI_component ):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def set_computed_input_vars(self):
# def read_input_files(self):
# def read_source_data(self):
# def read_sink_data(self):
# def read_canal_data(self):
#
# Path: topoflow/utils/cfg_files.py
# def unit_test():
# def skip_header(file_unit, n_lines=4):
# def get_yes_words():
# def read_words(file_unit, word_delim=None):
# def read_list(file_unit, dtype_list=None, dtype='string',
# word_delim=None):
# def read_key_value_pair(file_unit, key_delim=':', SILENT=True):
# def read_line_after_key(file_unit, key_delim=':'):
# def read_words_after_key(file_unit, key_delim=':',
# word_delim=None, n_words=None):
# def read_list_after_key(file_unit, dtype_list=None, dtype='string',
# key_delim=':', word_delim=None):
# def read_value(file_unit, dtype='string', key_delim=':'):
# def var_type_code(var_type):
# def read_input_option(file_unit, key_delim=':', word_delim=None):
# def read_output_option(file_unit, key_delim=':', word_delim=None):
#
# Path: topoflow/utils/tf_utils.py
# def TF_Use_CCA():
# def TF_Set_Test_Info(self):
# def TF_Test_Directory():
# def TF_Test_Site_Prefix():
# def TF_Test_Case_Prefix():
# def TF_Build_Date():
# def TF_Version_Number():
# def TF_Version():
# def TF_Print(string):
# def TF_String(number, FORMAT=None):
# def file_exists(filename):
# def Count_Lines(filename, SILENT=False):
# def Current_Directory():
# def Resize(array, factor, REDUCE, new_ncols, new_nrows, SAMP_TYPE=None):
# def Make_Savefile():
# def Get_Site_Prefix(filepath):
# def Get_Case_Prefix():
# def Not_Same_Byte_Order(byte_order):
# def Courant_Condition_OK(dx, dt, vmax):
# def Stable_Timestep(dx, vmax):
# def TF_Tan(angle):
# def Convert_Flow_Grid(infile, outfile, itype, otype, byte_order, \
# icodes=None, ocodes=None, REPORT=False):
# SAMP_TYPE = int16(0)
# NOT_SAME = (machine_byte_order != byte_order)
# OK = ((vmax * dt * factor) <= dx)
# SWAP_ENDIAN = Not_Same_Byte_Order(byte_order)
. Output only the next line. | FOUND = tf_utils.file_exists( self.source_file ) |
Given the following code snippet before the placeholder: <|code_start|># get_component_name()
# get_attribute() # (10/26/11)
# get_input_var_names() # (10/23/12)
# get_output_var_names() # (10/23/12)
# get_var_name() # (10/23/12)
# get_var_units() # (10/23/12)
# -------------------------
# initialize_layer_vars()
# set_computed_input_vars()
# check_input_types()
# update_infil_rate()
# -------------------------
# open_input_files()
# read_input_files()
# close_input_files()
# ----------------------
# update_outfile_names()
# Functions:
# Smith_Parlange_Infil_Rate_v1
# Smith_Parlange_Infil_Rate_1D
# Smith_Parlange_Infil_Rate_3D
# Smith_Parlange_Infil_Rate_v2 (uses previous 2)
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import os
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context including class names, function names, and sometimes code from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | class infil_component(infil_base.infil_component): |
Here is a snippet: <|code_start|> ## r_last = ???
## n = self.time_index
## Smith_Parlange_Infil_Rate_v2(self, r, r_last, n)
# update_infil_rate()
#-------------------------------------------------------------------
def open_input_files(self):
#-------------------------------------------------------
# This method works for Green-Ampt and Smith-Parlange
# but must be overridden for Richards 1D.
#-------------------------------------------------------
# NB! Green-Ampt and Smith-Parlange currently only
# support ONE layer (n_layers == 1).
#-------------------------------------------------------
self.Ks_unit = [] # (empty lists to hold file objects)
self.Ki_unit = []
self.qs_unit = []
self.qi_unit = []
self.G_unit = []
self.gam_unit = []
for k in xrange(self.n_layers):
self.Ks_file[k] = self.in_directory + self.Ks_file[k]
self.Ki_file[k] = self.in_directory + self.Ki_file[k]
self.qs_file[k] = self.in_directory + self.qs_file[k]
self.qi_file[k] = self.in_directory + self.qi_file[k]
self.G_file[k] = self.in_directory + self.G_file[k]
self.gam_file[k] = self.in_directory + self.gam_file[k]
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import os
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
, which may include functions, classes, or code. Output only the next line. | self.Ks_unit.append( model_input.open_file(self.Ks_type[k], self.Ks_file[k]) ) |
Using the snippet: <|code_start|> #------------------------------------------
MID_PONDING = np.logical_and((dIp > 0), (dIp < (r * self.dt)))
if (MID_PONDING):
print 'MID_PONDING occurred.'
#------------------------
#For this case: Ip = Ip2
#------------------------
self.tp = t_start + (dIp / r) #(r gt Ks, above)
self.fp = r
#------------------------------------------
# Does ponding occur at end of timestep ?
#------------------------------------------
# Ip(r_n) < Ia(n-1) < Ip(r_{n-1})
# [Ip(r_n) - Ia(n-1)] < 0 AND
# Ia(n-1) < Ip(r_{n-1})
#----------------------------------------
END_PONDING = np.logical_and(np.logical_and((dIp < 0), (self.I < Ip1)), np.logical_not(MID_PONDING))
if (END_PONDING):
print 'END_PONDING occurred.'
#-----------------------------
# For this case: Ip = self.I
#-----------------------------
self.tp = t_end
self.fp = ((gam * dK) / (np.exp(self.I / fac) - np.float64(1))) + Ks
#--------------------------
# For debugging & testing
#--------------------------
if (logical_or(MID_PONDING, END_PONDING)):
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import os
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context (class names, function names, or code) available:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | TF_Print('tp = ' + TF_String(self.tp)) |
Based on the snippet: <|code_start|> #------------------------------------------
MID_PONDING = np.logical_and((dIp > 0), (dIp < (r * self.dt)))
if (MID_PONDING):
print 'MID_PONDING occurred.'
#------------------------
#For this case: Ip = Ip2
#------------------------
self.tp = t_start + (dIp / r) #(r gt Ks, above)
self.fp = r
#------------------------------------------
# Does ponding occur at end of timestep ?
#------------------------------------------
# Ip(r_n) < Ia(n-1) < Ip(r_{n-1})
# [Ip(r_n) - Ia(n-1)] < 0 AND
# Ia(n-1) < Ip(r_{n-1})
#----------------------------------------
END_PONDING = np.logical_and(np.logical_and((dIp < 0), (self.I < Ip1)), np.logical_not(MID_PONDING))
if (END_PONDING):
print 'END_PONDING occurred.'
#-----------------------------
# For this case: Ip = self.I
#-----------------------------
self.tp = t_end
self.fp = ((gam * dK) / (np.exp(self.I / fac) - np.float64(1))) + Ks
#--------------------------
# For debugging & testing
#--------------------------
if (logical_or(MID_PONDING, END_PONDING)):
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import os
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context (classes, functions, sometimes code) from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | TF_Print('tp = ' + TF_String(self.tp)) |
Given the code snippet: <|code_start|># get_input_var_names() # (5/15/12)
# get_output_var_names() # (5/15/12)
# get_var_name() # (5/15/12)
# get_var_units() # (5/15/12)
# -------------------------
# initialize_layer_vars() # (5/11/10)
# set_computed_input_vars()
# check_input_types()
# update_infil_rate()
# -------------------------
# open_input_files()
# read_input_files()
# close_input_files()
# ----------------------
# update_outfile_names()
# Functions:
# Beven_Exp_K_Infil_Rate_v1 (Nov. 2016)
# Beven_Exp_K_Infil_Rate_1D (Not written)
# Beven_Exp_K_Infil_Rate_3D (Not written)
# Beven_Exp_K_Infil_Rate_v2 (Not written)
#-----------------------------------------------------------------------
# import os
#-----------------------------------------------------------------------
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from topoflow.components import infil_base
from topoflow.utils import model_input
from topoflow.utils.tf_utils import TF_Print, TF_String
and context (functions, classes, or occasionally code) from other files:
# Path: topoflow/components/infil_base.py
# class infil_component( BMI_base.BMI_component):
# def set_constants(self):
# def initialize(self, cfg_file=None, mode="nondriver",
# SILENT=False):
# def update(self, dt=-1.0):
# def finalize(self):
# def build_layer_z_vector(self):
# def build_layered_var(self, var_list_for_layers):
# def set_computed_input_vars(self):
# def check_input_types(self):
# def update_surface_influx(self):
# def update_infil_rate(self):
# def adjust_infil_rate(self):
# def update_IN_integral(self):
# def update_Rg(self):
# def update_Rg_integral(self):
# def update_I(self):
# def update_q0(self):
# def check_infiltration(self):
# def check_low_rainrate(self):
# def open_input_files(self):
# def read_input_files(self):
# def close_input_files(self):
# def update_outfile_names(self):
# def open_output_files(self):
# def write_output_files(self, time_seconds=None):
# def close_output_files(self):
# def save_grids(self):
# def save_pixel_values(self):
# def save_profiles(self):
# def save_cubes(self):
# ALL_SCALARS = (nmax == 1)
# SM = self.SM # (2/3/13, new framework)
# CHECK_LOW_RAIN = not(self.RICHARDS)
# SM = self.SM # (2/3/13, new framework)
# OK = np.isfinite( self.IN )
# OK = (nbad == 0)
# G = model_input.read_next(self.G_unit[k], self.G_type[k], rti)
#
# Path: topoflow/utils/model_input.py
# def open_file(var_type, input_file):
# def read_next2(self, var_name, rti, dtype='Float32', factor=1.0):
# def read_next(file_unit, var_type, rti, \
# dtype='Float32', factor=1.0):
# def read_scalar(file_unit, dtype='Float32'):
# def read_grid(file_unit, rti, dtype='Float32'):
# def close_file(file_unit):
# END_OF_FILE = (file_pos == file_size)
#
# Path: topoflow/utils/tf_utils.py
# def TF_Print(string):
# """Print a string to the TopoFlow output log window."""
#
# #------------------------------------------
# # For now, just print to terminal window.
# # Later, this will be method in tf_gui.py.
# #------------------------------------------
# print string
#
# def TF_String(number, FORMAT=None):
#
# return idl_func.string(number, format=FORMAT).strip()
. Output only the next line. | class infil_component( infil_base.infil_component ): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.