Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|> If username and password are given HTTP basic authentication
will be used.
:param url: The API URL
:type url: str
:param username: API username
:type username: str
:param password: corresponding password
:type password: str
:param verify_ssl: Control SSL verfication.
:type verify_ssl: bool
"""
self._url = url
self._username = username
self._password = password
self._verify_ssl = verify_ssl
self._session = None
self._connect()
def _connect(self):
"""
This function establishes a connection to the Icinga2 API.
"""
self._session = Session()
if self._username:
self._session.auth = HTTPBasicAuth(self._username, self._password)
if not self.is_authenticated():
<|code_end|>
, predict the next line using imports from the current file:
from abc import ABCMeta, abstractmethod
from requests import Session
from requests.auth import HTTPBasicAuth
from ..exceptions import UnauthenticatedError
and context including class names, function names, and sometimes code from other files:
# Path: katprep/exceptions.py
# class UnauthenticatedError(RuntimeError):
# """
# Exception for showing that a client wasn't able to authenticate itself.
# """
. Output only the next line. | raise UnauthenticatedError("Unable to authenticate!") |
Using the snippet: <|code_start|>
@pytest.mark.parametrize("address", [
'192.168.0.1',
'12.34.56.78',
pytest.param('no', marks=pytest.mark.xfail),
pytest.param('1.2.3', marks=pytest.mark.xfail),
pytest.param('1.2.3.4.5', marks=pytest.mark.xfail),
pytest.param('1.2.3.4', marks=pytest.mark.xfail),
])
def test_ipv4_check(address):
"Making sure we are able to identify an IPv4 address"
<|code_end|>
, determine the next line of code. You have imports:
import logging
import mock
import pytest
import ssl
from katprep.network import is_ipv4
from .utilities import load_config
and context (class names, function names, or code) available:
# Path: katprep/network.py
# def is_ipv4(address):
# """
# Returns whether the supplied address is a valid IPv4 address
#
# :param address: IP address
# :type address: str
# """
# # Friendly inspired by: https://stackoverflow.com/questions/319279/
# # how-to-validate-ip-address-in-python
# try:
# socket.inet_pton(socket.AF_INET, address)
# except AttributeError:
# try:
# socket.inet_aton(address)
# except socket.error:
# return False
# return address.count(".") == 3
# except socket.error:
# return False
# return True
#
# Path: tests/utilities.py
# def load_config(config_file):
# if not os.path.isfile(config_file):
# pytest.skip("Please create configuration file %s!" % config_file)
#
# try:
# with open(config_file, "r") as json_file:
# return json.load(json_file)
# except IOError as err:
# pytest.skip("Unable to read configuration file: '%s'", err)
. Output only the next line. | assert is_ipv4(address) |
Predict the next line for this snippet: <|code_start|>##
## This file is part of SUCEM.
##
## SUCEM is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test:
class test_interpolant(unittest.TestCase):
test_data_file = 'data/interpolant_test_data.pickle'
rtol=1e-10
atol=1e-7
def setUp(self):
<|code_end|>
with the help of current file imports:
import unittest
import pickle
import numpy as N
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff
from sucemfem.PostProcessing import variational_ntff
and context from other files:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
, which may contain function names, class names, or code. Output only the next line. | desired_file = Paths.get_module_path_file(self.test_data_file, __file__) |
Here is a snippet: <|code_start|>class test_interpolant_expression(test_interpolant):
def setUp(self):
super(test_interpolant_expression, self).setUp()
self.DUT = variational_ntff.TransformTestingExpression()
def test_expression_re(self):
dd = self.desired_data
k0, ahats, rhat = dd['k0'], dd['ahats'], dd['rhat']
ahats, coords = dd['ahats'], dd['coords']
for i, ahat in enumerate(ahats):
desired_vals = dd['vals'][i].real
self.DUT.set_parms(rhat, ahat, k0)
expr_r = self.DUT.get_expression()[0]
actual_vals = N.zeros((len(coords),3), N.float64)
for j, coord in enumerate(coords):
expr_r.eval(actual_vals[j,:], coord)
self.assertTrue(N.allclose(actual_vals, desired_vals,
rtol=self.rtol, atol=self.atol))
class NTFFEnvironment(object):
def __init__(self, datafile):
test_data = pickle.load(datafile)
ff_result_data = test_data['ff_result_data']
nf_input_data = test_data['nf_input_data']
self.desired_E_ff = ff_result_data['E_ff']
self.desired_E_theta = self.desired_E_ff[:,0]
self.desired_E_phi = self.desired_E_ff[:,1]
self.theta_coords = ff_result_data['theta_deg']
self.phi_coords = ff_result_data['phi_deg']
self.discretisation_order = nf_input_data['order']
<|code_end|>
. Write the next line using the current file imports:
import unittest
import pickle
import numpy as N
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff
from sucemfem.PostProcessing import variational_ntff
and context from other files:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
, which may include functions, classes, or code. Output only the next line. | self.mesh = get_centred_cube( |
Using the snippet: <|code_start|> expr_r.eval(actual_vals[j,:], coord)
self.assertTrue(N.allclose(actual_vals, desired_vals,
rtol=self.rtol, atol=self.atol))
class NTFFEnvironment(object):
def __init__(self, datafile):
test_data = pickle.load(datafile)
ff_result_data = test_data['ff_result_data']
nf_input_data = test_data['nf_input_data']
self.desired_E_ff = ff_result_data['E_ff']
self.desired_E_theta = self.desired_E_ff[:,0]
self.desired_E_phi = self.desired_E_ff[:,1]
self.theta_coords = ff_result_data['theta_deg']
self.phi_coords = ff_result_data['phi_deg']
self.discretisation_order = nf_input_data['order']
self.mesh = get_centred_cube(
nf_input_data['domain_size'], nf_input_data['max_edge_len'])
self.discretisation_space = dolfin.FunctionSpace(
self.mesh, "Nedelec 1st kind H(curl)", self.discretisation_order)
self.discretisation_dofs = nf_input_data['x']
self.frequency = nf_input_data['freq']
class test_surface_ntff(unittest.TestCase):
test_data_file = 'data/reference_surface_ntff-2-0.149896229-0.0499654096667.pickle'
rtol=1e-12
atol=1e-7
def setUp(self):
desired_file = Paths.get_module_path_file(self.test_data_file, __file__)
self.environment = NTFFEnvironment(desired_file)
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import pickle
import numpy as N
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff
from sucemfem.PostProcessing import variational_ntff
and context (class names, function names, or code) available:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
. Output only the next line. | self.DUT = surface_ntff.NTFF(self.environment.discretisation_space) |
Continue the code snippet: <|code_start|>## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test:
class test_interpolant(unittest.TestCase):
test_data_file = 'data/interpolant_test_data.pickle'
rtol=1e-10
atol=1e-7
def setUp(self):
desired_file = Paths.get_module_path_file(self.test_data_file, __file__)
self.desired_data = pickle.load(desired_file)
class test_interpolant_expression(test_interpolant):
def setUp(self):
super(test_interpolant_expression, self).setUp()
<|code_end|>
. Use current file imports:
import unittest
import pickle
import numpy as N
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff
from sucemfem.PostProcessing import variational_ntff
and context (classes, functions, or code) from other files:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
. Output only the next line. | self.DUT = variational_ntff.TransformTestingExpression() |
Predict the next line for this snippet: <|code_start|>from __future__ import division
class SurfaceNTFFForms(object):
def __init__(self, function_space):
self.function_space = V = function_space
self.n = V.cell().n
# \vec{r'}, i.e. rprime is simply the position vector
self.rprime = V.cell().x
self.E_r = dolfin.Function(V)
self.E_i = dolfin.Function(V)
self.r_hat = ntff_expressions.get_r_hat()
self.k0 = ntff_expressions.get_k0()
self.theta_hat = ntff_expressions.get_theta_hat()
self.phi_hat = ntff_expressions.get_phi_hat()
# phase term to be used in sin/cos
self.phase = ntff_expressions.get_phase(self.k0, self.rprime, self.r_hat)
def set_dofs(self, dofs):
x_r = np.real(dofs).copy()
x_i = np.imag(dofs).copy()
self.E_r.vector()[:] = x_r
self.E_i.vector()[:] = x_i
def get_N_form(self):
try:
return self.N_form
except AttributeError:
pass
# Set up magnetic field and equivalent electric current forms
<|code_end|>
with the help of current file imports:
import numpy as np
import dolfin
import sucemfem.PostProcessing.ntff_expressions as ntff_expressions
from dolfin import curl, cross, dx, ds, Constant, dot
from sucemfem.Consts import Z0, c0
and context from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
, which may contain function names, class names, or code. Output only the next line. | H_r = -curl(self.E_i)/(self.k0*Z0) |
Given the code snippet: <|code_start|> # evaluate numerically, adding the real and imaginary parts
L = self.get_L_form()
L_theta = dolfin.assemble(L['r_theta']) + 1j*dolfin.assemble(L['i_theta'])
L_phi = dolfin.assemble(L['r_phi']) + 1j*dolfin.assemble(L['i_phi'])
return (L_theta, L_phi)
def set_parms(self, theta, phi, k0):
self.k0.k0 = k0
self.theta_hat.theta = theta
self.theta_hat.phi = phi
self.phi_hat.theta = theta
self.phi_hat.phi = phi
self.r_hat.theta = theta
self.r_hat.phi = phi
class NTFF(object):
def __init__(self, function_space):
self.function_space = V = function_space
# Outward pointing normal
self.forms = SurfaceNTFFForms(V)
self._L = []
self._N = []
self._r_fac = []
def set_dofs(self, dofs):
self.forms.set_dofs(dofs)
def set_frequency(self, frequency):
self.frequency = frequency
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import dolfin
import sucemfem.PostProcessing.ntff_expressions as ntff_expressions
from dolfin import curl, cross, dx, ds, Constant, dot
from sucemfem.Consts import Z0, c0
and context (functions, classes, or occasionally code) from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | self.k0 = self.frequency*2*np.pi/c0 |
Given snippet: <|code_start|> print "Setting matrix entries"
t = Timer("Set matrix entries")
Beta = Beta_km(f)
ko = k_o(f)
coefficient_H_C = 1j*Beta*2/N.sqrt(a*b)*N.sqrt(ko*Z_0/Beta)
coefficient_A_E = N.sqrt(a/b)*N.sqrt(ko*Z_0/Beta)
for k in range(num_ports):
for m in range(M):
j = k*M + m
B_km = Beta_km(f, m+1)
AD[j,j] = -N.sqrt(a/b)*N.sqrt(ko*Z_0/B_km)
coefficients_C[j] = 1j*B_km*2/N.sqrt(a*b)*N.sqrt(ko*Z_0/B_km)
F_sp = dolfin_ublassparse_to_scipy_csr ( F ) # scipy.sparse.csr_matrix ( F.array() )
C_sp = scipy.sparse.csr_matrix ( N.dot(C, N.diag(coefficients_C)) )
# LHS[num_ports*M:,num_ports*M:] = F.array()[:,:]
# LHS[num_ports*M:,:num_ports*M] = N.dot(C, N.diag(coefficients_C))
LHS = scipy.sparse.vstack( ( AD, scipy.sparse.hstack( (C_sp, F_sp ), 'csr') ), 'csr' )
RHS[0,0] = -LHS[0,0]
RHS[num_ports*M:,0] = coefficient_H_C*H_inc.array()[:]
t.stop()
print "Solving (sparse)"
t = Timer("Sparse Solve")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as N
import pylab as P
import scipy.sparse
import csv
import sys
from dolfin import *
from sucemfem.Utilities.LinalgSolvers import solve_sparse_system
from sucemfem.Utilities.Converters import dolfin_ublassparse_to_scipy_csr
and context:
# Path: sucemfem/Utilities/LinalgSolvers.py
# def solve_sparse_system ( A, b, preconditioner_type='ilu' ):
# """
# This function solves the sparse linear system Ax = b for A a scipy sparse matrix, and b a numpy or scipy array
#
# By default an incomplete LU preconditioner is used with the bicgstab iterative solver
#
# @param A: a square matrix
# @param b: the RHS vector
# @param preconditioner_type: Preconditioner type string
# """
#
# solver = BiCGStabSolver ( A, preconditioner_type )
# # solver = BiCGStabSolver ( A ) #removed preconditioner -> 2D Waveguide works!
# x = solver.solve(b)
# return x
#
# Path: sucemfem/Utilities/Converters.py
# def dolfin_ublassparse_to_scipy_csr ( A, dtype=None, imagify=False ):
# """
# convert a DOLFIN uBLASSparseMatrix to a scipy.sparse.csr_matrix()
#
# @param A: a DOLFIN uBLASSparseMatrix
# @param dtype: the numpy data type to use to store the matrix
# @param imagify: multiply the original matrix data by 1j
# """
# import scipy.sparse
# # get the sparse data from the input matrix
# (row,col,data) = A.data() # get sparse data
# col = np.intc(col)
# row = np.intc(row)
# n = A.size(0)
# if imagify: data = data*1j
# A_sp = scipy.sparse.csr_matrix( (data,col,row), shape=(n,n), dtype=dtype)
#
# return A_sp
which might include code, classes, or functions. Output only the next line. | BE = solve_sparse_system (LHS, RHS) |
Given snippet: <|code_start|># k_o_squared.set_frequency(f)
# k_o_squared.f = f
k_o_squared.value = k_o(f)**2
print "Assemble F"
# F = S - k_o_squared*T
assemble(f_ii, tensor=F )
# F = assemble(s_ii - k_o(f)**2*t_ii)
print "apply BC"
bc.apply(F)
print "Done"
# P.show()
print "Setting matrix entries"
t = Timer("Set matrix entries")
Beta = Beta_km(f)
ko = k_o(f)
coefficient_H_C = 1j*Beta*2/N.sqrt(a*b)*N.sqrt(ko*Z_0/Beta)
coefficient_A_E = N.sqrt(a/b)*N.sqrt(ko*Z_0/Beta)
for k in range(num_ports):
for m in range(M):
j = k*M + m
B_km = Beta_km(f, m+1)
AD[j,j] = -N.sqrt(a/b)*N.sqrt(ko*Z_0/B_km)
coefficients_C[j] = 1j*B_km*2/N.sqrt(a*b)*N.sqrt(ko*Z_0/B_km)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as N
import pylab as P
import scipy.sparse
import csv
import sys
from dolfin import *
from sucemfem.Utilities.LinalgSolvers import solve_sparse_system
from sucemfem.Utilities.Converters import dolfin_ublassparse_to_scipy_csr
and context:
# Path: sucemfem/Utilities/LinalgSolvers.py
# def solve_sparse_system ( A, b, preconditioner_type='ilu' ):
# """
# This function solves the sparse linear system Ax = b for A a scipy sparse matrix, and b a numpy or scipy array
#
# By default an incomplete LU preconditioner is used with the bicgstab iterative solver
#
# @param A: a square matrix
# @param b: the RHS vector
# @param preconditioner_type: Preconditioner type string
# """
#
# solver = BiCGStabSolver ( A, preconditioner_type )
# # solver = BiCGStabSolver ( A ) #removed preconditioner -> 2D Waveguide works!
# x = solver.solve(b)
# return x
#
# Path: sucemfem/Utilities/Converters.py
# def dolfin_ublassparse_to_scipy_csr ( A, dtype=None, imagify=False ):
# """
# convert a DOLFIN uBLASSparseMatrix to a scipy.sparse.csr_matrix()
#
# @param A: a DOLFIN uBLASSparseMatrix
# @param dtype: the numpy data type to use to store the matrix
# @param imagify: multiply the original matrix data by 1j
# """
# import scipy.sparse
# # get the sparse data from the input matrix
# (row,col,data) = A.data() # get sparse data
# col = np.intc(col)
# row = np.intc(row)
# n = A.size(0)
# if imagify: data = data*1j
# A_sp = scipy.sparse.csr_matrix( (data,col,row), shape=(n,n), dtype=dtype)
#
# return A_sp
which might include code, classes, or functions. Output only the next line. | F_sp = dolfin_ublassparse_to_scipy_csr ( F ) # scipy.sparse.csr_matrix ( F.array() ) |
Using the snippet: <|code_start|>## Copyright (C) 2011 Stellenbosch University
##
## This file is part of SUCEM.
##
## SUCEM is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
class VoltageAlongLine(object):
"""Measure voltage along a straight line between two points"""
def __init__(self, field_function):
self.field_function = field_function
def calculate_voltage(self, start_pt, end_pt):
fn = self.field_function
delta = end_pt - start_pt
<|code_end|>
, determine the next line of code. You have imports:
import dolfin
import numpy as np
from scipy.integrate import romberg
from sucemfem.Utilities.Geometry import unit_vector, vector_length
from sucemfem.Utilities.Converters import as_dolfin_vector
and context (class names, function names, or code) available:
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
#
# Path: sucemfem/Utilities/Converters.py
# def as_dolfin_vector(a):
# """Convert array to a dolfin Vector() instance"""
# assert len(a.shape) == 1 # 1D vectors please
# v = dolfin.Vector(len(a))
# v.set_local(np.require(a, requirements=['C',]))
# return v
. Output only the next line. | l_hat = unit_vector(delta) |
Next line prediction: <|code_start|>## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
class VoltageAlongLine(object):
"""Measure voltage along a straight line between two points"""
def __init__(self, field_function):
self.field_function = field_function
def calculate_voltage(self, start_pt, end_pt):
fn = self.field_function
delta = end_pt - start_pt
l_hat = unit_vector(delta)
# Evaluate E . l_hat where E is the electric field vector and
# l_hat is a unit vector along the integration path.
eval_fn = lambda l: np.dot(l_hat, fn(*(start_pt + delta*l)))
# Integrate over unit length
intg = romberg(eval_fn, 0, 1)
# Multiply by inteval length to de-normalise
<|code_end|>
. Use current file imports:
(import dolfin
import numpy as np
from scipy.integrate import romberg
from sucemfem.Utilities.Geometry import unit_vector, vector_length
from sucemfem.Utilities.Converters import as_dolfin_vector)
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
#
# Path: sucemfem/Utilities/Converters.py
# def as_dolfin_vector(a):
# """Convert array to a dolfin Vector() instance"""
# assert len(a.shape) == 1 # 1D vectors please
# v = dolfin.Vector(len(a))
# v.set_local(np.require(a, requirements=['C',]))
# return v
. Output only the next line. | interval_len = vector_length(delta) |
Next line prediction: <|code_start|>## Contact: cemagga@gmail.com
from __future__ import division
class VoltageAlongLine(object):
"""Measure voltage along a straight line between two points"""
def __init__(self, field_function):
self.field_function = field_function
def calculate_voltage(self, start_pt, end_pt):
fn = self.field_function
delta = end_pt - start_pt
l_hat = unit_vector(delta)
# Evaluate E . l_hat where E is the electric field vector and
# l_hat is a unit vector along the integration path.
eval_fn = lambda l: np.dot(l_hat, fn(*(start_pt + delta*l)))
# Integrate over unit length
intg = romberg(eval_fn, 0, 1)
# Multiply by inteval length to de-normalise
interval_len = vector_length(delta)
intg = intg*interval_len
return intg
class ComplexVoltageAlongLine(object):
"""Measure complex voltage along a straight line between two points"""
def __init__(self, function_space):
self.function_space = function_space
def set_dofs(self, dofs):
self.dofs = dofs
<|code_end|>
. Use current file imports:
(import dolfin
import numpy as np
from scipy.integrate import romberg
from sucemfem.Utilities.Geometry import unit_vector, vector_length
from sucemfem.Utilities.Converters import as_dolfin_vector)
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
#
# Path: sucemfem/Utilities/Converters.py
# def as_dolfin_vector(a):
# """Convert array to a dolfin Vector() instance"""
# assert len(a.shape) == 1 # 1D vectors please
# v = dolfin.Vector(len(a))
# v.set_local(np.require(a, requirements=['C',]))
# return v
. Output only the next line. | self.x_r = as_dolfin_vector(self.dofs.real) |
Given snippet: <|code_start|>data = pickle.load(open(fname))
print data
lam = c0/data['freq']
k0 = data['freq']*2*N.pi/c0
mesh = get_centred_cube(data['domain_size'], data['max_edge_len'])
#plot(mesh,interactive=True)
V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", data['order'])
#------------------------------
# Calculate using the standard surface integral NTFF
surf_ntff = surface_ntff.NTFF(V)
surf_ntff.set_dofs(data['x'])
surf_ntff.set_frequency(data['freq'])
surf_E_ff = N.array([surf_ntff.calc_pt(th_deg, ph_deg)
for th_deg, ph_deg in zip(theta_deg, phi_deg)])
surf_E_theta = surf_E_ff[:,0]
surf_E_phi = surf_E_ff[:,1]
#------------------------------
# Calculate using the variational integral NTFF
var_ntff = variational_ntff.NTFF(V)
var_ntff.set_k0(k0)
var_ntff.set_dofs(data['x'])
var_ntff.set_frequency(data['freq'])
var_E_ff = N.array([var_ntff.calc_pt(th_deg, ph_deg)
for th_deg, ph_deg in zip(theta_deg, phi_deg)])
var_E_theta = var_E_ff[:,0]
var_E_phi = var_E_ff[:,1]
#------------------------------
# Analytical solution of the far-field of an infintesimal dipole
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pickle
import numpy as N
import sys
import sucemfem.Utilities.Optimization
import matplotlib as mpl
import matplotlib.pyplot as plt
from dolfin import *
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
which might include code, classes, or functions. Output only the next line. | E_theta_an = Z0*N.exp(-1j*k0)*(1j*k0*1*lam/1000)/(4*N.pi)*N.sin(N.deg2rad(theta_deg)) |
Given the following code snippet before the placeholder: <|code_start|>## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
#import dolfin
sys.path.append('../../')
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
fname = 'reference_dofs-2-0.149896229-0.0499654096667.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
print data
<|code_end|>
, predict the next line using imports from the current file:
import pickle
import numpy as N
import sys
import sucemfem.Utilities.Optimization
import matplotlib as mpl
import matplotlib.pyplot as plt
from dolfin import *
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
. Output only the next line. | lam = c0/data['freq'] |
Using the snippet: <|code_start|>## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
#import dolfin
sys.path.append('../../')
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
fname = 'reference_dofs-2-0.149896229-0.0499654096667.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
print data
lam = c0/data['freq']
k0 = data['freq']*2*N.pi/c0
<|code_end|>
, determine the next line of code. You have imports:
import pickle
import numpy as N
import sys
import sucemfem.Utilities.Optimization
import matplotlib as mpl
import matplotlib.pyplot as plt
from dolfin import *
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context (class names, function names, or code) available:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
. Output only the next line. | mesh = get_centred_cube(data['domain_size'], data['max_edge_len']) |
Here is a snippet: <|code_start|>## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
#import dolfin
sys.path.append('../../')
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
fname = 'reference_dofs-2-0.149896229-0.0499654096667.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
print data
lam = c0/data['freq']
k0 = data['freq']*2*N.pi/c0
mesh = get_centred_cube(data['domain_size'], data['max_edge_len'])
#plot(mesh,interactive=True)
V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", data['order'])
#------------------------------
# Calculate using the standard surface integral NTFF
<|code_end|>
. Write the next line using the current file imports:
import pickle
import numpy as N
import sys
import sucemfem.Utilities.Optimization
import matplotlib as mpl
import matplotlib.pyplot as plt
from dolfin import *
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
, which may include functions, classes, or code. Output only the next line. | surf_ntff = surface_ntff.NTFF(V) |
Predict the next line for this snippet: <|code_start|>sys.path.append('../../')
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
fname = 'reference_dofs-2-0.149896229-0.0499654096667.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
print data
lam = c0/data['freq']
k0 = data['freq']*2*N.pi/c0
mesh = get_centred_cube(data['domain_size'], data['max_edge_len'])
#plot(mesh,interactive=True)
V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", data['order'])
#------------------------------
# Calculate using the standard surface integral NTFF
surf_ntff = surface_ntff.NTFF(V)
surf_ntff.set_dofs(data['x'])
surf_ntff.set_frequency(data['freq'])
surf_E_ff = N.array([surf_ntff.calc_pt(th_deg, ph_deg)
for th_deg, ph_deg in zip(theta_deg, phi_deg)])
surf_E_theta = surf_E_ff[:,0]
surf_E_phi = surf_E_ff[:,1]
#------------------------------
# Calculate using the variational integral NTFF
<|code_end|>
with the help of current file imports:
import pickle
import numpy as N
import sys
import sucemfem.Utilities.Optimization
import matplotlib as mpl
import matplotlib.pyplot as plt
from dolfin import *
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
, which may contain function names, class names, or code. Output only the next line. | var_ntff = variational_ntff.NTFF(V) |
Given the following code snippet before the placeholder: <|code_start|> current flows from the start point towards the endpoint.
"""
self.source_endpoints = source_endpoints
self._dirty = True
def set_value(self, value):
"""Set line current value in Amperes"""
self.value = value
self._dirty = True
def _update(self):
if self._dirty:
self.source_start, self.source_end = self.source_endpoints
self.source_delta = self.source_end - self.source_start
self.vector_value = unit_vector(self.source_delta)*self.value
self._dirty == False
def get_contribution(self):
self._update()
source_len = vector_length(self.source_delta)
no_pts = self.no_integration_points
if no_pts == 1:
intg_pts = [self.source_start + self.source_delta*0.5]
else:
intg_pts = self.source_start + self.source_delta*np.linspace(
0,1,no_pts)[:, np.newaxis]
contribs = collections.defaultdict(lambda : 0.)
point_magnitude = self.vector_value*source_len/no_pts
for pt in intg_pts:
<|code_end|>
, predict the next line using imports from the current file:
import dolfin
import numpy as np
import collections
from sucemfem.Sources.current_source import CurrentSource
from sucemfem.Sources.point_source import calc_pointsource_contrib
from sucemfem.Utilities.Geometry import unit_vector, vector_length
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Sources/current_source.py
# class CurrentSource(object):
# """Abstract base class for current sources"""
#
# def set_function_space(self, function_space):
# """Set function space that the source is to be applied to"""
# self.function_space = function_space
#
# def get_contribution(self):
# """Get and return the RHS contribution of the current source
#
# @raise NotImplementedError: This method should be implemented in a sub-class.
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (dofnos, rhs_contribs) -- An array containing the indices of the degrees of freedom associated with
# the source, and the numerical values of the contributions of the current source.
#
# C{RHS[dofnos] += rhs_contribs} will add the current source to the system's RHS.
# """
# raise NotImplementedError('User subclass should implement get_contribution()')
#
# Path: sucemfem/Sources/point_source.py
# def calc_pointsource_contrib(V, source_coords, source_value):
# """Calculate the RHS contribution of a current point source (i.e. electric dipole)
#
# @param V: dolfin FunctionSpace object
# @param source_coords: length 3 array with x,y,z coordinates of point source
# @param source_value: length 3 array with x,y,z componets of source current
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (dofnos, rhs_contribs) -- An array containing the indices of the degrees of freedom associated with
# the source, and the numerical values of the contributions of the current source.
#
# C{RHS[dofnos] += rhs_contribs} will add the current source to the system's RHS.
# """
# source_coords = N.asarray(source_coords, dtype=N.float64)
# source_value = N.asarray(source_value)
# dm = V.dofmap()
# dofnos = N.zeros(dm.max_cell_dimension(), dtype=N.uintc)
# source_pt = dolfin.Point(*source_coords)
# io = V.mesh().intersection_operator()
# try:
# # cell_index = V.mesh().any_intersected_entity(source_pt)
# cell_index = io.any_intersected_entity(source_pt)
# except StandardError:
# # CGAL as used by dolfin to implement intersection searches
# # seems to break with 1-element meshes
# if dolfin.Cell(V.mesh(), 0).intersects(source_pt):
# cell_index = 0
# else: raise
# c = dolfin.Cell(V.mesh(), cell_index)
# # Check that the source point is in this element
# assert(c.intersects_exactly(source_pt))
#
# dm.tabulate_dofs(dofnos, c)
# finite_element = V.dolfin_element()
# no_basis_fns = finite_element.space_dimension()
# # Vector valued elements have rank of 1
# assert(finite_element.value_rank() == 1)
# # Vector valued elements have only one rank (i.e. 0) along which
# # dimensions are defined. This is the dimension that the basis
# # function value vector is. Since we have 3D Nedelec elements here
# # this should be 3
# bf_value_dimension = finite_element.value_dimension(0)
# el_basis_vals = N.zeros((no_basis_fns, bf_value_dimension), dtype=N.float64)
# finite_element.evaluate_basis_all(el_basis_vals, source_coords, c)
# rhs_contribs = N.sum(el_basis_vals*source_value, axis=1)
# return dofnos, rhs_contribs
#
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
. Output only the next line. | dnos, vals = calc_pointsource_contrib( |
Continue the code snippet: <|code_start|>class FillamentCurrentSource(CurrentSource):
no_integration_points = 100
def __init__(self, *names, **kwargs):
self._dirty = True
def set_no_integration_points(self, no_integration_points):
"""Set number of integration points to use along the length of
the fillament"""
self.no_integration_points = no_integration_points
def set_source_endpoints(self, source_endpoints):
"""Set the current filament endpoints.
@param source_endpoints: 2x3 array with the coordinates of the start
and end point of the current fillament. The conventional
current flows from the start point towards the endpoint.
"""
self.source_endpoints = source_endpoints
self._dirty = True
def set_value(self, value):
"""Set line current value in Amperes"""
self.value = value
self._dirty = True
def _update(self):
if self._dirty:
self.source_start, self.source_end = self.source_endpoints
self.source_delta = self.source_end - self.source_start
<|code_end|>
. Use current file imports:
import dolfin
import numpy as np
import collections
from sucemfem.Sources.current_source import CurrentSource
from sucemfem.Sources.point_source import calc_pointsource_contrib
from sucemfem.Utilities.Geometry import unit_vector, vector_length
and context (classes, functions, or code) from other files:
# Path: sucemfem/Sources/current_source.py
# class CurrentSource(object):
# """Abstract base class for current sources"""
#
# def set_function_space(self, function_space):
# """Set function space that the source is to be applied to"""
# self.function_space = function_space
#
# def get_contribution(self):
# """Get and return the RHS contribution of the current source
#
# @raise NotImplementedError: This method should be implemented in a sub-class.
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (dofnos, rhs_contribs) -- An array containing the indices of the degrees of freedom associated with
# the source, and the numerical values of the contributions of the current source.
#
# C{RHS[dofnos] += rhs_contribs} will add the current source to the system's RHS.
# """
# raise NotImplementedError('User subclass should implement get_contribution()')
#
# Path: sucemfem/Sources/point_source.py
# def calc_pointsource_contrib(V, source_coords, source_value):
# """Calculate the RHS contribution of a current point source (i.e. electric dipole)
#
# @param V: dolfin FunctionSpace object
# @param source_coords: length 3 array with x,y,z coordinates of point source
# @param source_value: length 3 array with x,y,z componets of source current
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (dofnos, rhs_contribs) -- An array containing the indices of the degrees of freedom associated with
# the source, and the numerical values of the contributions of the current source.
#
# C{RHS[dofnos] += rhs_contribs} will add the current source to the system's RHS.
# """
# source_coords = N.asarray(source_coords, dtype=N.float64)
# source_value = N.asarray(source_value)
# dm = V.dofmap()
# dofnos = N.zeros(dm.max_cell_dimension(), dtype=N.uintc)
# source_pt = dolfin.Point(*source_coords)
# io = V.mesh().intersection_operator()
# try:
# # cell_index = V.mesh().any_intersected_entity(source_pt)
# cell_index = io.any_intersected_entity(source_pt)
# except StandardError:
# # CGAL as used by dolfin to implement intersection searches
# # seems to break with 1-element meshes
# if dolfin.Cell(V.mesh(), 0).intersects(source_pt):
# cell_index = 0
# else: raise
# c = dolfin.Cell(V.mesh(), cell_index)
# # Check that the source point is in this element
# assert(c.intersects_exactly(source_pt))
#
# dm.tabulate_dofs(dofnos, c)
# finite_element = V.dolfin_element()
# no_basis_fns = finite_element.space_dimension()
# # Vector valued elements have rank of 1
# assert(finite_element.value_rank() == 1)
# # Vector valued elements have only one rank (i.e. 0) along which
# # dimensions are defined. This is the dimension that the basis
# # function value vector is. Since we have 3D Nedelec elements here
# # this should be 3
# bf_value_dimension = finite_element.value_dimension(0)
# el_basis_vals = N.zeros((no_basis_fns, bf_value_dimension), dtype=N.float64)
# finite_element.evaluate_basis_all(el_basis_vals, source_coords, c)
# rhs_contribs = N.sum(el_basis_vals*source_value, axis=1)
# return dofnos, rhs_contribs
#
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
. Output only the next line. | self.vector_value = unit_vector(self.source_delta)*self.value |
Next line prediction: <|code_start|>
def set_no_integration_points(self, no_integration_points):
"""Set number of integration points to use along the length of
the fillament"""
self.no_integration_points = no_integration_points
def set_source_endpoints(self, source_endpoints):
"""Set the current filament endpoints.
@param source_endpoints: 2x3 array with the coordinates of the start
and end point of the current fillament. The conventional
current flows from the start point towards the endpoint.
"""
self.source_endpoints = source_endpoints
self._dirty = True
def set_value(self, value):
"""Set line current value in Amperes"""
self.value = value
self._dirty = True
def _update(self):
if self._dirty:
self.source_start, self.source_end = self.source_endpoints
self.source_delta = self.source_end - self.source_start
self.vector_value = unit_vector(self.source_delta)*self.value
self._dirty == False
def get_contribution(self):
self._update()
<|code_end|>
. Use current file imports:
(import dolfin
import numpy as np
import collections
from sucemfem.Sources.current_source import CurrentSource
from sucemfem.Sources.point_source import calc_pointsource_contrib
from sucemfem.Utilities.Geometry import unit_vector, vector_length)
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Sources/current_source.py
# class CurrentSource(object):
# """Abstract base class for current sources"""
#
# def set_function_space(self, function_space):
# """Set function space that the source is to be applied to"""
# self.function_space = function_space
#
# def get_contribution(self):
# """Get and return the RHS contribution of the current source
#
# @raise NotImplementedError: This method should be implemented in a sub-class.
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (dofnos, rhs_contribs) -- An array containing the indices of the degrees of freedom associated with
# the source, and the numerical values of the contributions of the current source.
#
# C{RHS[dofnos] += rhs_contribs} will add the current source to the system's RHS.
# """
# raise NotImplementedError('User subclass should implement get_contribution()')
#
# Path: sucemfem/Sources/point_source.py
# def calc_pointsource_contrib(V, source_coords, source_value):
# """Calculate the RHS contribution of a current point source (i.e. electric dipole)
#
# @param V: dolfin FunctionSpace object
# @param source_coords: length 3 array with x,y,z coordinates of point source
# @param source_value: length 3 array with x,y,z componets of source current
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (dofnos, rhs_contribs) -- An array containing the indices of the degrees of freedom associated with
# the source, and the numerical values of the contributions of the current source.
#
# C{RHS[dofnos] += rhs_contribs} will add the current source to the system's RHS.
# """
# source_coords = N.asarray(source_coords, dtype=N.float64)
# source_value = N.asarray(source_value)
# dm = V.dofmap()
# dofnos = N.zeros(dm.max_cell_dimension(), dtype=N.uintc)
# source_pt = dolfin.Point(*source_coords)
# io = V.mesh().intersection_operator()
# try:
# # cell_index = V.mesh().any_intersected_entity(source_pt)
# cell_index = io.any_intersected_entity(source_pt)
# except StandardError:
# # CGAL as used by dolfin to implement intersection searches
# # seems to break with 1-element meshes
# if dolfin.Cell(V.mesh(), 0).intersects(source_pt):
# cell_index = 0
# else: raise
# c = dolfin.Cell(V.mesh(), cell_index)
# # Check that the source point is in this element
# assert(c.intersects_exactly(source_pt))
#
# dm.tabulate_dofs(dofnos, c)
# finite_element = V.dolfin_element()
# no_basis_fns = finite_element.space_dimension()
# # Vector valued elements have rank of 1
# assert(finite_element.value_rank() == 1)
# # Vector valued elements have only one rank (i.e. 0) along which
# # dimensions are defined. This is the dimension that the basis
# # function value vector is. Since we have 3D Nedelec elements here
# # this should be 3
# bf_value_dimension = finite_element.value_dimension(0)
# el_basis_vals = N.zeros((no_basis_fns, bf_value_dimension), dtype=N.float64)
# finite_element.evaluate_basis_all(el_basis_vals, source_coords, c)
# rhs_contribs = N.sum(el_basis_vals*source_value, axis=1)
# return dofnos, rhs_contribs
#
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
. Output only the next line. | source_len = vector_length(self.source_delta) |
Predict the next line for this snippet: <|code_start|>## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Evan Lezar <mail@evanlezar.com>
"""A simple 2D eigenproblem which calculates the TM modes of a square guide.
Note that this is done by modelling the Magnetic field and as such no dirichlet BCs are used.
Only natural boundary conditions."""
sys.path.insert(0, '../../../')
del sys.path[0]
script_path = os.path.dirname(__file__)
# Load the mesh and the material region markers
mesh = dol.UnitSquare ( 5, 5 )
a = 1.0
b = 1.0
mesh.coordinates()[:,0] = a*mesh.coordinates()[:,0]
mesh.coordinates()[:,1] = b*mesh.coordinates()[:,1]
# Use 4th order basis functions
order = 4
# Set up the eigen problem
<|code_end|>
with the help of current file imports:
import sys
import numpy as N
import os
import dolfin as dol
import warnings
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import EigenProblem
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import DefaultEigenSolver
from sucemfem.Consts import c0
and context from other files:
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class EigenProblem(EMProblem):
# FormCombiner = CombineForms
#
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class DefaultEigenSolver(object):
# def set_eigenproblem(self, eigenproblem):
# """Sets initialised instance of EigenProblem to solve"""
# self.eigenproblem = eigenproblem
#
# def set_sigma(self, sigma):
# """Spectrum shift (sigma) to apply to k^2"""
# self.sigma = sigma
#
# def solve_problem(self, nev, ncv=None):
# """Solve problem and return the eigenvalues and eigenvectors
#
# @param nev: Number of eigenpairs to compute
# @keyword ncv: Number of Arnoldi basisvectors to use.
# (default: 2*nev+1).
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (eigs_w, eigs_v) -- A tupple consisting of the eigenvalues and eigenvectors of the eigensystem.
# The eigenvalues are returned as an array of n_eig values corresponding to k^2 for the mode's resonant wavenumber.
# The eigenvectors are returned as a 2D array of shape (n_eig, problem_dim), with row i corresponding to the
# modal distributions associated with the i-th eigenvalue.
# """
# M = self.eigenproblem.system_matrices['M']
# S = self.eigenproblem.system_matrices['S']
# solve_mat = S - self.sigma*M
# lu = dolfin.LUSolver(solve_mat)
# lu.parameters["reuse_factorization"] = True
# lu.parameters["report"] = False
# bb = dolfin.Vector(M.size(0))
# xx = dolfin.Vector(M.size(0))
# def sigma_solve(b):
# bb[:] = b
# lu.solve(xx, bb)
# return xx[:]
# M_matvec = lambda x: M*x
#
# #speigs in ARPACK has been removed in scipy 0.9/0.10
# #eigs is now in scipy.sparse.linalg.arpack
# #therefore force M_matvec to have "shape" and "dtype" attributes to comply with "eigs" requirements
# #also perform the sigma_solve function for spectrum shift to sigma
# class RM:
# def __init__(self, M):
# self.M = M
# self.shape = (M.size(0), M.size(1))
# self.dtype = np.dtype('d')
# def matvec(self, x):
# return sigma_solve(self.M*x)
#
# # eigs_w, eigs_v = speigs.ARPACK_gen_eigs(
# # M_matvec, sigma_solve, M.size(0), self.sigma, nev, ncv=ncv)
#
# eigs_w, eigs_v= arpack.eigs(RM(M), k=nev, sigma=self.sigma, which='LM', ncv=ncv)
#
# return eigs_w, eigs_v.T
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
, which may contain function names, class names, or code. Output only the next line. | ep = EigenProblem() |
Continue the code snippet: <|code_start|># Evan Lezar <mail@evanlezar.com>
"""A simple 2D eigenproblem which calculates the TM modes of a square guide.
Note that this is done by modelling the Magnetic field and as such no dirichlet BCs are used.
Only natural boundary conditions."""
sys.path.insert(0, '../../../')
del sys.path[0]
script_path = os.path.dirname(__file__)
# Load the mesh and the material region markers
mesh = dol.UnitSquare ( 5, 5 )
a = 1.0
b = 1.0
mesh.coordinates()[:,0] = a*mesh.coordinates()[:,0]
mesh.coordinates()[:,1] = b*mesh.coordinates()[:,1]
# Use 4th order basis functions
order = 4
# Set up the eigen problem
ep = EigenProblem()
ep.set_mesh(mesh)
ep.set_basis_order(order)
ep.init_problem()
# Set up eigen problem solver where sigma is the shift to use in the
# shift-invert process
sigma = 1.5
<|code_end|>
. Use current file imports:
import sys
import numpy as N
import os
import dolfin as dol
import warnings
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import EigenProblem
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import DefaultEigenSolver
from sucemfem.Consts import c0
and context (classes, functions, or code) from other files:
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class EigenProblem(EMProblem):
# FormCombiner = CombineForms
#
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class DefaultEigenSolver(object):
# def set_eigenproblem(self, eigenproblem):
# """Sets initialised instance of EigenProblem to solve"""
# self.eigenproblem = eigenproblem
#
# def set_sigma(self, sigma):
# """Spectrum shift (sigma) to apply to k^2"""
# self.sigma = sigma
#
# def solve_problem(self, nev, ncv=None):
# """Solve problem and return the eigenvalues and eigenvectors
#
# @param nev: Number of eigenpairs to compute
# @keyword ncv: Number of Arnoldi basisvectors to use.
# (default: 2*nev+1).
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (eigs_w, eigs_v) -- A tupple consisting of the eigenvalues and eigenvectors of the eigensystem.
# The eigenvalues are returned as an array of n_eig values corresponding to k^2 for the mode's resonant wavenumber.
# The eigenvectors are returned as a 2D array of shape (n_eig, problem_dim), with row i corresponding to the
# modal distributions associated with the i-th eigenvalue.
# """
# M = self.eigenproblem.system_matrices['M']
# S = self.eigenproblem.system_matrices['S']
# solve_mat = S - self.sigma*M
# lu = dolfin.LUSolver(solve_mat)
# lu.parameters["reuse_factorization"] = True
# lu.parameters["report"] = False
# bb = dolfin.Vector(M.size(0))
# xx = dolfin.Vector(M.size(0))
# def sigma_solve(b):
# bb[:] = b
# lu.solve(xx, bb)
# return xx[:]
# M_matvec = lambda x: M*x
#
# #speigs in ARPACK has been removed in scipy 0.9/0.10
# #eigs is now in scipy.sparse.linalg.arpack
# #therefore force M_matvec to have "shape" and "dtype" attributes to comply with "eigs" requirements
# #also perform the sigma_solve function for spectrum shift to sigma
# class RM:
# def __init__(self, M):
# self.M = M
# self.shape = (M.size(0), M.size(1))
# self.dtype = np.dtype('d')
# def matvec(self, x):
# return sigma_solve(self.M*x)
#
# # eigs_w, eigs_v = speigs.ARPACK_gen_eigs(
# # M_matvec, sigma_solve, M.size(0), self.sigma, nev, ncv=ncv)
#
# eigs_w, eigs_v= arpack.eigs(RM(M), k=nev, sigma=self.sigma, which='LM', ncv=ncv)
#
# return eigs_w, eigs_v.T
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | es = DefaultEigenSolver() |
Given snippet: <|code_start|>## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
sys.path.append('../../')
reload(point_source)
# Define material and frequency
eps_r = 1;
mu_r = 1;
freq = 1e9;
source_coord = [0.5,0.5,0.5]
source_value = N.array([0,0,1.])
# Define mesh
mesh = dol.UnitCube(11,11,11)
# Define function space
order = 1
V = dol.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", order)
# Define basis and bilinear form
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import numpy as N
import os
import dolfin as dol
import scipy.sparse
import point_source
from dolfin import dot, cross, curl, inner, dx, ds
from sucemfem.Consts import eps0, mu0, c0
from scipy.sparse import csr_matrix
from pyamg import smoothed_aggregation_solver
from numpy import intc
and context:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
which might include code, classes, or functions. Output only the next line. | k_0 = 2*N.pi*freq/c0 |
Based on the snippet: <|code_start|>##
## This file is part of SUCEM.
##
## SUCEM is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test:
class test_VoltageAlongLine(unittest.TestCase):
def setUp(self):
self.mesh = dolfin.UnitCube(3,3,3)
self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 2)
self.u = dolfin.interpolate(
dolfin.Expression(('0','0', '2*x[2]')), self.V)
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import numpy as np
import dolfin
from sucemfem.Sources.PostProcess import VoltageAlongLine
from sucemfem.Sources.PostProcess import ComplexVoltageAlongLine
and context (classes, functions, sometimes code) from other files:
# Path: sucemfem/Sources/PostProcess.py
# class VoltageAlongLine(object):
# """Measure voltage along a straight line between two points"""
# def __init__(self, field_function):
# self.field_function = field_function
#
# def calculate_voltage(self, start_pt, end_pt):
# fn = self.field_function
# delta = end_pt - start_pt
# l_hat = unit_vector(delta)
# # Evaluate E . l_hat where E is the electric field vector and
# # l_hat is a unit vector along the integration path.
# eval_fn = lambda l: np.dot(l_hat, fn(*(start_pt + delta*l)))
# # Integrate over unit length
# intg = romberg(eval_fn, 0, 1)
# # Multiply by inteval length to de-normalise
# interval_len = vector_length(delta)
# intg = intg*interval_len
# return intg
#
# Path: sucemfem/Sources/PostProcess.py
# class ComplexVoltageAlongLine(object):
# """Measure complex voltage along a straight line between two points"""
# def __init__(self, function_space):
# self.function_space = function_space
#
# def set_dofs(self, dofs):
# self.dofs = dofs
# self.x_r = as_dolfin_vector(self.dofs.real)
# self.x_i = as_dolfin_vector(self.dofs.imag)
# self.E_r = dolfin.Function(self.function_space, self.x_r)
# self.E_i = dolfin.Function(self.function_space, self.x_i)
# self.real_voltage = VoltageAlongLine(self.E_r)
# self.imag_voltage = VoltageAlongLine(self.E_i)
#
# def calculate_voltage(self, start_pt, end_pt):
# return (self.real_voltage.calculate_voltage(start_pt, end_pt) +
# 1j*self.imag_voltage.calculate_voltage(start_pt, end_pt))
. Output only the next line. | self.DUT = VoltageAlongLine(self.u) |
Given the code snippet: <|code_start|> self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 2)
self.u = dolfin.interpolate(
dolfin.Expression(('0','0', '2*x[2]')), self.V)
self.DUT = VoltageAlongLine(self.u)
def test_calculate_voltage(self):
# Should result in 1v
p1v_pts = (np.array([[0.5,0.35,0], [0.5,0.5,1]]),
np.array([[0,0,0], [1,1,1]]))
# Should result in -1v
m1v_pts = (np.array([[0.25,0.5,1-3e-16], [0.5,0.75,3e-16]]),
np.array([[1,1,1], [0,0,0]]))
# Should result in 0v
p0v_pts = np.array([[0,0,1], [1,1,1]])
self.assertAlmostEqual(self.DUT.calculate_voltage(*p1v_pts[0]), 1.)
self.assertAlmostEqual(self.DUT.calculate_voltage(*p1v_pts[1]), 1.)
self.assertAlmostEqual(self.DUT.calculate_voltage(*m1v_pts[0]), -1.)
self.assertAlmostEqual(self.DUT.calculate_voltage(*m1v_pts[1]), -1.)
self.assertAlmostEqual(self.DUT.calculate_voltage(*p0v_pts), 0.)
class test_ComplexVoltageAlongLine(unittest.TestCase):
def setUp(self):
self.mesh = dolfin.UnitCube(3,3,3)
self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 3)
self.u_r = dolfin.interpolate(
dolfin.Expression(('0','0', '2*x[2]')), self.V)
self.u_i = dolfin.interpolate(
dolfin.Expression(('0','0', '-x[2]*x[2]')), self.V)
self.x = self.u_r.vector().array() + 1j*self.u_i.vector().array()
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import numpy as np
import dolfin
from sucemfem.Sources.PostProcess import VoltageAlongLine
from sucemfem.Sources.PostProcess import ComplexVoltageAlongLine
and context (functions, classes, or occasionally code) from other files:
# Path: sucemfem/Sources/PostProcess.py
# class VoltageAlongLine(object):
# """Measure voltage along a straight line between two points"""
# def __init__(self, field_function):
# self.field_function = field_function
#
# def calculate_voltage(self, start_pt, end_pt):
# fn = self.field_function
# delta = end_pt - start_pt
# l_hat = unit_vector(delta)
# # Evaluate E . l_hat where E is the electric field vector and
# # l_hat is a unit vector along the integration path.
# eval_fn = lambda l: np.dot(l_hat, fn(*(start_pt + delta*l)))
# # Integrate over unit length
# intg = romberg(eval_fn, 0, 1)
# # Multiply by inteval length to de-normalise
# interval_len = vector_length(delta)
# intg = intg*interval_len
# return intg
#
# Path: sucemfem/Sources/PostProcess.py
# class ComplexVoltageAlongLine(object):
# """Measure complex voltage along a straight line between two points"""
# def __init__(self, function_space):
# self.function_space = function_space
#
# def set_dofs(self, dofs):
# self.dofs = dofs
# self.x_r = as_dolfin_vector(self.dofs.real)
# self.x_i = as_dolfin_vector(self.dofs.imag)
# self.E_r = dolfin.Function(self.function_space, self.x_r)
# self.E_i = dolfin.Function(self.function_space, self.x_i)
# self.real_voltage = VoltageAlongLine(self.E_r)
# self.imag_voltage = VoltageAlongLine(self.E_i)
#
# def calculate_voltage(self, start_pt, end_pt):
# return (self.real_voltage.calculate_voltage(start_pt, end_pt) +
# 1j*self.imag_voltage.calculate_voltage(start_pt, end_pt))
. Output only the next line. | self.DUT = ComplexVoltageAlongLine(self.V) |
Based on the snippet: <|code_start|>
See documentation of L{Materials.MaterialPropertiesFactory} for input format
"""
self.material_regions = material_regions
def set_region_meshfunction(self, region_meshfunction):
self.region_meshfunction = region_meshfunction
def _init_boundary_conditions(self):
"""Initialise the boundary conditions associated with the problem.
"""
self.boundary_conditions.set_function_space(self.function_space)
def _init_combined_forms (self):
"""Initialise the Dolfin forms for the problem.
"""
self.combined_forms = self.FormCombiner()
self.combined_forms.set_interior_forms(self.interior_forms)
self.combined_forms.set_boundary_conditions(self.boundary_conditions)
def _init_function_space (self):
"""If required, initialise a dolfin function space from the stored mesh, element_type, and basis function order information.
"""
if self.function_space is None:
self.function_space = dolfin.FunctionSpace(
self.mesh, self.element_type, self.basis_order)
def _init_interior_forms(self):
"""Initialise the Galerkin interior forms for the problem.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import dolfin
from sucemfem import Forms
from sucemfem import Materials
from sucemfem import SystemMatrices
from sucemfem.BoundaryConditions import BoundaryConditions
and context (classes, functions, sometimes code) from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/Materials.py
# class MaterialProperties(object):
# class MaterialPropertiesFactory(object):
# class MaterialFunctionFactory(object):
# def __init__(self):
# def init_values(self, **kwargs):
# def set_eps_r(self, eps_r):
# def set_mu_r(self, mu_r):
# def get_eps_r(self):
# def get_mu_r(self):
# def get_mu_r_inv(self):
# def get_eps(self):
# def get_mu(self):
# def __init__(self, material_regions):
# def get_material_properties(self):
# def __init__(self, region_material_properties, region_meshfunction, mesh):
# def get_material_functions(self, *property_names):
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/BoundaryConditions/container.py
# class BoundaryConditions(object):
# def __init__(self):
# self.boundary_conditions = {}
#
# def add_boundary_condition(self, boundary_condition):
# bc_num = boundary_condition.region_number
# # boundary condition numbers have to be unique
# assert(bc_num not in self.boundary_conditions)
# self.boundary_conditions[bc_num] = boundary_condition
#
# def apply_essential(self, A, b=None):
# """
# Apply essential boundary conditions to system matrix A and optional RHS b
# """
# for bc_num, bc in self.boundary_conditions.items():
# apply_fn = bc.get_essential_application_func()
# if b: apply_fn(A, b)
# else: apply_fn(A)
#
# def get_linear_form(self):
# """Get boundary conditions contribution to RHS linear form
# """
# lin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# lin_form = lin_form + bc.get_linear_form()
#
# return lin_form
#
# def get_bilinear_form(self):
# """Get boundary conditions contribution to bilinear form
# """
#
# bilin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# bilin_form = bilin_form + bc.get_bilinear_form()
#
# return bilin_form
#
# def set_function_space(self, function_space):
# """Set all the boundary conditions in the collection's function_space
# """
# self.function_space = function_space
# for bc in self.boundary_conditions.values():
# bc.set_function_space(function_space)
. Output only the next line. | self.interior_forms = Forms.EMGalerkinInteriorForms() |
Based on the snippet: <|code_start|> def set_region_meshfunction(self, region_meshfunction):
self.region_meshfunction = region_meshfunction
def _init_boundary_conditions(self):
"""Initialise the boundary conditions associated with the problem.
"""
self.boundary_conditions.set_function_space(self.function_space)
def _init_combined_forms (self):
"""Initialise the Dolfin forms for the problem.
"""
self.combined_forms = self.FormCombiner()
self.combined_forms.set_interior_forms(self.interior_forms)
self.combined_forms.set_boundary_conditions(self.boundary_conditions)
def _init_function_space (self):
"""If required, initialise a dolfin function space from the stored mesh, element_type, and basis function order information.
"""
if self.function_space is None:
self.function_space = dolfin.FunctionSpace(
self.mesh, self.element_type, self.basis_order)
def _init_interior_forms(self):
"""Initialise the Galerkin interior forms for the problem.
"""
self.interior_forms = Forms.EMGalerkinInteriorForms()
self.interior_forms.set_material_functions(self.material_functions)
self.interior_forms.set_function_space(self.function_space)
def _init_material_properties (self):
<|code_end|>
, predict the immediate next line with the help of imports:
import dolfin
from sucemfem import Forms
from sucemfem import Materials
from sucemfem import SystemMatrices
from sucemfem.BoundaryConditions import BoundaryConditions
and context (classes, functions, sometimes code) from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/Materials.py
# class MaterialProperties(object):
# class MaterialPropertiesFactory(object):
# class MaterialFunctionFactory(object):
# def __init__(self):
# def init_values(self, **kwargs):
# def set_eps_r(self, eps_r):
# def set_mu_r(self, mu_r):
# def get_eps_r(self):
# def get_mu_r(self):
# def get_mu_r_inv(self):
# def get_eps(self):
# def get_mu(self):
# def __init__(self, material_regions):
# def get_material_properties(self):
# def __init__(self, region_material_properties, region_meshfunction, mesh):
# def get_material_functions(self, *property_names):
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/BoundaryConditions/container.py
# class BoundaryConditions(object):
# def __init__(self):
# self.boundary_conditions = {}
#
# def add_boundary_condition(self, boundary_condition):
# bc_num = boundary_condition.region_number
# # boundary condition numbers have to be unique
# assert(bc_num not in self.boundary_conditions)
# self.boundary_conditions[bc_num] = boundary_condition
#
# def apply_essential(self, A, b=None):
# """
# Apply essential boundary conditions to system matrix A and optional RHS b
# """
# for bc_num, bc in self.boundary_conditions.items():
# apply_fn = bc.get_essential_application_func()
# if b: apply_fn(A, b)
# else: apply_fn(A)
#
# def get_linear_form(self):
# """Get boundary conditions contribution to RHS linear form
# """
# lin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# lin_form = lin_form + bc.get_linear_form()
#
# return lin_form
#
# def get_bilinear_form(self):
# """Get boundary conditions contribution to bilinear form
# """
#
# bilin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# bilin_form = bilin_form + bc.get_bilinear_form()
#
# return bilin_form
#
# def set_function_space(self, function_space):
# """Set all the boundary conditions in the collection's function_space
# """
# self.function_space = function_space
# for bc in self.boundary_conditions.values():
# bc.set_function_space(function_space)
. Output only the next line. | mat_props_fac = Materials.MaterialPropertiesFactory ( self.material_regions ) |
Here is a snippet: <|code_start|>
def _init_function_space (self):
"""If required, initialise a dolfin function space from the stored mesh, element_type, and basis function order information.
"""
if self.function_space is None:
self.function_space = dolfin.FunctionSpace(
self.mesh, self.element_type, self.basis_order)
def _init_interior_forms(self):
"""Initialise the Galerkin interior forms for the problem.
"""
self.interior_forms = Forms.EMGalerkinInteriorForms()
self.interior_forms.set_material_functions(self.material_functions)
self.interior_forms.set_function_space(self.function_space)
def _init_material_properties (self):
mat_props_fac = Materials.MaterialPropertiesFactory ( self.material_regions )
mat_func_fac = Materials.MaterialFunctionFactory(
mat_props_fac.get_material_properties(),
self.region_meshfunction,
self.mesh )
self.material_functions = mat_func_fac.get_material_functions ( 'eps_r', 'mu_r' )
def _init_system_matrices (self, matrix_class=None):
"""Initialise the system matrices associated with the problem.
@keyword matrix_class: An optional dolfin class to use for matrix storage.
(default: None).
"""
bilin_forms = self.combined_forms.get_forms()
<|code_end|>
. Write the next line using the current file imports:
import dolfin
from sucemfem import Forms
from sucemfem import Materials
from sucemfem import SystemMatrices
from sucemfem.BoundaryConditions import BoundaryConditions
and context from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/Materials.py
# class MaterialProperties(object):
# class MaterialPropertiesFactory(object):
# class MaterialFunctionFactory(object):
# def __init__(self):
# def init_values(self, **kwargs):
# def set_eps_r(self, eps_r):
# def set_mu_r(self, mu_r):
# def get_eps_r(self):
# def get_mu_r(self):
# def get_mu_r_inv(self):
# def get_eps(self):
# def get_mu(self):
# def __init__(self, material_regions):
# def get_material_properties(self):
# def __init__(self, region_material_properties, region_meshfunction, mesh):
# def get_material_functions(self, *property_names):
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/BoundaryConditions/container.py
# class BoundaryConditions(object):
# def __init__(self):
# self.boundary_conditions = {}
#
# def add_boundary_condition(self, boundary_condition):
# bc_num = boundary_condition.region_number
# # boundary condition numbers have to be unique
# assert(bc_num not in self.boundary_conditions)
# self.boundary_conditions[bc_num] = boundary_condition
#
# def apply_essential(self, A, b=None):
# """
# Apply essential boundary conditions to system matrix A and optional RHS b
# """
# for bc_num, bc in self.boundary_conditions.items():
# apply_fn = bc.get_essential_application_func()
# if b: apply_fn(A, b)
# else: apply_fn(A)
#
# def get_linear_form(self):
# """Get boundary conditions contribution to RHS linear form
# """
# lin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# lin_form = lin_form + bc.get_linear_form()
#
# return lin_form
#
# def get_bilinear_form(self):
# """Get boundary conditions contribution to bilinear form
# """
#
# bilin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# bilin_form = bilin_form + bc.get_bilinear_form()
#
# return bilin_form
#
# def set_function_space(self, function_space):
# """Set all the boundary conditions in the collection's function_space
# """
# self.function_space = function_space
# for bc in self.boundary_conditions.values():
# bc.set_function_space(function_space)
, which may include functions, classes, or code. Output only the next line. | sysmats = SystemMatrices.SystemMatrices() |
Here is a snippet: <|code_start|>## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
# Evan Lezar <mail@evanlezar.com>
class EMProblem(object):
"""
A base class for solving electromagnetic problems
"""
def __init__ (self):
self.element_type = "Nedelec 1st kind H(curl)"
self.mesh = None
self.order = None
self.function_space = None
self.material_regions = None
self.region_meshfunction = None
<|code_end|>
. Write the next line using the current file imports:
import dolfin
from sucemfem import Forms
from sucemfem import Materials
from sucemfem import SystemMatrices
from sucemfem.BoundaryConditions import BoundaryConditions
and context from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/Materials.py
# class MaterialProperties(object):
# class MaterialPropertiesFactory(object):
# class MaterialFunctionFactory(object):
# def __init__(self):
# def init_values(self, **kwargs):
# def set_eps_r(self, eps_r):
# def set_mu_r(self, mu_r):
# def get_eps_r(self):
# def get_mu_r(self):
# def get_mu_r_inv(self):
# def get_eps(self):
# def get_mu(self):
# def __init__(self, material_regions):
# def get_material_properties(self):
# def __init__(self, region_material_properties, region_meshfunction, mesh):
# def get_material_functions(self, *property_names):
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/BoundaryConditions/container.py
# class BoundaryConditions(object):
# def __init__(self):
# self.boundary_conditions = {}
#
# def add_boundary_condition(self, boundary_condition):
# bc_num = boundary_condition.region_number
# # boundary condition numbers have to be unique
# assert(bc_num not in self.boundary_conditions)
# self.boundary_conditions[bc_num] = boundary_condition
#
# def apply_essential(self, A, b=None):
# """
# Apply essential boundary conditions to system matrix A and optional RHS b
# """
# for bc_num, bc in self.boundary_conditions.items():
# apply_fn = bc.get_essential_application_func()
# if b: apply_fn(A, b)
# else: apply_fn(A)
#
# def get_linear_form(self):
# """Get boundary conditions contribution to RHS linear form
# """
# lin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# lin_form = lin_form + bc.get_linear_form()
#
# return lin_form
#
# def get_bilinear_form(self):
# """Get boundary conditions contribution to bilinear form
# """
#
# bilin_form = Forms.NullForm()
# for bc_num, bc in self.boundary_conditions.items():
# bilin_form = bilin_form + bc.get_bilinear_form()
#
# return bilin_form
#
# def set_function_space(self, function_space):
# """Set all the boundary conditions in the collection's function_space
# """
# self.function_space = function_space
# for bc in self.boundary_conditions.values():
# bc.set_function_space(function_space)
, which may include functions, classes, or code. Output only the next line. | self.boundary_conditions = BoundaryConditions() |
Given snippet: <|code_start|># Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
class SystemMatrices(object):
MatrixClass = dolfin.PETScMatrix
def set_matrix_class(self, matrix_class):
"""Set matrix class to use for system matrix.
Overrides the default value (dolfin.PETScMatrix) set in the
class definition
"""
self.MatrixClass = matrix_class
def set_matrix_forms(self, matrix_forms):
"""Set matrix_forms with a dict mapping matrix names to bilinear forms"""
self.matrix_forms = matrix_forms
def set_boundary_conditions(self, boundary_conditions):
"""Set boundary_conditions with instance of BoundaryConditions"""
self.boundary_conditions = boundary_conditions
def calc_system_matrices(self):
"""Calculate and return system matrices in a dict"""
system_matrices = dict()
for matname, form in self.matrix_forms.items():
mat = self.MatrixClass()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import dolfin
from sucemfem import Forms
and context:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
which might include code, classes, or functions. Output only the next line. | if isinstance(form, Forms.NullForm): |
Continue the code snippet: <|code_start|>## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
sys.path.append('../../')
# Define mesh
# mesh = dol.UnitCube(1,1,1)
# mesh.coordinates()[:] *= [cdims.a,cdims.b,cdims.c]
#mesh_file = 'lee_mittra92_fig6b.xml'
#mesh_file = 'lee_mittra92_fig6c.xml'
mesh_file = '../../examples/albani_bernardi74/mesh/albani_bernardi74_fig2VII.xml'
materials_mesh_file = "%s_physical_region%s" % (os.path.splitext(mesh_file))
mesh = dol.Mesh(mesh_file)
material_mesh_func = dol.MeshFunction('uint', mesh, materials_mesh_file)
materials = {1000:dict(eps_r=16),
1001:dict(eps_r=1)}
order = 3
sigma = 1.5
# Set up eigen problem
<|code_end|>
. Use current file imports:
import sys
import numpy as N
import os
import dolfin as dol
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import EigenProblem
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import DefaultEigenSolver
from sucemfem.Consts import c0
and context (classes, functions, or code) from other files:
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class EigenProblem(EMProblem):
# FormCombiner = CombineForms
#
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class DefaultEigenSolver(object):
# def set_eigenproblem(self, eigenproblem):
# """Sets initialised instance of EigenProblem to solve"""
# self.eigenproblem = eigenproblem
#
# def set_sigma(self, sigma):
# """Spectrum shift (sigma) to apply to k^2"""
# self.sigma = sigma
#
# def solve_problem(self, nev, ncv=None):
# """Solve problem and return the eigenvalues and eigenvectors
#
# @param nev: Number of eigenpairs to compute
# @keyword ncv: Number of Arnoldi basisvectors to use.
# (default: 2*nev+1).
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (eigs_w, eigs_v) -- A tupple consisting of the eigenvalues and eigenvectors of the eigensystem.
# The eigenvalues are returned as an array of n_eig values corresponding to k^2 for the mode's resonant wavenumber.
# The eigenvectors are returned as a 2D array of shape (n_eig, problem_dim), with row i corresponding to the
# modal distributions associated with the i-th eigenvalue.
# """
# M = self.eigenproblem.system_matrices['M']
# S = self.eigenproblem.system_matrices['S']
# solve_mat = S - self.sigma*M
# lu = dolfin.LUSolver(solve_mat)
# lu.parameters["reuse_factorization"] = True
# lu.parameters["report"] = False
# bb = dolfin.Vector(M.size(0))
# xx = dolfin.Vector(M.size(0))
# def sigma_solve(b):
# bb[:] = b
# lu.solve(xx, bb)
# return xx[:]
# M_matvec = lambda x: M*x
#
# #speigs in ARPACK has been removed in scipy 0.9/0.10
# #eigs is now in scipy.sparse.linalg.arpack
# #therefore force M_matvec to have "shape" and "dtype" attributes to comply with "eigs" requirements
# #also perform the sigma_solve function for spectrum shift to sigma
# class RM:
# def __init__(self, M):
# self.M = M
# self.shape = (M.size(0), M.size(1))
# self.dtype = np.dtype('d')
# def matvec(self, x):
# return sigma_solve(self.M*x)
#
# # eigs_w, eigs_v = speigs.ARPACK_gen_eigs(
# # M_matvec, sigma_solve, M.size(0), self.sigma, nev, ncv=ncv)
#
# eigs_w, eigs_v= arpack.eigs(RM(M), k=nev, sigma=self.sigma, which='LM', ncv=ncv)
#
# return eigs_w, eigs_v.T
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | ep = EigenProblem() |
Given the code snippet: <|code_start|>from __future__ import division
sys.path.append('../../')
# Define mesh
# mesh = dol.UnitCube(1,1,1)
# mesh.coordinates()[:] *= [cdims.a,cdims.b,cdims.c]
#mesh_file = 'lee_mittra92_fig6b.xml'
#mesh_file = 'lee_mittra92_fig6c.xml'
mesh_file = '../../examples/albani_bernardi74/mesh/albani_bernardi74_fig2VII.xml'
materials_mesh_file = "%s_physical_region%s" % (os.path.splitext(mesh_file))
mesh = dol.Mesh(mesh_file)
material_mesh_func = dol.MeshFunction('uint', mesh, materials_mesh_file)
materials = {1000:dict(eps_r=16),
1001:dict(eps_r=1)}
order = 3
sigma = 1.5
# Set up eigen problem
ep = EigenProblem()
ep.set_mesh(mesh)
ep.set_basis_order(order)
ep.set_material_regions(materials)
ep.set_region_meshfunction(material_mesh_func)
ep.init_problem()
# Set up eigen problem linear solution
<|code_end|>
, generate the next line using the imports in this file:
import sys
import numpy as N
import os
import dolfin as dol
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import EigenProblem
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import DefaultEigenSolver
from sucemfem.Consts import c0
and context (functions, classes, or occasionally code) from other files:
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class EigenProblem(EMProblem):
# FormCombiner = CombineForms
#
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class DefaultEigenSolver(object):
# def set_eigenproblem(self, eigenproblem):
# """Sets initialised instance of EigenProblem to solve"""
# self.eigenproblem = eigenproblem
#
# def set_sigma(self, sigma):
# """Spectrum shift (sigma) to apply to k^2"""
# self.sigma = sigma
#
# def solve_problem(self, nev, ncv=None):
# """Solve problem and return the eigenvalues and eigenvectors
#
# @param nev: Number of eigenpairs to compute
# @keyword ncv: Number of Arnoldi basisvectors to use.
# (default: 2*nev+1).
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (eigs_w, eigs_v) -- A tupple consisting of the eigenvalues and eigenvectors of the eigensystem.
# The eigenvalues are returned as an array of n_eig values corresponding to k^2 for the mode's resonant wavenumber.
# The eigenvectors are returned as a 2D array of shape (n_eig, problem_dim), with row i corresponding to the
# modal distributions associated with the i-th eigenvalue.
# """
# M = self.eigenproblem.system_matrices['M']
# S = self.eigenproblem.system_matrices['S']
# solve_mat = S - self.sigma*M
# lu = dolfin.LUSolver(solve_mat)
# lu.parameters["reuse_factorization"] = True
# lu.parameters["report"] = False
# bb = dolfin.Vector(M.size(0))
# xx = dolfin.Vector(M.size(0))
# def sigma_solve(b):
# bb[:] = b
# lu.solve(xx, bb)
# return xx[:]
# M_matvec = lambda x: M*x
#
# #speigs in ARPACK has been removed in scipy 0.9/0.10
# #eigs is now in scipy.sparse.linalg.arpack
# #therefore force M_matvec to have "shape" and "dtype" attributes to comply with "eigs" requirements
# #also perform the sigma_solve function for spectrum shift to sigma
# class RM:
# def __init__(self, M):
# self.M = M
# self.shape = (M.size(0), M.size(1))
# self.dtype = np.dtype('d')
# def matvec(self, x):
# return sigma_solve(self.M*x)
#
# # eigs_w, eigs_v = speigs.ARPACK_gen_eigs(
# # M_matvec, sigma_solve, M.size(0), self.sigma, nev, ncv=ncv)
#
# eigs_w, eigs_v= arpack.eigs(RM(M), k=nev, sigma=self.sigma, which='LM', ncv=ncv)
#
# return eigs_w, eigs_v.T
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | es = DefaultEigenSolver() |
Here is a snippet: <|code_start|># mesh = dol.UnitCube(1,1,1)
# mesh.coordinates()[:] *= [cdims.a,cdims.b,cdims.c]
#mesh_file = 'lee_mittra92_fig6b.xml'
#mesh_file = 'lee_mittra92_fig6c.xml'
mesh_file = '../../examples/albani_bernardi74/mesh/albani_bernardi74_fig2VII.xml'
materials_mesh_file = "%s_physical_region%s" % (os.path.splitext(mesh_file))
mesh = dol.Mesh(mesh_file)
material_mesh_func = dol.MeshFunction('uint', mesh, materials_mesh_file)
materials = {1000:dict(eps_r=16),
1001:dict(eps_r=1)}
order = 3
sigma = 1.5
# Set up eigen problem
ep = EigenProblem()
ep.set_mesh(mesh)
ep.set_basis_order(order)
ep.set_material_regions(materials)
ep.set_region_meshfunction(material_mesh_func)
ep.init_problem()
# Set up eigen problem linear solution
es = DefaultEigenSolver()
es.set_eigenproblem(ep)
es.set_sigma(sigma)
eigs_w, eigs_v = es.solve_problem(10)
res = N.array(sorted(eigs_w)[0:10])
print N.sqrt(res)
<|code_end|>
. Write the next line using the current file imports:
import sys
import numpy as N
import os
import dolfin as dol
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import EigenProblem
from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import DefaultEigenSolver
from sucemfem.Consts import c0
and context from other files:
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class EigenProblem(EMProblem):
# FormCombiner = CombineForms
#
# Path: sucemfem/ProblemConfigurations/EMVectorWaveEigenproblem.py
# class DefaultEigenSolver(object):
# def set_eigenproblem(self, eigenproblem):
# """Sets initialised instance of EigenProblem to solve"""
# self.eigenproblem = eigenproblem
#
# def set_sigma(self, sigma):
# """Spectrum shift (sigma) to apply to k^2"""
# self.sigma = sigma
#
# def solve_problem(self, nev, ncv=None):
# """Solve problem and return the eigenvalues and eigenvectors
#
# @param nev: Number of eigenpairs to compute
# @keyword ncv: Number of Arnoldi basisvectors to use.
# (default: 2*nev+1).
#
# @rtype: (C{numpy.array}, C{numpy.array})
# @return: (eigs_w, eigs_v) -- A tupple consisting of the eigenvalues and eigenvectors of the eigensystem.
# The eigenvalues are returned as an array of n_eig values corresponding to k^2 for the mode's resonant wavenumber.
# The eigenvectors are returned as a 2D array of shape (n_eig, problem_dim), with row i corresponding to the
# modal distributions associated with the i-th eigenvalue.
# """
# M = self.eigenproblem.system_matrices['M']
# S = self.eigenproblem.system_matrices['S']
# solve_mat = S - self.sigma*M
# lu = dolfin.LUSolver(solve_mat)
# lu.parameters["reuse_factorization"] = True
# lu.parameters["report"] = False
# bb = dolfin.Vector(M.size(0))
# xx = dolfin.Vector(M.size(0))
# def sigma_solve(b):
# bb[:] = b
# lu.solve(xx, bb)
# return xx[:]
# M_matvec = lambda x: M*x
#
# #speigs in ARPACK has been removed in scipy 0.9/0.10
# #eigs is now in scipy.sparse.linalg.arpack
# #therefore force M_matvec to have "shape" and "dtype" attributes to comply with "eigs" requirements
# #also perform the sigma_solve function for spectrum shift to sigma
# class RM:
# def __init__(self, M):
# self.M = M
# self.shape = (M.size(0), M.size(1))
# self.dtype = np.dtype('d')
# def matvec(self, x):
# return sigma_solve(self.M*x)
#
# # eigs_w, eigs_v = speigs.ARPACK_gen_eigs(
# # M_matvec, sigma_solve, M.size(0), self.sigma, nev, ncv=ncv)
#
# eigs_w, eigs_v= arpack.eigs(RM(M), k=nev, sigma=self.sigma, which='LM', ncv=ncv)
#
# return eigs_w, eigs_v.T
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
, which may include functions, classes, or code. Output only the next line. | print c0*N.sqrt(res)/2/N.pi/1e6 |
Given snippet: <|code_start|># Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
sys.path.append('../../')
#from FenicsCode.Consts import Z0, c0
#from FenicsCode.Utilities.MeshGenerators import get_centred_cube
#import FenicsCode.Utilities.Optimization
#from FenicsCode.PostProcessing import surface_ntff, variational_ntff
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
#FenicsCode.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
#fname = 'data/dofs-2-0.299792458-0.0166551365556-0.0749481145-1000.pickle'
fname = 'data/dofs-2-0.899377374-0.0499654096667-0.6895226534-1000.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pickle
import numpy as N
import dolfin
import sys
import sucemfem.Utilities.Optimization
import pylab
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
which might include code, classes, or functions. Output only the next line. | lam = c0/data['freq'] |
Given the code snippet: <|code_start|># Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
sys.path.append('../../')
#from FenicsCode.Consts import Z0, c0
#from FenicsCode.Utilities.MeshGenerators import get_centred_cube
#import FenicsCode.Utilities.Optimization
#from FenicsCode.PostProcessing import surface_ntff, variational_ntff
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
#FenicsCode.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
#fname = 'data/dofs-2-0.299792458-0.0166551365556-0.0749481145-1000.pickle'
fname = 'data/dofs-2-0.899377374-0.0499654096667-0.6895226534-1000.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
lam = c0/data['freq']
k0 = data['freq']*2*N.pi/c0
<|code_end|>
, generate the next line using the imports in this file:
import pickle
import numpy as N
import dolfin
import sys
import sucemfem.Utilities.Optimization
import pylab
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context (functions, classes, or occasionally code) from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
. Output only the next line. | mesh = get_centred_cube(data['domain_size'], data['max_edge_len']) |
Predict the next line for this snippet: <|code_start|># Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
sys.path.append('../../')
#from FenicsCode.Consts import Z0, c0
#from FenicsCode.Utilities.MeshGenerators import get_centred_cube
#import FenicsCode.Utilities.Optimization
#from FenicsCode.PostProcessing import surface_ntff, variational_ntff
# Enable dolfin's form optimizations
sucemfem.Utilities.Optimization.set_dolfin_optimisation()
#FenicsCode.Utilities.Optimization.set_dolfin_optimisation()
# Near-field of an infintesimal dipole
#fname = 'data/dofs-2-0.299792458-0.0166551365556-0.0749481145-1000.pickle'
fname = 'data/dofs-2-0.899377374-0.0499654096667-0.6895226534-1000.pickle'
theta_deg = N.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = N.zeros(no_ff_pts)
data = pickle.load(open(fname))
lam = c0/data['freq']
k0 = data['freq']*2*N.pi/c0
mesh = get_centred_cube(data['domain_size'], data['max_edge_len'])
V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", data['order'])
#------------------------------
# Calculate using the standard surface integral NTFF
<|code_end|>
with the help of current file imports:
import pickle
import numpy as N
import dolfin
import sys
import sucemfem.Utilities.Optimization
import pylab
from sucemfem.Consts import Z0, c0
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.PostProcessing import surface_ntff, variational_ntff
and context from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/PostProcessing/surface_ntff.py
# class SurfaceNTFFForms(object):
# class NTFF(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def get_N_form(self):
# def get_L_form(self):
# def assemble_N(self):
# def assemble_L(self):
# def set_parms(self, theta, phi, k0):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_frequency(self, frequency):
# def calc_pt(self, theta_deg, phi_deg):
# N = self.get_N_form()
# L = self.get_L_form()
#
# Path: sucemfem/PostProcessing/variational_ntff.py
# class TransformTestingExpression(object):
# class NTFF(object):
# def __init__(self):
# def set_parms(self, rhat, ahat, k0):
# def _set_expr_parms(self, expr, rhat, k0, constfac):
# def get_expression(self):
# def __init__(self, function_space, testing_space=None):
# def set_k0(self, k0):
# def set_frequency(self, frequency):
# def set_dofs(self, dofs):
# def calc_pt(self, theta_deg, phi_deg):
# def calc_pt_E_H(self, theta_deg, phi_deg):
# def calc_ff_func(self, rhat, ahat):
, which may contain function names, class names, or code. Output only the next line. | surf_ntff = surface_ntff.NTFF(V) |
Predict the next line for this snippet: <|code_start|> fo = open(self.mesh_filename)
for l in fo:
bfun = self.find_block_fun(l)
if bfun: bfun(fo)
self.read = True
@uninit_error
def get_mesh_filename(self):
return os.path.basename(self.mesh_filename)
@uninit_error
def get_mesh_dirname(self):
return os.path.dirname(self.mesh_filename)
@uninit_error
def get_tet_nodes(self):
return self.tet_nodes
@uninit_error
def get_tet_property_nos(self):
return self.tet_property_nos
@uninit_error
def get_nodes(self):
return self.nodes
def femmesh_2_dolfin_mesh(femmesh_file):
"""Convert a femmesh file to a dolfin mesh object"""
femmesh_reader = FemmeshReader(femmesh_file)
<|code_end|>
with the help of current file imports:
import numpy as N
import re, os
from sucemfem.Utilities import MeshConverters
and context from other files:
# Path: sucemfem/Utilities/MeshConverters.py
# def listmesh_2_dolfin_mesh(listmesh, reorder=False):
# def dolfin_mesh_2_listmesh(dolfin_mesh):
# def femmesh_reader_2_dolfin_mesh(femmesh_reader, reorder=True):
, which may contain function names, class names, or code. Output only the next line. | return MeshConverters.femmesh_reader_2_dolfin_mesh(femmesh_reader) |
Here is a snippet: <|code_start|>## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
class FillamentSource(object):
"""High level current fillament source representation"""
def __init__(self, function_space):
self.function_space = function_space
def set_source_parameters(self, source_parameters):
"""Set current fillament source paerameters using dict
source_parameters is a dict with keys:
I -- Source current in amperes
endpoints -- 2x3 array with start and end coordinates of the source
"""
self.source_parameters = source_parameters
endpoints = source_parameters['endpoints']
delta = endpoints[1] - endpoints[0]
self.direction = unit_vector(delta)
self.length = vector_length(delta)
def get_current_source(self):
"""get FillamentCurrentSource instance
Each call results in a new instance being instantiated.
"""
<|code_end|>
. Write the next line using the current file imports:
from sucemfem.Sources.fillament_current_source import FillamentCurrentSource
from sucemfem.Utilities.Geometry import unit_vector, vector_length
and context from other files:
# Path: sucemfem/Sources/fillament_current_source.py
# class FillamentCurrentSource(CurrentSource):
# no_integration_points = 100
#
# def __init__(self, *names, **kwargs):
# self._dirty = True
#
# def set_no_integration_points(self, no_integration_points):
# """Set number of integration points to use along the length of
# the fillament"""
# self.no_integration_points = no_integration_points
#
# def set_source_endpoints(self, source_endpoints):
# """Set the current filament endpoints.
#
# @param source_endpoints: 2x3 array with the coordinates of the start
# and end point of the current fillament. The conventional
# current flows from the start point towards the endpoint.
# """
# self.source_endpoints = source_endpoints
# self._dirty = True
#
# def set_value(self, value):
# """Set line current value in Amperes"""
# self.value = value
# self._dirty = True
#
# def _update(self):
# if self._dirty:
# self.source_start, self.source_end = self.source_endpoints
# self.source_delta = self.source_end - self.source_start
# self.vector_value = unit_vector(self.source_delta)*self.value
# self._dirty == False
#
# def get_contribution(self):
# self._update()
# source_len = vector_length(self.source_delta)
# no_pts = self.no_integration_points
# if no_pts == 1:
# intg_pts = [self.source_start + self.source_delta*0.5]
# else:
# intg_pts = self.source_start + self.source_delta*np.linspace(
# 0,1,no_pts)[:, np.newaxis]
#
# contribs = collections.defaultdict(lambda : 0.)
# point_magnitude = self.vector_value*source_len/no_pts
# for pt in intg_pts:
# dnos, vals = calc_pointsource_contrib(
# self.function_space, pt, point_magnitude)
# for dn, v in zip(dnos, vals):
# contribs[dn] = contribs[dn] + v
#
# dofnos = np.array(contribs.keys(), dtype=np.uint)
# rhs_contribs = np.array(contribs.values())
# return dofnos, rhs_contribs
#
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
, which may include functions, classes, or code. Output only the next line. | cs = FillamentCurrentSource() |
Based on the snippet: <|code_start|>## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
class FillamentSource(object):
"""High level current fillament source representation"""
def __init__(self, function_space):
self.function_space = function_space
def set_source_parameters(self, source_parameters):
"""Set current fillament source paerameters using dict
source_parameters is a dict with keys:
I -- Source current in amperes
endpoints -- 2x3 array with start and end coordinates of the source
"""
self.source_parameters = source_parameters
endpoints = source_parameters['endpoints']
delta = endpoints[1] - endpoints[0]
<|code_end|>
, predict the immediate next line with the help of imports:
from sucemfem.Sources.fillament_current_source import FillamentCurrentSource
from sucemfem.Utilities.Geometry import unit_vector, vector_length
and context (classes, functions, sometimes code) from other files:
# Path: sucemfem/Sources/fillament_current_source.py
# class FillamentCurrentSource(CurrentSource):
# no_integration_points = 100
#
# def __init__(self, *names, **kwargs):
# self._dirty = True
#
# def set_no_integration_points(self, no_integration_points):
# """Set number of integration points to use along the length of
# the fillament"""
# self.no_integration_points = no_integration_points
#
# def set_source_endpoints(self, source_endpoints):
# """Set the current filament endpoints.
#
# @param source_endpoints: 2x3 array with the coordinates of the start
# and end point of the current fillament. The conventional
# current flows from the start point towards the endpoint.
# """
# self.source_endpoints = source_endpoints
# self._dirty = True
#
# def set_value(self, value):
# """Set line current value in Amperes"""
# self.value = value
# self._dirty = True
#
# def _update(self):
# if self._dirty:
# self.source_start, self.source_end = self.source_endpoints
# self.source_delta = self.source_end - self.source_start
# self.vector_value = unit_vector(self.source_delta)*self.value
# self._dirty == False
#
# def get_contribution(self):
# self._update()
# source_len = vector_length(self.source_delta)
# no_pts = self.no_integration_points
# if no_pts == 1:
# intg_pts = [self.source_start + self.source_delta*0.5]
# else:
# intg_pts = self.source_start + self.source_delta*np.linspace(
# 0,1,no_pts)[:, np.newaxis]
#
# contribs = collections.defaultdict(lambda : 0.)
# point_magnitude = self.vector_value*source_len/no_pts
# for pt in intg_pts:
# dnos, vals = calc_pointsource_contrib(
# self.function_space, pt, point_magnitude)
# for dn, v in zip(dnos, vals):
# contribs[dn] = contribs[dn] + v
#
# dofnos = np.array(contribs.keys(), dtype=np.uint)
# rhs_contribs = np.array(contribs.values())
# return dofnos, rhs_contribs
#
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
. Output only the next line. | self.direction = unit_vector(delta) |
Predict the next line after this snippet: <|code_start|>##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
class FillamentSource(object):
"""High level current fillament source representation"""
def __init__(self, function_space):
self.function_space = function_space
def set_source_parameters(self, source_parameters):
"""Set current fillament source paerameters using dict
source_parameters is a dict with keys:
I -- Source current in amperes
endpoints -- 2x3 array with start and end coordinates of the source
"""
self.source_parameters = source_parameters
endpoints = source_parameters['endpoints']
delta = endpoints[1] - endpoints[0]
self.direction = unit_vector(delta)
<|code_end|>
using the current file's imports:
from sucemfem.Sources.fillament_current_source import FillamentCurrentSource
from sucemfem.Utilities.Geometry import unit_vector, vector_length
and any relevant context from other files:
# Path: sucemfem/Sources/fillament_current_source.py
# class FillamentCurrentSource(CurrentSource):
# no_integration_points = 100
#
# def __init__(self, *names, **kwargs):
# self._dirty = True
#
# def set_no_integration_points(self, no_integration_points):
# """Set number of integration points to use along the length of
# the fillament"""
# self.no_integration_points = no_integration_points
#
# def set_source_endpoints(self, source_endpoints):
# """Set the current filament endpoints.
#
# @param source_endpoints: 2x3 array with the coordinates of the start
# and end point of the current fillament. The conventional
# current flows from the start point towards the endpoint.
# """
# self.source_endpoints = source_endpoints
# self._dirty = True
#
# def set_value(self, value):
# """Set line current value in Amperes"""
# self.value = value
# self._dirty = True
#
# def _update(self):
# if self._dirty:
# self.source_start, self.source_end = self.source_endpoints
# self.source_delta = self.source_end - self.source_start
# self.vector_value = unit_vector(self.source_delta)*self.value
# self._dirty == False
#
# def get_contribution(self):
# self._update()
# source_len = vector_length(self.source_delta)
# no_pts = self.no_integration_points
# if no_pts == 1:
# intg_pts = [self.source_start + self.source_delta*0.5]
# else:
# intg_pts = self.source_start + self.source_delta*np.linspace(
# 0,1,no_pts)[:, np.newaxis]
#
# contribs = collections.defaultdict(lambda : 0.)
# point_magnitude = self.vector_value*source_len/no_pts
# for pt in intg_pts:
# dnos, vals = calc_pointsource_contrib(
# self.function_space, pt, point_magnitude)
# for dn, v in zip(dnos, vals):
# contribs[dn] = contribs[dn] + v
#
# dofnos = np.array(contribs.keys(), dtype=np.uint)
# rhs_contribs = np.array(contribs.values())
# return dofnos, rhs_contribs
#
# Path: sucemfem/Utilities/Geometry.py
# def unit_vector(vec):
# """Calculate a unit vector of vec"""
# return vec/vector_length(vec)
#
# def vector_length(vec):
# """Calculate the length of a vector"""
# return np.sqrt(np.sum(vec**2))
. Output only the next line. | self.length = vector_length(delta) |
Next line prediction: <|code_start|>## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
# Evan Lezar <mail@evanlezar.com>
"""this is a set of test cases for the testing of the matrix IO routines in FenicsCode/Utilities"""
sys.path.insert(0, '../')
del sys.path[0]
data_path = 'data/MatrixIO'
class TestMatrixIO ( unittest.TestCase ):
def test_save_scipy_matrix ( self ):
N = 1000;
A = scipy.sparse.rand ( N, N, format='csr' )
save_scipy_matrix_as_mat ( data_path, 'A', A )
def __save_and_load_test (self, name, A ):
save_scipy_matrix_as_mat ( data_path, name, A )
<|code_end|>
. Use current file imports:
(import numpy as np
import sys
import unittest
import scipy.sparse
import scipy.sparse
import scipy.sparse
from sucemfem.Utilities.MatrixIO import (
load_scipy_matrix_from_mat,
save_scipy_matrix_as_mat,
))
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Utilities/MatrixIO.py
# def load_scipy_matrix_from_mat ( path, name ):
# """
# Load a scipy sparse matrix from a .mat file.
#
# @param path: the folder in which the matrix is saved
# @param name: the filename of the matrix
# """
# import scipy.io
# import scipy.sparse
#
# filename = os.path.join ( path, name)
#
# if not os.path.exists( filename + '.mat' ):
# return None
#
# data = scipy.io.loadmat ( filename )[name]
#
# if type(data) is np.ndarray:
# matrix = data
# else:
# matrix = data.tocsr ()
#
# return matrix
#
# def save_scipy_matrix_as_mat ( path, name, matrix ):
# """
# Save a scipy sparse matrix as a .mat file.
#
# @param path: the folder in which the matrix is to be saved
# @param name: the filename of the matrix
# @param matrix: the scipy matrix to save
# """
# import scipy.io
# if not check_path ( path ):
# return False
#
# scipy.io.savemat ( os.path.join(path, name), {name: matrix }, oned_as='column' )
#
# return True
. Output only the next line. | A_load = load_scipy_matrix_from_mat ( data_path, name ) |
Continue the code snippet: <|code_start|>## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
# Evan Lezar <mail@evanlezar.com>
"""this is a set of test cases for the testing of the matrix IO routines in FenicsCode/Utilities"""
sys.path.insert(0, '../')
del sys.path[0]
data_path = 'data/MatrixIO'
class TestMatrixIO ( unittest.TestCase ):
def test_save_scipy_matrix ( self ):
N = 1000;
A = scipy.sparse.rand ( N, N, format='csr' )
<|code_end|>
. Use current file imports:
import numpy as np
import sys
import unittest
import scipy.sparse
import scipy.sparse
import scipy.sparse
from sucemfem.Utilities.MatrixIO import (
load_scipy_matrix_from_mat,
save_scipy_matrix_as_mat,
)
and context (classes, functions, or code) from other files:
# Path: sucemfem/Utilities/MatrixIO.py
# def load_scipy_matrix_from_mat ( path, name ):
# """
# Load a scipy sparse matrix from a .mat file.
#
# @param path: the folder in which the matrix is saved
# @param name: the filename of the matrix
# """
# import scipy.io
# import scipy.sparse
#
# filename = os.path.join ( path, name)
#
# if not os.path.exists( filename + '.mat' ):
# return None
#
# data = scipy.io.loadmat ( filename )[name]
#
# if type(data) is np.ndarray:
# matrix = data
# else:
# matrix = data.tocsr ()
#
# return matrix
#
# def save_scipy_matrix_as_mat ( path, name, matrix ):
# """
# Save a scipy sparse matrix as a .mat file.
#
# @param path: the folder in which the matrix is to be saved
# @param name: the filename of the matrix
# @param matrix: the scipy matrix to save
# """
# import scipy.io
# if not check_path ( path ):
# return False
#
# scipy.io.savemat ( os.path.join(path, name), {name: matrix }, oned_as='column' )
#
# return True
. Output only the next line. | save_scipy_matrix_as_mat ( data_path, 'A', A ) |
Using the snippet: <|code_start|> """Set function space on which the essential boundary condition is to be applied.
@param function_space: a dolfin function space object
"""
self.function_space = function_space
def get_essential_application_func(self, function_space=None):
"""Return an essential boundary condition application function.
@keyword function_space: An optional dolfin function space to use for
constructing the essential boundary condition. If None is
specified, the function space stored in self is used.
@return: A function that applies the essential
component of the boundary condition to the system matrix
equation with the matrix A on LHS and the optional vector
b on the RHS.
"""
return lambda x: None
def get_linear_form(self, test_function=None):
"""Return boundary condition's linear form contribution as a dolfin form
@param test_function: An optional dolfin testing function to use in
the form construction. If None is specified, the testing
function stored in self is used
@return: a dolfin linear form. The contribution of the
linear form should be added to the form used to calculate
the RHS of the system matrix equation that is eventually
solved.
"""
<|code_end|>
, determine the next line of code. You have imports:
from sucemfem import Forms
and context (class names, function names, or code) available:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
. Output only the next line. | return Forms.NullForm() |
Continue the code snippet: <|code_start|>
sys.path.insert(0, '../../../')
sucemfem.Utilities.Optimization.set_dolfin_optimisation(True)
## Postprocessing requests
theta_deg = np.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = np.zeros(no_ff_pts)
## Problem parameters
freq = 1.0e+9 # Frequency
lam = c0/freq
l = lam/4 # Dipole length
# l = 2.3*lam # Dipole length
I = 1.0 # Dipole current
source_direction = np.array([0,0,1.]) # Source orientation
source_centre = np.array([0,0,0.]) # Position of the source
source_endpoints = np.array(
[-source_direction*l/2, source_direction*l/2]) + source_centre
## Discretisation settings
order = 2
domain_size = np.array([lam]*3)/2
max_edge_len = lam/3
<|code_end|>
. Use current file imports:
import dolfin
import numpy as np
import pickle
import sys
import sucemfem.Utilities.Optimization
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.Consts import c0
from sucemfem.Sources.fillament_current_source import FillamentCurrentSource
and context (classes, functions, or code) from other files:
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Sources/fillament_current_source.py
# class FillamentCurrentSource(CurrentSource):
# no_integration_points = 100
#
# def __init__(self, *names, **kwargs):
# self._dirty = True
#
# def set_no_integration_points(self, no_integration_points):
# """Set number of integration points to use along the length of
# the fillament"""
# self.no_integration_points = no_integration_points
#
# def set_source_endpoints(self, source_endpoints):
# """Set the current filament endpoints.
#
# @param source_endpoints: 2x3 array with the coordinates of the start
# and end point of the current fillament. The conventional
# current flows from the start point towards the endpoint.
# """
# self.source_endpoints = source_endpoints
# self._dirty = True
#
# def set_value(self, value):
# """Set line current value in Amperes"""
# self.value = value
# self._dirty = True
#
# def _update(self):
# if self._dirty:
# self.source_start, self.source_end = self.source_endpoints
# self.source_delta = self.source_end - self.source_start
# self.vector_value = unit_vector(self.source_delta)*self.value
# self._dirty == False
#
# def get_contribution(self):
# self._update()
# source_len = vector_length(self.source_delta)
# no_pts = self.no_integration_points
# if no_pts == 1:
# intg_pts = [self.source_start + self.source_delta*0.5]
# else:
# intg_pts = self.source_start + self.source_delta*np.linspace(
# 0,1,no_pts)[:, np.newaxis]
#
# contribs = collections.defaultdict(lambda : 0.)
# point_magnitude = self.vector_value*source_len/no_pts
# for pt in intg_pts:
# dnos, vals = calc_pointsource_contrib(
# self.function_space, pt, point_magnitude)
# for dn, v in zip(dnos, vals):
# contribs[dn] = contribs[dn] + v
#
# dofnos = np.array(contribs.keys(), dtype=np.uint)
# rhs_contribs = np.array(contribs.values())
# return dofnos, rhs_contribs
. Output only the next line. | mesh = get_centred_cube(domain_size, max_edge_len) |
Predict the next line for this snippet: <|code_start|>##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
"""Generate data used as reference values for the fillament source test"""
sys.path.insert(0, '../../../')
sucemfem.Utilities.Optimization.set_dolfin_optimisation(True)
## Postprocessing requests
theta_deg = np.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = np.zeros(no_ff_pts)
## Problem parameters
freq = 1.0e+9 # Frequency
<|code_end|>
with the help of current file imports:
import dolfin
import numpy as np
import pickle
import sys
import sucemfem.Utilities.Optimization
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.Consts import c0
from sucemfem.Sources.fillament_current_source import FillamentCurrentSource
and context from other files:
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Sources/fillament_current_source.py
# class FillamentCurrentSource(CurrentSource):
# no_integration_points = 100
#
# def __init__(self, *names, **kwargs):
# self._dirty = True
#
# def set_no_integration_points(self, no_integration_points):
# """Set number of integration points to use along the length of
# the fillament"""
# self.no_integration_points = no_integration_points
#
# def set_source_endpoints(self, source_endpoints):
# """Set the current filament endpoints.
#
# @param source_endpoints: 2x3 array with the coordinates of the start
# and end point of the current fillament. The conventional
# current flows from the start point towards the endpoint.
# """
# self.source_endpoints = source_endpoints
# self._dirty = True
#
# def set_value(self, value):
# """Set line current value in Amperes"""
# self.value = value
# self._dirty = True
#
# def _update(self):
# if self._dirty:
# self.source_start, self.source_end = self.source_endpoints
# self.source_delta = self.source_end - self.source_start
# self.vector_value = unit_vector(self.source_delta)*self.value
# self._dirty == False
#
# def get_contribution(self):
# self._update()
# source_len = vector_length(self.source_delta)
# no_pts = self.no_integration_points
# if no_pts == 1:
# intg_pts = [self.source_start + self.source_delta*0.5]
# else:
# intg_pts = self.source_start + self.source_delta*np.linspace(
# 0,1,no_pts)[:, np.newaxis]
#
# contribs = collections.defaultdict(lambda : 0.)
# point_magnitude = self.vector_value*source_len/no_pts
# for pt in intg_pts:
# dnos, vals = calc_pointsource_contrib(
# self.function_space, pt, point_magnitude)
# for dn, v in zip(dnos, vals):
# contribs[dn] = contribs[dn] + v
#
# dofnos = np.array(contribs.keys(), dtype=np.uint)
# rhs_contribs = np.array(contribs.values())
# return dofnos, rhs_contribs
, which may contain function names, class names, or code. Output only the next line. | lam = c0/freq |
Next line prediction: <|code_start|>
sucemfem.Utilities.Optimization.set_dolfin_optimisation(True)
## Postprocessing requests
theta_deg = np.linspace(0, 180, 181)
no_ff_pts = len(theta_deg)
phi_deg = np.zeros(no_ff_pts)
## Problem parameters
freq = 1.0e+9 # Frequency
lam = c0/freq
l = lam/4 # Dipole length
# l = 2.3*lam # Dipole length
I = 1.0 # Dipole current
source_direction = np.array([0,0,1.]) # Source orientation
source_centre = np.array([0,0,0.]) # Position of the source
source_endpoints = np.array(
[-source_direction*l/2, source_direction*l/2]) + source_centre
## Discretisation settings
order = 2
domain_size = np.array([lam]*3)/2
max_edge_len = lam/3
mesh = get_centred_cube(domain_size, max_edge_len)
## Implementation
V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", order)
<|code_end|>
. Use current file imports:
(import dolfin
import numpy as np
import pickle
import sys
import sucemfem.Utilities.Optimization
from sucemfem.Utilities.MeshGenerators import get_centred_cube
from sucemfem.Consts import c0
from sucemfem.Sources.fillament_current_source import FillamentCurrentSource)
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Utilities/MeshGenerators.py
# def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None):
# """ Generate a cube mesh centred arount [0,0,0]
#
# optionally translates mesh slightly such that
# centred_element_coordinate is at the centre of an element.
# """
# domain_subdivisions = N.array(N.ceil(N.sqrt(2)*domain_size/max_edge_len), N.uint)
# mesh = dolfin.UnitCube(*domain_subdivisions)
# # Transform mesh to correct dimensions
# mesh.coordinates()[:] *= domain_size
# mesh.coordinates()[:] -= domain_size/2
# if centred_element_coordinate is not None:
# ## Translate mesh slightly so that source coordinate lies at
# ## centroid of an element
# centred_element_point = dolfin.Point(*centred_element_coordinate)
# # source_elnos = mesh.all_intersected_entities(centred_element_point)
# source_elnos = mesh.intersected_cells(centred_element_point)
# closest_elno = source_elnos[(N.argmin(
# [centred_element_point.distance(dolfin.Cell(mesh, i).midpoint())
# for i in source_elnos]))]
# centre_pt = dolfin.Cell(mesh, closest_elno).midpoint()
# centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()])
# # The mesh intersect operator caches certain data
# # structures. We need to clear them if the mesh coordinates
# # are changed after calling any mesh intersection methods.
# mesh.intersection_operator().clear()
# mesh.coordinates()[:] -= centre_coord
# return mesh
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Sources/fillament_current_source.py
# class FillamentCurrentSource(CurrentSource):
# no_integration_points = 100
#
# def __init__(self, *names, **kwargs):
# self._dirty = True
#
# def set_no_integration_points(self, no_integration_points):
# """Set number of integration points to use along the length of
# the fillament"""
# self.no_integration_points = no_integration_points
#
# def set_source_endpoints(self, source_endpoints):
# """Set the current filament endpoints.
#
# @param source_endpoints: 2x3 array with the coordinates of the start
# and end point of the current fillament. The conventional
# current flows from the start point towards the endpoint.
# """
# self.source_endpoints = source_endpoints
# self._dirty = True
#
# def set_value(self, value):
# """Set line current value in Amperes"""
# self.value = value
# self._dirty = True
#
# def _update(self):
# if self._dirty:
# self.source_start, self.source_end = self.source_endpoints
# self.source_delta = self.source_end - self.source_start
# self.vector_value = unit_vector(self.source_delta)*self.value
# self._dirty == False
#
# def get_contribution(self):
# self._update()
# source_len = vector_length(self.source_delta)
# no_pts = self.no_integration_points
# if no_pts == 1:
# intg_pts = [self.source_start + self.source_delta*0.5]
# else:
# intg_pts = self.source_start + self.source_delta*np.linspace(
# 0,1,no_pts)[:, np.newaxis]
#
# contribs = collections.defaultdict(lambda : 0.)
# point_magnitude = self.vector_value*source_len/no_pts
# for pt in intg_pts:
# dnos, vals = calc_pointsource_contrib(
# self.function_space, pt, point_magnitude)
# for dn, v in zip(dnos, vals):
# contribs[dn] = contribs[dn] + v
#
# dofnos = np.array(contribs.keys(), dtype=np.uint)
# rhs_contribs = np.array(contribs.values())
# return dofnos, rhs_contribs
. Output only the next line. | dipole_source = FillamentCurrentSource() |
Predict the next line after this snippet: <|code_start|>## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
# Evan Lezar <mail@evanlezar.com>
"""this is a set of test cases for the testing of the linear algebra solvers in FenicsCode/Utilities"""
sys.path.insert(0, '../')
del sys.path[0]
class TestSparseSolver ( unittest.TestCase ):
def test_sparse_identity ( self ):
N = 1000;
A = scipy.sparse.eye ( N, N )
b = np.random.rand ( N )
try:
<|code_end|>
using the current file's imports:
import sys
import unittest
import numpy as np
import scipy.sparse
from sucemfem.Utilities.LinalgSolvers import solve_sparse_system, calculate_residual
and any relevant context from other files:
# Path: sucemfem/Utilities/LinalgSolvers.py
# def solve_sparse_system ( A, b, preconditioner_type='ilu' ):
# """
# This function solves the sparse linear system Ax = b for A a scipy sparse matrix, and b a numpy or scipy array
#
# By default an incomplete LU preconditioner is used with the bicgstab iterative solver
#
# @param A: a square matrix
# @param b: the RHS vector
# @param preconditioner_type: Preconditioner type string
# """
#
# solver = BiCGStabSolver ( A, preconditioner_type )
# # solver = BiCGStabSolver ( A ) #removed preconditioner -> 2D Waveguide works!
# x = solver.solve(b)
# return x
#
# def calculate_residual ( A, x, b ):
# """
# Calculate the residual of the system Ax = b
#
# @param A: a matrix
# @param x: a vector
# @param b: a vector
# """
# return np.linalg.norm( A*x - b.reshape(x.shape) )
. Output only the next line. | x = solve_sparse_system ( A, b ) |
Next line prediction: <|code_start|>## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
# Evan Lezar <mail@evanlezar.com>
"""this is a set of test cases for the testing of the linear algebra solvers in FenicsCode/Utilities"""
sys.path.insert(0, '../')
del sys.path[0]
class TestSparseSolver ( unittest.TestCase ):
def test_sparse_identity ( self ):
N = 1000;
A = scipy.sparse.eye ( N, N )
b = np.random.rand ( N )
try:
x = solve_sparse_system ( A, b )
except AttributeError:
# Deal with older scipy versions that do not have spilu module
x = solve_sparse_system ( A, b, preconditioner_type='diagonal')
np.testing.assert_array_equal( b, x )
class TestOther ( unittest.TestCase ):
def _call_function (self, A, x, b ):
print b.shape
print x.shape
<|code_end|>
. Use current file imports:
(import sys
import unittest
import numpy as np
import scipy.sparse
from sucemfem.Utilities.LinalgSolvers import solve_sparse_system, calculate_residual)
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Utilities/LinalgSolvers.py
# def solve_sparse_system ( A, b, preconditioner_type='ilu' ):
# """
# This function solves the sparse linear system Ax = b for A a scipy sparse matrix, and b a numpy or scipy array
#
# By default an incomplete LU preconditioner is used with the bicgstab iterative solver
#
# @param A: a square matrix
# @param b: the RHS vector
# @param preconditioner_type: Preconditioner type string
# """
#
# solver = BiCGStabSolver ( A, preconditioner_type )
# # solver = BiCGStabSolver ( A ) #removed preconditioner -> 2D Waveguide works!
# x = solver.solve(b)
# return x
#
# def calculate_residual ( A, x, b ):
# """
# Calculate the residual of the system Ax = b
#
# @param A: a matrix
# @param x: a vector
# @param b: a vector
# """
# return np.linalg.norm( A*x - b.reshape(x.shape) )
. Output only the next line. | assert ( calculate_residual ( A, x, b ) == 0 ) |
Predict the next line for this snippet: <|code_start|>from __future__ import division
mpath = '../../'
sys.path.append(mpath)
#sys.path.remove(mpath)
fname = 'patch_o-2_gmres_Z.pickle'
res = pickle.load(open(fname))
Z0 = 50.
Z = res['Zs']
freqs = res['freqs']
<|code_end|>
with the help of current file imports:
import numpy as np
import pickle
import pylab
import sys
from sucemfem.PostProcessing.circuit import S11
and context from other files:
# Path: sucemfem/PostProcessing/circuit.py
# def S11(Zl, Z0):
# """Calculate reflection coeficient of load
#
# @param Zl: Load impedance
# @param Z0: Characteristic impedance
# """
# Zl = np.asarray(Zl)
# return (Zl - Z0)/(Zl + Z0)
, which may contain function names, class names, or code. Output only the next line. | S11 = S11(Z, Z0) |
Given the following code snippet before the placeholder: <|code_start|># Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
sys.path.append('../../')
# Test for PETSc and SLEPc
if not dol.has_la_backend("PETSc"):
print "DOLFIN has not been configured with PETSc. Exiting."
exit()
if not dol.has_slepc():
print "DOLFIN has not been configured with SLEPc. Exiting."
exit()
# class CavityDims(object): pass
# cdims = CavityDims()
# cdims.a, cdims.b, cdims.c = 29,23,19
# Define mesh
# mesh = dol.UnitCube(1,1,1)
# mesh.coordinates()[:] *= [cdims.a,cdims.b,cdims.c]
#mesh_file = 'lee_mittra92_fig6b.xml'
#mesh_file = 'lee_mittra92_fig6c.xml'
mesh_file = '../examples/albani_bernardi74/mesh/albani_bernardi74_fig2VII.xml'
materials_mesh_file = "%s_physical_region%s" % (os.path.splitext(mesh_file))
mesh = dol.Mesh(mesh_file)
<|code_end|>
, predict the next line using imports from the current file:
import sys
import numpy as N
import os
import dolfin as dol
import postproc_eigres
from dolfin import dot, curl, inner, dx
from scipy.sparse.linalg.eigen.arpack import speigs
from sucemfem.Consts import eps0, mu0, c0
from material_properties import MaterialProperties
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | materials = {1000:MaterialProperties(eps_r=16/eps0), |
Given the following code snippet before the placeholder: <|code_start|>lu = dol.LUSolver(smat)
lu.parameters["reuse_factorization"] = True
lu.parameters["report"] = False
bb = dol.Vector(M.size(0))
xx = dol.Vector(M.size(0))
def sigma_solve(b):
bb[:] = b
lu.solve(xx, bb)
return xx[:]
M_matvec = lambda x: M*x
arpack_eigs,arpack_v = speigs.ARPACK_gen_eigs(M_matvec, sigma_solve, M.size(0), sigma, 51, ncv=91)
# Create eigensolver
# esolver = dol.SLEPcEigenSolver(S,M)
# esolver.parameters["spectrum"] = "smallest real"
# esolver.parameters["solver"] = "arnoldi"
# esolver.parameters["spectral_shift"] = sigma
# esolver.parameters["spectral_transform"] = "shift-and-invert"
# esolver.solve()
# eigs = [esolver.get_eigenvalue(i)[0] for i in range(4)]
# filtered_eigs = []
# for i in range(S.size(0)):
# ev_r, ev_i = esolver.get_eigenvalue(i)
# if ev_r > 0.001:
# filtered_eigs.append(ev_r)
res = N.array(sorted(arpack_eigs)[0:10])
print N.sqrt(res)
<|code_end|>
, predict the next line using imports from the current file:
import sys
import numpy as N
import os
import dolfin as dol
import postproc_eigres
from dolfin import dot, curl, inner, dx
from scipy.sparse.linalg.eigen.arpack import speigs
from sucemfem.Consts import eps0, mu0, c0
from material_properties import MaterialProperties
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | print c0*N.sqrt(res)/2/N.pi/1e6 |
Here is a snippet: <|code_start|>##
## This file is part of SUCEM.
##
## SUCEM is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test
class test_SurfaceFlux(unittest.TestCase):
data_dir = 'data'
test_data_file = 'power_flux_reference_dofs_f-1000000000.000000_o-2_s-0.074948_l-0.100000_h-0.166667.pickle'
def setUp(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import os
import pickle
import numpy as np
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Consts import c0
from sucemfem.PostProcessing import power_flux
and context from other files:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/PostProcessing/power_flux.py
# class SurfaceFlux(object):
# class VariationalSurfaceFlux(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_k0(self,k0):
# def _get_mur_function(self):
# def set_mur_function(self, mur_function):
# def _get_form(self):
# def calc_flux(self):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_k0(self,k0):
# def set_epsr_function(self, epsr_function):
# def set_mur_function(self, mur_function):
# def calc_flux(self):
# def _get_mur_function(self):
# def _get_epsr_function(self):
, which may include functions, classes, or code. Output only the next line. | data_dir = Paths.get_module_path_filename(self.data_dir, __file__) |
Given the following code snippet before the placeholder: <|code_start|>##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test
class test_SurfaceFlux(unittest.TestCase):
data_dir = 'data'
test_data_file = 'power_flux_reference_dofs_f-1000000000.000000_o-2_s-0.074948_l-0.100000_h-0.166667.pickle'
def setUp(self):
data_dir = Paths.get_module_path_filename(self.data_dir, __file__)
data_file = open(os.path.join(data_dir, self.test_data_file))
data = self.data = pickle.load(data_file)
self.mesh = dolfin.Mesh(os.path.join(data_dir, data['meshfile']))
self.discretisation_order = data['order']
self.function_space = dolfin.FunctionSpace(
self.mesh, "Nedelec 1st kind H(curl)", self.discretisation_order)
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import os
import pickle
import numpy as np
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Consts import c0
from sucemfem.PostProcessing import power_flux
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/PostProcessing/power_flux.py
# class SurfaceFlux(object):
# class VariationalSurfaceFlux(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_k0(self,k0):
# def _get_mur_function(self):
# def set_mur_function(self, mur_function):
# def _get_form(self):
# def calc_flux(self):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_k0(self,k0):
# def set_epsr_function(self, epsr_function):
# def set_mur_function(self, mur_function):
# def calc_flux(self):
# def _get_mur_function(self):
# def _get_epsr_function(self):
. Output only the next line. | self.k0 = 2*np.pi*data['freq']/c0 |
Next line prediction: <|code_start|>## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test
class test_SurfaceFlux(unittest.TestCase):
data_dir = 'data'
test_data_file = 'power_flux_reference_dofs_f-1000000000.000000_o-2_s-0.074948_l-0.100000_h-0.166667.pickle'
def setUp(self):
data_dir = Paths.get_module_path_filename(self.data_dir, __file__)
data_file = open(os.path.join(data_dir, self.test_data_file))
data = self.data = pickle.load(data_file)
self.mesh = dolfin.Mesh(os.path.join(data_dir, data['meshfile']))
self.discretisation_order = data['order']
self.function_space = dolfin.FunctionSpace(
self.mesh, "Nedelec 1st kind H(curl)", self.discretisation_order)
self.k0 = 2*np.pi*data['freq']/c0
<|code_end|>
. Use current file imports:
(import unittest
import os
import pickle
import numpy as np
import dolfin
from sucemfem.Testing import Paths
from sucemfem.Consts import c0
from sucemfem.PostProcessing import power_flux)
and context including class names, function names, or small code snippets from other files:
# Path: sucemfem/Testing/Paths.py
# def get_module_path(modfile):
# def get_module_path_filename(filename, __file__):
# def get_module_path_file(filename, __file__, mode='r'):
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/PostProcessing/power_flux.py
# class SurfaceFlux(object):
# class VariationalSurfaceFlux(object):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_k0(self,k0):
# def _get_mur_function(self):
# def set_mur_function(self, mur_function):
# def _get_form(self):
# def calc_flux(self):
# def __init__(self, function_space):
# def set_dofs(self, dofs):
# def set_k0(self,k0):
# def set_epsr_function(self, epsr_function):
# def set_mur_function(self, mur_function):
# def calc_flux(self):
# def _get_mur_function(self):
# def _get_epsr_function(self):
. Output only the next line. | self.DUT = power_flux.SurfaceFlux(self.function_space) |
Given snippet: <|code_start|>##
## SUCEM is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
omega, mu, L, beta, r, theta = sp.symbols(
'omega mu L beta r theta')
I0 = sp.Symbol('I0')
E_theta = 1j*omega*mu*I0*L*exp(-1j*beta*r)/(4*pi*r)*sin(theta)* \
sin((beta*L/2)*cos(theta))/((beta*L/2)*cos(theta))
def eval_E_theta(freq, L_val, I_val, theta_val, r_val=1):
return complex(E_theta.evalf(subs={
omega:2*pi*freq,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sympy as sp
import sys
import numpy as np
import pylab
from sympy import sin, cos, exp, pi
from sucemfem.Consts import mu0, c0
and context:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
which might include code, classes, or functions. Output only the next line. | mu:mu0, |
Predict the next line after this snippet: <|code_start|>## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
from __future__ import division
omega, mu, L, beta, r, theta = sp.symbols(
'omega mu L beta r theta')
I0 = sp.Symbol('I0')
E_theta = 1j*omega*mu*I0*L*exp(-1j*beta*r)/(4*pi*r)*sin(theta)* \
sin((beta*L/2)*cos(theta))/((beta*L/2)*cos(theta))
def eval_E_theta(freq, L_val, I_val, theta_val, r_val=1):
return complex(E_theta.evalf(subs={
omega:2*pi*freq,
mu:mu0,
I0:I_val,
L:L_val,
<|code_end|>
using the current file's imports:
import sympy as sp
import sys
import numpy as np
import pylab
from sympy import sin, cos, exp, pi
from sucemfem.Consts import mu0, c0
and any relevant context from other files:
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
. Output only the next line. | beta:2*pi*freq/c0, |
Given the code snippet: <|code_start|> return dict(M=m, S=s, S_0=ABC_form)
class DrivenProblemABC(EMProblem):
"""Set up driven problem, potentially terminated by an ABC.
Assumes lossless, frequency independent materials, and that the
boundary bilinear form is:
dot(cross(n, u), cross(n, v))
where n is a face normal and u,v are the trial and testing
functions. All forms are assumed to be real valued. They real
forms will be combined into a complex system matrix of the form
A = S - k0**2*M + 1j*k_0*S_0
where S, M are stiffness and mass matrices and k0 is the
freespace wave-number
"""
FormCombiner = CombineForms
def set_sources(self, sources):
self.sources = sources
def set_frequency(self, frequency):
"""Set simulation frequency in Hz"""
self.frequency = frequency
def get_LHS_matrix(self):
<|code_end|>
, generate the next line using the imports in this file:
import numpy as N
import dolfin
from sucemfem import Forms
from sucemfem import SystemMatrices
from sucemfem.Consts import c0, Z0
from sucemfem.Utilities.Converters import dolfin_ublassparse_to_scipy_csr
from EMProblem import EMProblem
and context (functions, classes, or occasionally code) from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/Converters.py
# def dolfin_ublassparse_to_scipy_csr ( A, dtype=None, imagify=False ):
# """
# convert a DOLFIN uBLASSparseMatrix to a scipy.sparse.csr_matrix()
#
# @param A: a DOLFIN uBLASSparseMatrix
# @param dtype: the numpy data type to use to store the matrix
# @param imagify: multiply the original matrix data by 1j
# """
# import scipy.sparse
# # get the sparse data from the input matrix
# (row,col,data) = A.data() # get sparse data
# col = np.intc(col)
# row = np.intc(row)
# n = A.size(0)
# if imagify: data = data*1j
# A_sp = scipy.sparse.csr_matrix( (data,col,row), shape=(n,n), dtype=dtype)
#
# return A_sp
. Output only the next line. | k0 = 2*N.pi*self.frequency/c0 |
Given the following code snippet before the placeholder: <|code_start|> where n is a face normal and u,v are the trial and testing
functions. All forms are assumed to be real valued. They real
forms will be combined into a complex system matrix of the form
A = S - k0**2*M + 1j*k_0*S_0
where S, M are stiffness and mass matrices and k0 is the
freespace wave-number
"""
FormCombiner = CombineForms
def set_sources(self, sources):
self.sources = sources
def set_frequency(self, frequency):
"""Set simulation frequency in Hz"""
self.frequency = frequency
def get_LHS_matrix(self):
k0 = 2*N.pi*self.frequency/c0
M = dolfin_ublassparse_to_scipy_csr(self.system_matrices['M'])
S = dolfin_ublassparse_to_scipy_csr(self.system_matrices['S'])
S_0 = dolfin_ublassparse_to_scipy_csr(self.system_matrices['S_0'])
return S - k0**2*M + 1j*k0*S_0
def get_RHS(self):
RHS = N.zeros(self.get_global_dimension(), N.complex128)
dofnos, contribs = self._get_RHS_contributions()
k0 = 2*N.pi*self.frequency/c0
<|code_end|>
, predict the next line using imports from the current file:
import numpy as N
import dolfin
from sucemfem import Forms
from sucemfem import SystemMatrices
from sucemfem.Consts import c0, Z0
from sucemfem.Utilities.Converters import dolfin_ublassparse_to_scipy_csr
from EMProblem import EMProblem
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/Converters.py
# def dolfin_ublassparse_to_scipy_csr ( A, dtype=None, imagify=False ):
# """
# convert a DOLFIN uBLASSparseMatrix to a scipy.sparse.csr_matrix()
#
# @param A: a DOLFIN uBLASSparseMatrix
# @param dtype: the numpy data type to use to store the matrix
# @param imagify: multiply the original matrix data by 1j
# """
# import scipy.sparse
# # get the sparse data from the input matrix
# (row,col,data) = A.data() # get sparse data
# col = np.intc(col)
# row = np.intc(row)
# n = A.size(0)
# if imagify: data = data*1j
# A_sp = scipy.sparse.csr_matrix( (data,col,row), shape=(n,n), dtype=dtype)
#
# return A_sp
. Output only the next line. | contribs = -1j*k0*Z0*contribs |
Here is a snippet: <|code_start|>
class DrivenProblemABC(EMProblem):
"""Set up driven problem, potentially terminated by an ABC.
Assumes lossless, frequency independent materials, and that the
boundary bilinear form is:
dot(cross(n, u), cross(n, v))
where n is a face normal and u,v are the trial and testing
functions. All forms are assumed to be real valued. They real
forms will be combined into a complex system matrix of the form
A = S - k0**2*M + 1j*k_0*S_0
where S, M are stiffness and mass matrices and k0 is the
freespace wave-number
"""
FormCombiner = CombineForms
def set_sources(self, sources):
self.sources = sources
def set_frequency(self, frequency):
"""Set simulation frequency in Hz"""
self.frequency = frequency
def get_LHS_matrix(self):
k0 = 2*N.pi*self.frequency/c0
<|code_end|>
. Write the next line using the current file imports:
import numpy as N
import dolfin
from sucemfem import Forms
from sucemfem import SystemMatrices
from sucemfem.Consts import c0, Z0
from sucemfem.Utilities.Converters import dolfin_ublassparse_to_scipy_csr
from EMProblem import EMProblem
and context from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
#
# Path: sucemfem/SystemMatrices.py
# class SystemMatrices(object):
# MatrixClass = dolfin.PETScMatrix
#
# def set_matrix_class(self, matrix_class):
# """Set matrix class to use for system matrix.
#
# Overrides the default value (dolfin.PETScMatrix) set in the
# class definition
#
# """
# self.MatrixClass = matrix_class
#
# def set_matrix_forms(self, matrix_forms):
# """Set matrix_forms with a dict mapping matrix names to bilinear forms"""
# self.matrix_forms = matrix_forms
#
# def set_boundary_conditions(self, boundary_conditions):
# """Set boundary_conditions with instance of BoundaryConditions"""
# self.boundary_conditions = boundary_conditions
#
# def calc_system_matrices(self):
# """Calculate and return system matrices in a dict"""
# system_matrices = dict()
# for matname, form in self.matrix_forms.items():
# mat = self.MatrixClass()
# if isinstance(form, Forms.NullForm):
# mat = None
# else:
# dolfin.assemble(form, tensor=mat)
# self.boundary_conditions.apply_essential(mat)
# system_matrices[matname] = mat
#
# return system_matrices
#
# Path: sucemfem/Consts.py
# Z0 = mu0*c0
#
# Path: sucemfem/Utilities/Converters.py
# def dolfin_ublassparse_to_scipy_csr ( A, dtype=None, imagify=False ):
# """
# convert a DOLFIN uBLASSparseMatrix to a scipy.sparse.csr_matrix()
#
# @param A: a DOLFIN uBLASSparseMatrix
# @param dtype: the numpy data type to use to store the matrix
# @param imagify: multiply the original matrix data by 1j
# """
# import scipy.sparse
# # get the sparse data from the input matrix
# (row,col,data) = A.data() # get sparse data
# col = np.intc(col)
# row = np.intc(row)
# n = A.size(0)
# if imagify: data = data*1j
# A_sp = scipy.sparse.csr_matrix( (data,col,row), shape=(n,n), dtype=dtype)
#
# return A_sp
, which may include functions, classes, or code. Output only the next line. | M = dolfin_ublassparse_to_scipy_csr(self.system_matrices['M']) |
Given the following code snippet before the placeholder: <|code_start|>## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
class BoundaryConditions(object):
def __init__(self):
self.boundary_conditions = {}
def add_boundary_condition(self, boundary_condition):
bc_num = boundary_condition.region_number
# boundary condition numbers have to be unique
assert(bc_num not in self.boundary_conditions)
self.boundary_conditions[bc_num] = boundary_condition
def apply_essential(self, A, b=None):
"""
Apply essential boundary conditions to system matrix A and optional RHS b
"""
for bc_num, bc in self.boundary_conditions.items():
apply_fn = bc.get_essential_application_func()
if b: apply_fn(A, b)
else: apply_fn(A)
def get_linear_form(self):
"""Get boundary conditions contribution to RHS linear form
"""
<|code_end|>
, predict the next line using imports from the current file:
from sucemfem import Forms
and context including class names, function names, and sometimes code from other files:
# Path: sucemfem/Forms.py
# class NullForm(object):
# class GalerkinInteriorForms(object):
# class EMGalerkinInteriorForms(GalerkinInteriorForms):
# class CombineGalerkinForms(object):
# def __add__(self, other):
# def set_material_functions(self, material_functions):
# def set_function_space(self, function_space):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def get_mass_form(self):
# def get_stiffness_form(self):
# def set_interior_forms(self, interior_forms):
# def set_boundary_conditions(self, boundary_conditions):
# def get_combined_forms(self):
# V = self.function_space = function_space
. Output only the next line. | lin_form = Forms.NullForm() |
Using the snippet: <|code_start|> # tris on each face
self.DUT = Geometry.BoundaryEdges(self.mesh)
def test_mark(self):
edge_meshfunc = dolfin.EdgeFunction('uint', self.mesh)
edge_meshfunc.set_all(0)
test_val = 11
self.DUT.mark(edge_meshfunc, test_val)
no_edges = len(edge_meshfunc.array())
self.assertTrue(
sum(edge_meshfunc.array() == test_val) == self.no_boundary_edges)
for edge in dolfin.SubsetIterator(edge_meshfunc, test_val):
self.assertTrue(self._check_on_boundary(edge))
def _check_on_boundary(self, entity):
"""Check if an entity is on boundary using numerical node positions
For the unit cube geometry an entity is on a boundary face if
all the nodes have one coordinate value that is equal to 0 or
one. Eg. if all the x values are equal to 1 that means the
entity lies on the x=0 boundary face.
"""
node_coords = entity.mesh().coordinates()[entity.entities(0)]
for coordvals in node_coords.T:
if np.allclose(coordvals,0) or np.allclose(coordvals, 1):
return True
return False
class test_BoundaryEdgeCells(unittest.TestCase):
def setUp(self):
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import dolfin
import numpy as np
from sucemfem.Testing.Meshes import InscribedTet
from sucemfem import Geometry
and context (class names, function names, or code) available:
# Path: sucemfem/Testing/Meshes.py
# class InscribedTet(object):
# def __init__(self):
# self.coordinates = N.array(
# [[-1./2 , 1./2 , -1./2],
# [ 1./2 , 1./2 , 1./2],
# [ 1./2 , -1./2 , -1./2],
# [-1./2 , -1./2 , 1./2],
# [ 1./6 , 1./6 , -1./6],
# [-1./6 , 1./6 , 1./6],
# [-1./6 , -1./6 , -1./6],
# [ 1./6 , -1./6 , 1./6]],
# N.float64)
# self.element_nodes = N.array(
# [[1, 4, 6, 7],
# [1, 3, 5, 7],
# [3, 4, 7, 8],
# [1, 2, 5, 6],
# [2, 3, 5, 8],
# [2, 4, 6, 8],
# [4, 6, 7, 8],
# [1, 5, 6, 7],
# [3, 5, 7, 8],
# [2, 5, 6, 8],
# [5, 6, 7, 8]], N.uint32) - 1
#
# def get_dolfin_mesh(self):
# mesh = dolfin.Mesh()
# me = dolfin.MeshEditor()
# me.open(mesh,'tetrahedron', 3, 3)
# me.init_vertices(len(self.coordinates))
# me.init_cells(len(self.element_nodes))
# for i, coord in enumerate(self.coordinates):
# me.add_vertex(N.uint(i), *coord)
# for i, el_nodes in enumerate(self.element_nodes):
# me.add_cell(i, *el_nodes)
# me.close()
# return mesh
#
# Path: sucemfem/Geometry.py
# class EnsureInitialised(object):
# class BoundaryEdges(object):
# class BoundaryEdgeCells(object):
# class CellsConnected2Edges(object):
# def __init__(self, dolfin_mesh):
# def __call__(self, dim0, dim1):
# def __init__(self, mesh, boundary_facefun=None, boundary_value=1):
# def mark(self, edge_meshfun, value):
# def __init__(self, mesh):
# def mark(self, cell_meshfun, value):
# def __init__(self, boundary_edgefun, boundary_value):
# def mark(self, cell_meshfun, value):
. Output only the next line. | self.mesh = InscribedTet().get_dolfin_mesh() |
Continue the code snippet: <|code_start|>## Copyright (C) 2011 Stellenbosch University
##
## This file is part of SUCEM.
##
## SUCEM is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## SUCEM is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SUCEM. If not, see <http://www.gnu.org/licenses/>.
##
## Contact: cemagga@gmail.com
# Authors:
# Neilen Marais <nmarais@gmail.com>
from __future__ import division
# Module under test
class test_BoundaryEdges(unittest.TestCase):
def setUp(self):
self.mesh = dolfin.UnitCube(1,1,1)
self.no_boundary_edges = 18 # for 1x1x1 UnitCube meshed with 2
# tris on each face
<|code_end|>
. Use current file imports:
import unittest
import dolfin
import numpy as np
from sucemfem.Testing.Meshes import InscribedTet
from sucemfem import Geometry
and context (classes, functions, or code) from other files:
# Path: sucemfem/Testing/Meshes.py
# class InscribedTet(object):
# def __init__(self):
# self.coordinates = N.array(
# [[-1./2 , 1./2 , -1./2],
# [ 1./2 , 1./2 , 1./2],
# [ 1./2 , -1./2 , -1./2],
# [-1./2 , -1./2 , 1./2],
# [ 1./6 , 1./6 , -1./6],
# [-1./6 , 1./6 , 1./6],
# [-1./6 , -1./6 , -1./6],
# [ 1./6 , -1./6 , 1./6]],
# N.float64)
# self.element_nodes = N.array(
# [[1, 4, 6, 7],
# [1, 3, 5, 7],
# [3, 4, 7, 8],
# [1, 2, 5, 6],
# [2, 3, 5, 8],
# [2, 4, 6, 8],
# [4, 6, 7, 8],
# [1, 5, 6, 7],
# [3, 5, 7, 8],
# [2, 5, 6, 8],
# [5, 6, 7, 8]], N.uint32) - 1
#
# def get_dolfin_mesh(self):
# mesh = dolfin.Mesh()
# me = dolfin.MeshEditor()
# me.open(mesh,'tetrahedron', 3, 3)
# me.init_vertices(len(self.coordinates))
# me.init_cells(len(self.element_nodes))
# for i, coord in enumerate(self.coordinates):
# me.add_vertex(N.uint(i), *coord)
# for i, el_nodes in enumerate(self.element_nodes):
# me.add_cell(i, *el_nodes)
# me.close()
# return mesh
#
# Path: sucemfem/Geometry.py
# class EnsureInitialised(object):
# class BoundaryEdges(object):
# class BoundaryEdgeCells(object):
# class CellsConnected2Edges(object):
# def __init__(self, dolfin_mesh):
# def __call__(self, dim0, dim1):
# def __init__(self, mesh, boundary_facefun=None, boundary_value=1):
# def mark(self, edge_meshfun, value):
# def __init__(self, mesh):
# def mark(self, cell_meshfun, value):
# def __init__(self, boundary_edgefun, boundary_value):
# def mark(self, cell_meshfun, value):
. Output only the next line. | self.DUT = Geometry.BoundaryEdges(self.mesh) |
Given the code snippet: <|code_start|># coding: utf-8
class HomePageTestCase(TestCase):
def setUp(self):
self.client = Client()
<|code_end|>
, generate the next line using the imports in this file:
from lxml import html
from django.test import TestCase
from django.test.client import Client
from quotes.tests.utils import create_test_quote
and context (functions, classes, or occasionally code) from other files:
# Path: quotes/tests/utils.py
# def create_test_quote():
# body = 'Test quote'
# now = datetime.now()
# quote = Quote.objects.create(body=body, publish_date=now)
# quote.authors.create(name='Author 1')
# quote.authors.create(name='Author 2')
# quote.tags.create(name='Tag 1')
# quote.tags.create(name='Tag 2')
# return quote
. Output only the next line. | self.quote = create_test_quote() |
Given the code snippet: <|code_start|># coding: utf-8
class AuthorsPageTestCase(TestCase):
def setUp(self):
self.client = Client()
self.dom = ''
self.authors = []
def tearDown(self):
self.dom = ''
self.authors = []
def __load_dom(self):
response = self.client.get('/authors/')
self.dom = html.fromstring(response.content)
def testAuthorsPageResponse(self):
response = self.client.get('/authors/')
self.failUnlessEqual(response.status_code, 200)
def testAuthorsPageShouldShowAuthors(self):
<|code_end|>
, generate the next line using the imports in this file:
from lxml import html
from django.test import TestCase
from django.test.client import Client
from quotes.tests.utils import create_multiple_test_authors
and context (functions, classes, or occasionally code) from other files:
# Path: quotes/tests/utils.py
# def create_multiple_test_authors(ammount=100):
# authors = []
# for i in xrange(ammount):
# name = "Author %d" % i
# author = Author.objects.create(name=name)
# authors.append(author)
# now = datetime.now()
# for i in xrange(10):
# body = 'Test quote %d' % i
# quote = Quote.objects.create(body=body, publish_date=now)
# quote.authors.add(authors[0])
# return authors
. Output only the next line. | self.authors = create_multiple_test_authors() |
Continue the code snippet: <|code_start|># coding: utf-8
class QuoteAdminForm(forms.ModelForm):
readonly_fields = ('uuid',)
class Meta:
model = Quote
def __init__(self, *args, **kwds):
super(QuoteAdminForm, self).__init__(*args, **kwds)
<|code_end|>
. Use current file imports:
from quotes.models import Author, Tag, Quote
from django import forms
from django.contrib import admin
and context (classes, functions, or code) from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
. Output only the next line. | self.fields['authors'].queryset = Author.objects.order_by('name') |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class QuoteAdminForm(forms.ModelForm):
readonly_fields = ('uuid',)
class Meta:
model = Quote
def __init__(self, *args, **kwds):
super(QuoteAdminForm, self).__init__(*args, **kwds)
self.fields['authors'].queryset = Author.objects.order_by('name')
<|code_end|>
, predict the next line using imports from the current file:
from quotes.models import Author, Tag, Quote
from django import forms
from django.contrib import admin
and context including class names, function names, and sometimes code from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
. Output only the next line. | self.fields['tags'].queryset = Tag.objects.order_by('name') |
Here is a snippet: <|code_start|># coding: utf-8
class QuoteAdminForm(forms.ModelForm):
readonly_fields = ('uuid',)
class Meta:
<|code_end|>
. Write the next line using the current file imports:
from quotes.models import Author, Tag, Quote
from django import forms
from django.contrib import admin
and context from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
, which may include functions, classes, or code. Output only the next line. | model = Quote |
Predict the next line for this snippet: <|code_start|># coding: utf-8
def author_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.name[:99])
def quote_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.body[:99])
def tag_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.name[:99])
<|code_end|>
with the help of current file imports:
import uuid
from django.db.models import signals
from django.template.defaultfilters import slugify
from .models import Author, Quote, Tag
and context from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
, which may contain function names, class names, or code. Output only the next line. | signals.pre_save.connect(author_pre_save, sender=Author) |
Predict the next line after this snippet: <|code_start|># coding: utf-8
def author_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.name[:99])
def quote_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.body[:99])
def tag_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.name[:99])
signals.pre_save.connect(author_pre_save, sender=Author)
<|code_end|>
using the current file's imports:
import uuid
from django.db.models import signals
from django.template.defaultfilters import slugify
from .models import Author, Quote, Tag
and any relevant context from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | signals.pre_save.connect(quote_pre_save, sender=Quote) |
Based on the snippet: <|code_start|># coding: utf-8
def author_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.name[:99])
def quote_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.body[:99])
def tag_pre_save(signal, instance, sender, **kwargs):
if not instance.uuid:
instance.uuid = uuid.uuid4().hex[:12]
instance.slug = slugify(instance.name[:99])
signals.pre_save.connect(author_pre_save, sender=Author)
signals.pre_save.connect(quote_pre_save, sender=Quote)
<|code_end|>
, predict the immediate next line with the help of imports:
import uuid
from django.db.models import signals
from django.template.defaultfilters import slugify
from .models import Author, Quote, Tag
and context (classes, functions, sometimes code) from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | signals.pre_save.connect(tag_pre_save, sender=Tag) |
Predict the next line after this snippet: <|code_start|># coding: utf-8
class QuotesRenderer(StaticSiteRenderer):
def get_paths(self):
paths = set([
'/',
'/authors/',
'/tags/',
'/random/',
'/submit/',
'/feed/',
'/sitemap.xml',
])
<|code_end|>
using the current file's imports:
from django_medusa.renderers import StaticSiteRenderer
from .models import Quote, Author, Tag
and any relevant context from other files:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | for data in [Quote, Author, Tag]: |
Based on the snippet: <|code_start|># coding: utf-8
class QuotesRenderer(StaticSiteRenderer):
def get_paths(self):
paths = set([
'/',
'/authors/',
'/tags/',
'/random/',
'/submit/',
'/feed/',
'/sitemap.xml',
])
<|code_end|>
, predict the immediate next line with the help of imports:
from django_medusa.renderers import StaticSiteRenderer
from .models import Quote, Author, Tag
and context (classes, functions, sometimes code) from other files:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | for data in [Quote, Author, Tag]: |
Based on the snippet: <|code_start|># coding: utf-8
class QuotesRenderer(StaticSiteRenderer):
def get_paths(self):
paths = set([
'/',
'/authors/',
'/tags/',
'/random/',
'/submit/',
'/feed/',
'/sitemap.xml',
])
<|code_end|>
, predict the immediate next line with the help of imports:
from django_medusa.renderers import StaticSiteRenderer
from .models import Quote, Author, Tag
and context (classes, functions, sometimes code) from other files:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | for data in [Quote, Author, Tag]: |
Based on the snippet: <|code_start|># coding: utf-8
class AuthorPageTestCase(TestCase):
def setUp(self):
self.client = Client()
self.dom = ''
<|code_end|>
, predict the immediate next line with the help of imports:
from lxml import html
from django.test import TestCase
from django.test.client import Client
from quotes.tests.utils import create_test_author
and context (classes, functions, sometimes code) from other files:
# Path: quotes/tests/utils.py
# def create_test_author():
# name = 'Author'
# author = Author.objects.create(name=name)
# now = datetime.now()
# for i in xrange(10):
# body = 'Test quote %d' % i
# quote = Quote.objects.create(body=body, publish_date=now)
# quote.authors.add(author)
# return author
. Output only the next line. | self.author = create_test_author() |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class TagPageTestCase(TestCase):
def setUp(self):
self.client = Client()
self.dom = ''
<|code_end|>
, predict the next line using imports from the current file:
from lxml import html
from django.test import TestCase
from django.test.client import Client
from quotes.tests.utils import create_test_tag
and context including class names, function names, and sometimes code from other files:
# Path: quotes/tests/utils.py
# def create_test_tag():
# name = 'Tag'
# tag = Tag.objects.create(name=name)
# now = datetime.now()
# for i in xrange(10):
# body = 'Test quote %d' % i
# quote = Quote.objects.create(body=body, publish_date=now)
# quote.tags.add(tag)
# return tag
. Output only the next line. | self.tag = create_test_tag() |
Next line prediction: <|code_start|># coding: utf-8
urlpatterns = patterns(
'quotes.views',
url(
regex=r'^q/(?P<uuid>[\w]+)/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
<|code_end|>
. Use current file imports:
(from django.conf import settings
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from .views import (QuoteDetailView, AuthorDetailView, TagDetailView,
AuthorListView, TagListView))
and context including class names, function names, or small code snippets from other files:
# Path: quotes/views.py
# class QuoteDetailView(DetailView):
# model = Quote
#
# def get_object(self):
# return get_object_or_404(Quote, uuid=self.kwargs['uuid'])
#
# class AuthorDetailView(DetailViewMixin):
# model = Author
# title = "Programming quotes by %s | defprogramming"
# description = "Listing all programming quotes by %s. Quotes about " \
# "programming, coding, software industry."
#
# class TagDetailView(DetailViewMixin):
# model = Tag
# title = "Programming quotes tagged under %s | defprogramming"
# description = "Listing all programming quotes tagged under %s. "\
# "Quotes about programming, coding, software industry."
#
# class AuthorListView(ListView):
# model = Author
#
# def get_queryset(self):
# return self.model.objects.extra(select={
# 'name_lower': 'lower(name)'}
# ).order_by('name_lower')
#
# def get_context_data(self, **kwargs):
# context = super(AuthorListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all authors | defprogramming"
# context['description'] = "List of all the authors with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
#
# class TagListView(ListView):
# model = Tag
#
# def get_context_data(self, **kwargs):
# context = super(TagListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all tags | defprogramming"
# context['description'] = "List of all the tags with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
. Output only the next line. | QuoteDetailView.as_view() |
Given the code snippet: <|code_start|># coding: utf-8
urlpatterns = patterns(
'quotes.views',
url(
regex=r'^q/(?P<uuid>[\w]+)/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
QuoteDetailView.as_view()
),
name='quote'
),
# url(r'^q/(?P<uuid>[\w]+)/$', 'detail', name='quote'),
url(r'^quote/(?P<slug>[\w-]+)/$', 'quote_redirect'),
url(
regex=r'^authors/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
AuthorListView.as_view()
),
name='authors'
),
url(
regex=r'^quotes-by/(?P<slug>[\w-]+)/(page/(?P<page>\d+)/)?$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from .views import (QuoteDetailView, AuthorDetailView, TagDetailView,
AuthorListView, TagListView)
and context (functions, classes, or occasionally code) from other files:
# Path: quotes/views.py
# class QuoteDetailView(DetailView):
# model = Quote
#
# def get_object(self):
# return get_object_or_404(Quote, uuid=self.kwargs['uuid'])
#
# class AuthorDetailView(DetailViewMixin):
# model = Author
# title = "Programming quotes by %s | defprogramming"
# description = "Listing all programming quotes by %s. Quotes about " \
# "programming, coding, software industry."
#
# class TagDetailView(DetailViewMixin):
# model = Tag
# title = "Programming quotes tagged under %s | defprogramming"
# description = "Listing all programming quotes tagged under %s. "\
# "Quotes about programming, coding, software industry."
#
# class AuthorListView(ListView):
# model = Author
#
# def get_queryset(self):
# return self.model.objects.extra(select={
# 'name_lower': 'lower(name)'}
# ).order_by('name_lower')
#
# def get_context_data(self, **kwargs):
# context = super(AuthorListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all authors | defprogramming"
# context['description'] = "List of all the authors with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
#
# class TagListView(ListView):
# model = Tag
#
# def get_context_data(self, **kwargs):
# context = super(TagListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all tags | defprogramming"
# context['description'] = "List of all the tags with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
. Output only the next line. | AuthorDetailView.as_view() |
Next line prediction: <|code_start|> name='quote'
),
# url(r'^q/(?P<uuid>[\w]+)/$', 'detail', name='quote'),
url(r'^quote/(?P<slug>[\w-]+)/$', 'quote_redirect'),
url(
regex=r'^authors/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
AuthorListView.as_view()
),
name='authors'
),
url(
regex=r'^quotes-by/(?P<slug>[\w-]+)/(page/(?P<page>\d+)/)?$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
AuthorDetailView.as_view()
),
name='author'
),
url(
regex=r'^tags/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
TagListView.as_view()
),
name='tags'
),
url(
regex=r'^quotes-tagged-with/(?P<slug>[\w-]+)/(page/(?P<page>\d+)/)?$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
<|code_end|>
. Use current file imports:
(from django.conf import settings
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from .views import (QuoteDetailView, AuthorDetailView, TagDetailView,
AuthorListView, TagListView))
and context including class names, function names, or small code snippets from other files:
# Path: quotes/views.py
# class QuoteDetailView(DetailView):
# model = Quote
#
# def get_object(self):
# return get_object_or_404(Quote, uuid=self.kwargs['uuid'])
#
# class AuthorDetailView(DetailViewMixin):
# model = Author
# title = "Programming quotes by %s | defprogramming"
# description = "Listing all programming quotes by %s. Quotes about " \
# "programming, coding, software industry."
#
# class TagDetailView(DetailViewMixin):
# model = Tag
# title = "Programming quotes tagged under %s | defprogramming"
# description = "Listing all programming quotes tagged under %s. "\
# "Quotes about programming, coding, software industry."
#
# class AuthorListView(ListView):
# model = Author
#
# def get_queryset(self):
# return self.model.objects.extra(select={
# 'name_lower': 'lower(name)'}
# ).order_by('name_lower')
#
# def get_context_data(self, **kwargs):
# context = super(AuthorListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all authors | defprogramming"
# context['description'] = "List of all the authors with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
#
# class TagListView(ListView):
# model = Tag
#
# def get_context_data(self, **kwargs):
# context = super(TagListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all tags | defprogramming"
# context['description'] = "List of all the tags with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
. Output only the next line. | TagDetailView.as_view() |
Here is a snippet: <|code_start|># coding: utf-8
urlpatterns = patterns(
'quotes.views',
url(
regex=r'^q/(?P<uuid>[\w]+)/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
QuoteDetailView.as_view()
),
name='quote'
),
# url(r'^q/(?P<uuid>[\w]+)/$', 'detail', name='quote'),
url(r'^quote/(?P<slug>[\w-]+)/$', 'quote_redirect'),
url(
regex=r'^authors/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from .views import (QuoteDetailView, AuthorDetailView, TagDetailView,
AuthorListView, TagListView)
and context from other files:
# Path: quotes/views.py
# class QuoteDetailView(DetailView):
# model = Quote
#
# def get_object(self):
# return get_object_or_404(Quote, uuid=self.kwargs['uuid'])
#
# class AuthorDetailView(DetailViewMixin):
# model = Author
# title = "Programming quotes by %s | defprogramming"
# description = "Listing all programming quotes by %s. Quotes about " \
# "programming, coding, software industry."
#
# class TagDetailView(DetailViewMixin):
# model = Tag
# title = "Programming quotes tagged under %s | defprogramming"
# description = "Listing all programming quotes tagged under %s. "\
# "Quotes about programming, coding, software industry."
#
# class AuthorListView(ListView):
# model = Author
#
# def get_queryset(self):
# return self.model.objects.extra(select={
# 'name_lower': 'lower(name)'}
# ).order_by('name_lower')
#
# def get_context_data(self, **kwargs):
# context = super(AuthorListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all authors | defprogramming"
# context['description'] = "List of all the authors with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
#
# class TagListView(ListView):
# model = Tag
#
# def get_context_data(self, **kwargs):
# context = super(TagListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all tags | defprogramming"
# context['description'] = "List of all the tags with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
, which may include functions, classes, or code. Output only the next line. | AuthorListView.as_view() |
Continue the code snippet: <|code_start|>urlpatterns = patterns(
'quotes.views',
url(
regex=r'^q/(?P<uuid>[\w]+)/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
QuoteDetailView.as_view()
),
name='quote'
),
# url(r'^q/(?P<uuid>[\w]+)/$', 'detail', name='quote'),
url(r'^quote/(?P<slug>[\w-]+)/$', 'quote_redirect'),
url(
regex=r'^authors/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
AuthorListView.as_view()
),
name='authors'
),
url(
regex=r'^quotes-by/(?P<slug>[\w-]+)/(page/(?P<page>\d+)/)?$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
AuthorDetailView.as_view()
),
name='author'
),
url(
regex=r'^tags/$',
view=cache_page(settings.DEFAULT_CACHE_TIME)(
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from .views import (QuoteDetailView, AuthorDetailView, TagDetailView,
AuthorListView, TagListView)
and context (classes, functions, or code) from other files:
# Path: quotes/views.py
# class QuoteDetailView(DetailView):
# model = Quote
#
# def get_object(self):
# return get_object_or_404(Quote, uuid=self.kwargs['uuid'])
#
# class AuthorDetailView(DetailViewMixin):
# model = Author
# title = "Programming quotes by %s | defprogramming"
# description = "Listing all programming quotes by %s. Quotes about " \
# "programming, coding, software industry."
#
# class TagDetailView(DetailViewMixin):
# model = Tag
# title = "Programming quotes tagged under %s | defprogramming"
# description = "Listing all programming quotes tagged under %s. "\
# "Quotes about programming, coding, software industry."
#
# class AuthorListView(ListView):
# model = Author
#
# def get_queryset(self):
# return self.model.objects.extra(select={
# 'name_lower': 'lower(name)'}
# ).order_by('name_lower')
#
# def get_context_data(self, **kwargs):
# context = super(AuthorListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all authors | defprogramming"
# context['description'] = "List of all the authors with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
#
# class TagListView(ListView):
# model = Tag
#
# def get_context_data(self, **kwargs):
# context = super(TagListView, self).get_context_data(**kwargs)
# context['title'] = "Listing all tags | defprogramming"
# context['description'] = "List of all the tags with quotes " \
# "published. Quotes about programming, " \
# "coding, software industry."
# return context
. Output only the next line. | TagListView.as_view() |
Given snippet: <|code_start|>
class DetailViewMixin(DetailView):
def get_context_data(self, **kwargs):
context = super(DetailViewMixin, self).get_context_data(**kwargs)
quotes = self.object.quote_set.all()
context['quotes'] = Paginator(quotes, PER_PAGE).page(
self.kwargs.get('page') or 1
)
key = self.model._meta.verbose_name_plural.lower()
context[key] = self.model.objects.extra(select={
'name_lower': 'lower(name)'}
).order_by('name_lower')
context['title'] = self.title % self.object.name
context['description'] = self.description % self.object.name
context['base_url_pagination'] = reverse(
self.model.__name__.lower(),
kwargs={
'slug': self.object.slug
}
)
return context
class AuthorListView(ListView):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.cache import cache_page
from django.views.generic import DetailView, ListView
from .models import Author, Tag, Quote
from .forms import QuoteForm
and context:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# Path: quotes/forms.py
# class QuoteForm(forms.Form):
# name = forms.CharField(label='Your name', max_length=50)
# email = forms.EmailField(label='Your e-mail')
# quote = forms.Field(label='Quote', widget=forms.Textarea)
# authors = forms.CharField(label='Authors, separated by commas')
# tags = forms.CharField(label='Tags, separated by commas')
# source = forms.CharField(label='Source (website, book etc.)')
#
# def save(self, data):
# message = "%s\n\nFrom: %s <%s>\nAuthors: %s\n" \
# "Tags: %s\nSource: %s\n" % (data.get('quote'),
# data.get('name'),
# data.get('email'),
# data.get('authors'),
# data.get('tags'),
# data.get('source'))
#
# send_mail('[defprogramming] New quote', message, data.get('email'),
# [settings.SERVER_EMAIL], fail_silently=False)
which might include code, classes, or functions. Output only the next line. | model = Author |
Given snippet: <|code_start|> )
return context
class AuthorListView(ListView):
model = Author
def get_queryset(self):
return self.model.objects.extra(select={
'name_lower': 'lower(name)'}
).order_by('name_lower')
def get_context_data(self, **kwargs):
context = super(AuthorListView, self).get_context_data(**kwargs)
context['title'] = "Listing all authors | defprogramming"
context['description'] = "List of all the authors with quotes " \
"published. Quotes about programming, " \
"coding, software industry."
return context
class AuthorDetailView(DetailViewMixin):
model = Author
title = "Programming quotes by %s | defprogramming"
description = "Listing all programming quotes by %s. Quotes about " \
"programming, coding, software industry."
class TagListView(ListView):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.cache import cache_page
from django.views.generic import DetailView, ListView
from .models import Author, Tag, Quote
from .forms import QuoteForm
and context:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# Path: quotes/forms.py
# class QuoteForm(forms.Form):
# name = forms.CharField(label='Your name', max_length=50)
# email = forms.EmailField(label='Your e-mail')
# quote = forms.Field(label='Quote', widget=forms.Textarea)
# authors = forms.CharField(label='Authors, separated by commas')
# tags = forms.CharField(label='Tags, separated by commas')
# source = forms.CharField(label='Source (website, book etc.)')
#
# def save(self, data):
# message = "%s\n\nFrom: %s <%s>\nAuthors: %s\n" \
# "Tags: %s\nSource: %s\n" % (data.get('quote'),
# data.get('name'),
# data.get('email'),
# data.get('authors'),
# data.get('tags'),
# data.get('source'))
#
# send_mail('[defprogramming] New quote', message, data.get('email'),
# [settings.SERVER_EMAIL], fail_silently=False)
which might include code, classes, or functions. Output only the next line. | model = Tag |
Using the snippet: <|code_start|># coding: utf-8
PER_PAGE = 25
@cache_page(settings.DEFAULT_CACHE_TIME)
def index(request, page=1, format=None):
try:
<|code_end|>
, determine the next line of code. You have imports:
import json
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.cache import cache_page
from django.views.generic import DetailView, ListView
from .models import Author, Tag, Quote
from .forms import QuoteForm
and context (class names, function names, or code) available:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# Path: quotes/forms.py
# class QuoteForm(forms.Form):
# name = forms.CharField(label='Your name', max_length=50)
# email = forms.EmailField(label='Your e-mail')
# quote = forms.Field(label='Quote', widget=forms.Textarea)
# authors = forms.CharField(label='Authors, separated by commas')
# tags = forms.CharField(label='Tags, separated by commas')
# source = forms.CharField(label='Source (website, book etc.)')
#
# def save(self, data):
# message = "%s\n\nFrom: %s <%s>\nAuthors: %s\n" \
# "Tags: %s\nSource: %s\n" % (data.get('quote'),
# data.get('name'),
# data.get('email'),
# data.get('authors'),
# data.get('tags'),
# data.get('source'))
#
# send_mail('[defprogramming] New quote', message, data.get('email'),
# [settings.SERVER_EMAIL], fail_silently=False)
. Output only the next line. | featured_quote = Quote.objects.filter(featured=True) \ |
Using the snippet: <|code_start|> return HttpResponse(json.dumps(data), mimetype='application/json')
else:
title = "defprogramming: quotes about coding"
description = "Quotes about programming, coding, computer science, " \
"debugging, software industry, startups and motivation."
base_url_pagination = reverse('root')
return render_to_response('quotes/index.html',
locals(),
context_instance=RequestContext(request))
def quote_redirect(request, slug):
quote = get_object_or_404(Quote, slug=slug)
return HttpResponsePermanentRedirect(quote.get_absolute_url())
def random(request):
quote = Quote.objects.order_by('?')[0]
return render_to_response('quotes/random.html',
{'quote': quote},
context_instance=RequestContext(request))
def submit_quote(request):
title = "Submit a quote | defprogramming"
description = "Use this form to submit a quote. Please send only quotes " \
"about programming, coding, software industry."
sent = False
if request.method == 'POST':
<|code_end|>
, determine the next line of code. You have imports:
import json
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.cache import cache_page
from django.views.generic import DetailView, ListView
from .models import Author, Tag, Quote
from .forms import QuoteForm
and context (class names, function names, or code) available:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# Path: quotes/forms.py
# class QuoteForm(forms.Form):
# name = forms.CharField(label='Your name', max_length=50)
# email = forms.EmailField(label='Your e-mail')
# quote = forms.Field(label='Quote', widget=forms.Textarea)
# authors = forms.CharField(label='Authors, separated by commas')
# tags = forms.CharField(label='Tags, separated by commas')
# source = forms.CharField(label='Source (website, book etc.)')
#
# def save(self, data):
# message = "%s\n\nFrom: %s <%s>\nAuthors: %s\n" \
# "Tags: %s\nSource: %s\n" % (data.get('quote'),
# data.get('name'),
# data.get('email'),
# data.get('authors'),
# data.get('tags'),
# data.get('source'))
#
# send_mail('[defprogramming] New quote', message, data.get('email'),
# [settings.SERVER_EMAIL], fail_silently=False)
. Output only the next line. | form = QuoteForm(request.POST) |
Based on the snippet: <|code_start|># coding: utf-8
admin.autodiscover()
quotes = {
'queryset': Quote.objects.all(),
'date_field': 'publish_date'
}
authors = {
<|code_end|>
, predict the immediate next line with the help of imports:
from random import choice
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.contrib import admin
from django.contrib.sitemaps import GenericSitemap
from rest_framework import routers, serializers, viewsets, generics
from quotes.models import Quote, Author, Tag
from quotes.feeds import LatestEntriesFeed
and context (classes, functions, sometimes code) from other files:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# Path: quotes/feeds.py
# class LatestEntriesFeed(Feed):
# title = "def programming: latest quotes"
# link = "/"
# description = "Latest published quotes from defprogramming.com"
#
# def items(self):
# return Quote.objects.order_by('-publish_date')[:20]
#
# def item_title(self, item):
# authors = ""
# for author in item.authors.all():
# authors += author.name + " and "
# return re.sub(r' and $', '', authors)
#
# def item_description(self, item):
# return item.body
. Output only the next line. | 'queryset': Author.objects.all() |
Given snippet: <|code_start|># coding: utf-8
admin.autodiscover()
quotes = {
'queryset': Quote.objects.all(),
'date_field': 'publish_date'
}
authors = {
'queryset': Author.objects.all()
}
tags = {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from random import choice
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.contrib import admin
from django.contrib.sitemaps import GenericSitemap
from rest_framework import routers, serializers, viewsets, generics
from quotes.models import Quote, Author, Tag
from quotes.feeds import LatestEntriesFeed
and context:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# Path: quotes/feeds.py
# class LatestEntriesFeed(Feed):
# title = "def programming: latest quotes"
# link = "/"
# description = "Latest published quotes from defprogramming.com"
#
# def items(self):
# return Quote.objects.order_by('-publish_date')[:20]
#
# def item_title(self, item):
# authors = ""
# for author in item.authors.all():
# authors += author.name + " and "
# return re.sub(r' and $', '', authors)
#
# def item_description(self, item):
# return item.body
which might include code, classes, or functions. Output only the next line. | 'queryset': Tag.objects.all() |
Given snippet: <|code_start|>
class QuoteSerializer(serializers.HyperlinkedModelSerializer):
authors = AuthorSerializer(many=True, read_only=True)
class Meta:
model = Quote
fields = ('body', 'authors', 'slug')
# ViewSets define the view behavior.
class QuoteViewSet(viewsets.ModelViewSet):
queryset = Quote.objects.all()
serializer_class = QuoteSerializer
class RandomQuoteViewSet(viewsets.ModelViewSet):
queryset = Quote.objects.all().order_by('?')[:1]
serializer_class = QuoteSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'quotes', QuoteViewSet)
router.register(r'random', RandomQuoteViewSet)
urlpatterns = patterns(
'',
url(r'^', include('quotes.urls')),
url(r'^api/v1/', include(router.urls)),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from random import choice
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.contrib import admin
from django.contrib.sitemaps import GenericSitemap
from rest_framework import routers, serializers, viewsets, generics
from quotes.models import Quote, Author, Tag
from quotes.feeds import LatestEntriesFeed
and context:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# Path: quotes/feeds.py
# class LatestEntriesFeed(Feed):
# title = "def programming: latest quotes"
# link = "/"
# description = "Latest published quotes from defprogramming.com"
#
# def items(self):
# return Quote.objects.order_by('-publish_date')[:20]
#
# def item_title(self, item):
# authors = ""
# for author in item.authors.all():
# authors += author.name + " and "
# return re.sub(r' and $', '', authors)
#
# def item_description(self, item):
# return item.body
which might include code, classes, or functions. Output only the next line. | url(r'^feed/$', LatestEntriesFeed(), name='feed'), |
Using the snippet: <|code_start|># coding: utf-8
class LatestEntriesFeed(Feed):
title = "def programming: latest quotes"
link = "/"
description = "Latest published quotes from defprogramming.com"
def items(self):
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib.syndication.views import Feed
from quotes.models import Quote
import re
and context (class names, function names, or code) available:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
. Output only the next line. | return Quote.objects.order_by('-publish_date')[:20] |
Given the code snippet: <|code_start|># coding: utf-8
class TagsPageTestCase(TestCase):
def setUp(self):
self.client = Client()
self.dom = ''
def tearDown(self):
self.dom = ''
def __load_dom(self):
response = self.client.get('/tags/')
self.dom = html.fromstring(response.content)
def testTagsPageResponse(self):
response = self.client.get('/tags/')
self.failUnlessEqual(response.status_code, 200)
def testTagsPageShouldShowTags(self):
<|code_end|>
, generate the next line using the imports in this file:
from lxml import html
from django.test import TestCase
from django.test.client import Client
from quotes.tests.utils import create_multiple_test_tags
and context (functions, classes, or occasionally code) from other files:
# Path: quotes/tests/utils.py
# def create_multiple_test_tags(ammount=100):
# tags = []
# for i in xrange(ammount):
# name = "Tag %d" % i
# tag = Tag.objects.create(name=name)
# tags.append(tag)
# now = datetime.now()
# for i in xrange(10):
# body = 'Test quote %d' % i
# quote = Quote.objects.create(body=body, publish_date=now)
# quote.tags.add(tags[0])
# return tags
. Output only the next line. | self.tags = create_multiple_test_tags() |
Predict the next line after this snippet: <|code_start|># coding: utf-8
class Command(BaseCommand):
help = 'Generates unique hashes for quotes, tags and authors'
def handle(self, *args, **options):
<|code_end|>
using the current file's imports:
import uuid
from django.core.management.base import BaseCommand
from quotes.models import Quote, Author, Tag
and any relevant context from other files:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | models = [Quote, Author, Tag] |
Using the snippet: <|code_start|># coding: utf-8
class Command(BaseCommand):
help = 'Generates unique hashes for quotes, tags and authors'
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have imports:
import uuid
from django.core.management.base import BaseCommand
from quotes.models import Quote, Author, Tag
and context (class names, function names, or code) available:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | models = [Quote, Author, Tag] |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
class Command(BaseCommand):
help = 'Generates unique hashes for quotes, tags and authors'
def handle(self, *args, **options):
<|code_end|>
, predict the next line using imports from the current file:
import uuid
from django.core.management.base import BaseCommand
from quotes.models import Quote, Author, Tag
and context including class names, function names, and sometimes code from other files:
# Path: quotes/models.py
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
#
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
. Output only the next line. | models = [Quote, Author, Tag] |
Here is a snippet: <|code_start|># coding: utf-8
class SubmitQuotePageTestCase(TestCase):
def setUp(self):
self.client = Client()
self.dom = ''
<|code_end|>
. Write the next line using the current file imports:
from lxml import html
from django.test import TestCase
from django.test.client import Client
from quotes.tests.utils import create_test_tag
and context from other files:
# Path: quotes/tests/utils.py
# def create_test_tag():
# name = 'Tag'
# tag = Tag.objects.create(name=name)
# now = datetime.now()
# for i in xrange(10):
# body = 'Test quote %d' % i
# quote = Quote.objects.create(body=body, publish_date=now)
# quote.tags.add(tag)
# return tag
, which may include functions, classes, or code. Output only the next line. | self.tag = create_test_tag() |
Next line prediction: <|code_start|># coding: utf-8
def create_test_quote():
body = 'Test quote'
now = datetime.now()
quote = Quote.objects.create(body=body, publish_date=now)
quote.authors.create(name='Author 1')
quote.authors.create(name='Author 2')
quote.tags.create(name='Tag 1')
quote.tags.create(name='Tag 2')
return quote
def create_test_author():
name = 'Author'
<|code_end|>
. Use current file imports:
(from datetime import datetime
from quotes.models import Author, Tag, Quote)
and context including class names, function names, or small code snippets from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
. Output only the next line. | author = Author.objects.create(name=name) |
Given the code snippet: <|code_start|># coding: utf-8
def create_test_quote():
body = 'Test quote'
now = datetime.now()
quote = Quote.objects.create(body=body, publish_date=now)
quote.authors.create(name='Author 1')
quote.authors.create(name='Author 2')
quote.tags.create(name='Tag 1')
quote.tags.create(name='Tag 2')
return quote
def create_test_author():
name = 'Author'
author = Author.objects.create(name=name)
now = datetime.now()
for i in xrange(10):
body = 'Test quote %d' % i
quote = Quote.objects.create(body=body, publish_date=now)
quote.authors.add(author)
return author
def create_test_tag():
name = 'Tag'
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from quotes.models import Author, Tag, Quote
and context (functions, classes, or occasionally code) from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
. Output only the next line. | tag = Tag.objects.create(name=name) |
Continue the code snippet: <|code_start|># coding: utf-8
def create_test_quote():
body = 'Test quote'
now = datetime.now()
<|code_end|>
. Use current file imports:
from datetime import datetime
from quotes.models import Author, Tag, Quote
and context (classes, functions, or code) from other files:
# Path: quotes/models.py
# class Author(models.Model):
# name = models.CharField(max_length=200)
# short_bio = models.TextField(max_length=500, null=True, blank=True)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
# avatar = ImageField(upload_to='authors',
# blank=True,
# null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('author', kwargs={'slug': self.slug})
#
# def get_avatar(self, size='60x60'):
# try:
# thumbnail = get_thumbnail(self.avatar,
# size,
# crop='center',
# quality=70)
# if thumbnail:
# return thumbnail.url
# except ThumbnailError:
# return None
#
# class Tag(models.Model):
# name = models.CharField(max_length=100)
# slug = models.SlugField(max_length=100, blank=True)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['name']
#
# def __unicode__(self):
# return self.name
#
# def get_absolute_url(self):
# return reverse('tag', kwargs={'slug': self.slug})
#
# class Quote(models.Model):
# body = models.TextField()
# authors = models.ManyToManyField(Author)
# tags = models.ManyToManyField(Tag, blank=True, null=True)
# slug = models.SlugField(max_length=100, blank=True)
# publish_date = models.DateTimeField(default=datetime.now)
# source = models.TextField(null=True, blank=True)
# featured = models.BooleanField(default=False)
# uuid = models.CharField(max_length=100, blank=True, null=True)
#
# class Meta:
# ordering = ['-publish_date']
#
# def __unicode__(self):
# return self.body
#
# def get_absolute_url(self):
# return reverse('quote', kwargs={'uuid': self.uuid})
#
# def serialize(self):
# return {
# 'body': self.body,
# 'url': self.get_absolute_url(),
# 'authors': [
# {
# 'name': author.name,
# 'url': author.get_absolute_url(),
# 'avatar': author.get_avatar(),
# }
# for author in self.authors.all()
# ],
# 'tags': [
# {
# 'name': tag.name,
# 'url': tag.get_absolute_url(),
# }
# for tag in self.tags.all()
# ]
# }
. Output only the next line. | quote = Quote.objects.create(body=body, publish_date=now) |
Predict the next line for this snippet: <|code_start|>
def delete_batch(objects):
if not objects:
return
for attempt in range(MAX_ATTEMPTS):
if attempt:
print "Attempt %d of %d will start in %d seconds." % (
attempt + 1, MAX_ATTEMPTS, attempt)
time.sleep(attempt)
print "Deleting %d objects (%s to %s):" % (
len(objects), objects[0].name(), objects[-1].name())
try:
db.delete(objects)
break
except Timeout:
print "*** Timeout ***"
if attempt + 1 == MAX_ATTEMPTS:
sys.exit(1)
del objects[:]
def main():
parser = OptionParser()
parser.add_option('--server', metavar='<hostname>',
default='scoretool.appspot.com',
help="connect to a different server")
(options, args) = parser.parse_args()
remote_api_stub.ConfigureRemoteDatastore(
'scoretool', '/remote_api', auth_func, options.server)
while True:
<|code_end|>
with the help of current file imports:
import os
import sys
import time
import getpass
import datetime
import ADNS
from common.appenginepatch.aecmd import setup_env
from adns import rr
from google.appengine.ext import db
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.api.datastore_errors import Timeout
from domains.models import Domain, Whois
from optparse import OptionParser
and context from other files:
# Path: domains/models.py
# MAX_NAME_LENGTH = 12
# DOMAIN_CHARS = 'abcdefghijklmnopqrstuvwxyz-0123456789'
# OBSOLETE_ATTRIBUTES = """
# scowl com net org dns_com dns_net dns_org dns_timestamp
# """.split()
# CACHE_ATTRIBUTES = """
# digits dashes
# english spanish french german
# prefix suffix score
# com net org biz info
# """.split()
# class Domain(db.Model):
# def __unicode__(self):
# def get_absolute_url(self):
# def before_put(self):
# def delete_obsolete_attributes(self):
# def update_counts(self):
# def language_scores_need_update(self):
# def update_language_scores(self):
# def popularity_scores_need_update(self):
# def update_popularity_scores(self):
# def get_best_prefix(self):
# def get_best_suffix(self):
# def update_score(self):
# def update_substrings(self):
# def to_cache(self):
# def from_cache(cls, key, values):
, which may contain function names, class names, or code. Output only the next line. | whois_keys = Whois.all(keys_only=True).fetch(BATCH_SIZE) |
Based on the snippet: <|code_start|> Find and remove for obselete attributes from previous versions
of the software.
"""
for attr in OBSOLETE_ATTRIBUTES:
if hasattr(self, attr):
delattr(self, attr)
def update_counts(self):
"""
Count digits and dashes.
"""
name = self.key().name()
self.length = len(name)
self.digits = self.dashes = 0
for char in name:
if '0' <= char <= '9':
self.digits += 1
elif char == '-':
self.dashes += 1
def language_scores_need_update(self):
for lang in 'english spanish french german'.split():
if not hasattr(self, lang):
return True
score = getattr(self, lang)
if score is None or score < 0.0 or score >= 1.0:
return True
return False
def update_language_scores(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from google.appengine.ext import db
from django.core.urlresolvers import reverse
from languages.utils import word_score
from languages import english, spanish, german, french
from prefixes.popular import prefix_score, suffix_score
and context (classes, functions, sometimes code) from other files:
# Path: languages/utils.py
# def word_score(word, triple_scores):
# triples = list(word_triples(word))
# result = 0.0
# for triple in triples:
# result += triple_scores.get(triple, 0.0)
# return result / len(triples)
. Output only the next line. | self.english = word_score(self.key().name(), english.TRIPLE_SCORES) |
Predict the next line after this snippet: <|code_start|> for name in names:
print name
print '""".split()'
max_score = float(length) / max(lengths)
print 'for index, name in enumerate(POPULAR_%sES[%d]):' % (
upper, length)
print ' %s_SCORES[name] = (%d - index) / %.1f' % (
upper, len(names), len(names) / max_score)
def score_function(variable, slice):
func = """
def prefix_score(name):
best_score = 0.0
best_prefix = ''
for length in range(2, min(6, len(name)) + 1):
prefix = name[slice]
score = PREFIX_SCORES.get(prefix, None)
if score > best_score:
best_score = score
best_prefix = prefix
return best_score, best_prefix
""".strip()
func = func.replace('PREFIX', variable)
func = func.replace('prefix', variable.lower())
func = func.replace('[slice]', slice)
print '\n\n' + func
def main():
<|code_end|>
using the current file's imports:
import os
import sys
from common.appenginepatch.aecmd import setup_env
from prefixes.models import Prefix, Suffix
and any relevant context from other files:
# Path: prefixes/models.py
# class Prefix(db.Expando):
# """
# Count all domains in the datastore that start with the same
# prefix. The key name is the prefix, with a leading dot and
# optional property 'resume' if incomplete.
# """
# length = db.IntegerProperty(required=True)
# count = db.IntegerProperty(required=True, default=0)
# com = db.IntegerProperty()
# percentage = db.FloatProperty()
# timestamp = db.DateTimeProperty()
#
# @classmethod
# def name_cut(cls, name, length=None):
# """
# >>> Prefix.name_cut('123456789')
# '123456789'
# >>> Prefix.name_cut('123456789', 3)
# '123'
# """
# if length is None:
# return name
# else:
# return name[:length]
#
# class Suffix(db.Expando):
# """
# Count all domains in the datastore that end with the same suffix.
# The key name is the suffix backwards, with a leading dot
# and optional property 'resume' if incomplete.
# """
# length = db.IntegerProperty(required=True)
# count = db.IntegerProperty(required=True, default=0)
# com = db.IntegerProperty()
# percentage = db.FloatProperty()
# timestamp = db.DateTimeProperty()
#
# @classmethod
# def name_cut(cls, name, length=None):
# """
# >>> Suffix.name_cut('123456789')
# '987654321'
# >>> Suffix.name_cut('123456789', 3)
# '987'
# """
# if length is None:
# return name[::-1]
# else:
# return name[::-1][:length]
. Output only the next line. | all_lengths(Prefix, LENGTHS) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.