rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print >>f, '\n f.close
print >> f, '\n f.close()
#ifndef GEANY_FUNCTIONS_H
def _get_superclass(self, c):
def _get_superclass(self, _object):
def _get_superclass(self, c): """ Python class base-finder (found on http://mail.python.org/pipermail/python-list/2002-November/173949.html)
@param c (object)
@param _object (object)
def _get_superclass(self, c): """ Python class base-finder (found on http://mail.python.org/pipermail/python-list/2002-November/173949.html)
if type(c) == types.ClassType: return c.__bases__[0].__name__
if type(_object) == types.ClassType: return _object.__bases__[0].__name__
def _get_superclass(self, c): """ Python class base-finder (found on http://mail.python.org/pipermail/python-list/2002-November/173949.html)
return c.__mro__[1].__name__ except Exception, e:
return _object.__mro__[1].__name__ except IndexError:
def _get_superclass(self, c): """ Python class base-finder (found on http://mail.python.org/pipermail/python-list/2002-November/173949.html)
return '(' + string.join(specs, ', ') + ')'
return ', '.join(specs)
def _formatargspec(self, args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=inspect.joinseq): """Format an argument spec from the 4 values returned by getargspec.
except TypeError, KeyError:
except (TypeError, KeyError):
def _add_tag(self, obj, tag_type, parent=''): """ Verify the found tag name and if it is valid, add it to the list
except Exception, e:
except IOError, e: print '%s: %s' % (filename, e) return except Exception:
def process_file(self, filename): """ Read the file specified by filename and look for class and function definitions
continue;
continue
def process_file(self, filename): """ Read the file specified by filename and look for class and function definitions
fp = open(filename) for line in fp:
filep = open(filename) for line in filep:
def process_file(self, filename): """ Read the file specified by filename and look for class and function definitions
fp.close()
filep.close()
def process_file(self, filename): """ Read the file specified by filename and look for class and function definitions
fp = open(filename, 'wb') fp.write(
target_file = open(filename, 'wb') target_file.write(
def write_to_file(self, filename): """ Sort the found tags and write them into the file specified by filename
for s in result: if not s == '\n': fp.write(s) fp.close()
for symbol in result: if not symbol == '\n': target_file.write(symbol) target_file.close()
def write_to_file(self, filename): """ Sort the found tags and write them into the file specified by filename
try: firstLine = str(generators.next()) except Exception: s = format_exc() yield 'HTTP/1.0 500 Internal Server Error\r\n\r\n' yield str(s) return if not firstLine.startswith('HTTP/1.'): contentType = 'text/html' if path.endswith('.xml'): contentType = 'text/xml' yield 'HTTP/1.0 200 Ok\r\nContent-Type: %s; charset=utf-...
while True: try: firstValue = generators.next() if callable(firstValue): yield firstValue else: firstLine = str(firstValue) if not firstLine.startswith('HTTP/1.'): contentType = 'text/html' if path.endswith('.xml'): contentType = 'text/xml' yield 'HTTP/1.0 200 Ok\r\nContent-Type: %s; charset=utf-8\r\n\r\n' % contentTy...
def handleRequest(self, scheme='', netloc='', path='', query='', fragments='', arguments={}, Headers={}, **kwargs):
yield str(line)
yield line if callable(line) else str(line)
def handleRequest(self, scheme='', netloc='', path='', query='', fragments='', arguments={}, Headers={}, **kwargs):
}
} limit 5
def test_federation (self): F = SWObjects.AtomFactory() sparqlParser = SWObjects.SPARQLfedDriver("", F) mapSetParser = SWObjects.MapSetDriver("", F) queryMapper = SWObjects.ChainingMapper(F, None) sparqlParser.unnestTree = True
print "MS nodeshare: ", ms.nodeShare
def test_federation (self): F = SWObjects.AtomFactory() sparqlParser = SWObjects.SPARQLfedDriver("", F) mapSetParser = SWObjects.MapSetDriver("", F) queryMapper = SWObjects.ChainingMapper(F, None) sparqlParser.unnestTree = True
transformed = queryMapper.map(query) print transformed.toString() canon = SWObjects.SWObjectCanonicalizer(F) print "canon: ", canon transformed.express(canon) ourlast = canon.last print "our last: ", ourlast transformedNorm = ourlast.operation print transformedNorm.toString() agent = SWObjects.WEBagent_boostASIO()...
try: transformed = queryMapper.map(query) canon = SWObjects.SWObjectCanonicalizer(F) transformed.express(canon) ourlast = canon.last transformedNorm = ourlast.operation agent = SWObjects.WEBagent_boostASIO() xmlParser = SWObjects.SAXparser_expat() DB = SWObjects.RdfDB(agent, xmlParser) rs = SWObjects.ResultSet(F) tr...
def test_federation (self): F = SWObjects.AtomFactory() sparqlParser = SWObjects.SPARQLfedDriver("", F) mapSetParser = SWObjects.MapSetDriver("", F) queryMapper = SWObjects.ChainingMapper(F, None) sparqlParser.unnestTree = True
ctx.set_source_rgb(255,255,255)
ctx.set_source_rgb(1,1,1)
def __init__(self, image=None, # PIL image size=None, ctx=None, imageType=None, # determines file type fileName=None, # if set determines output file name ): """ Canvas can be used in four modes: 1) using the supplied PIL image 2) using the supplied cairo context ctx 3) writing to a file fileName with image type imag...
"raw","RGBA",0,1)
"raw","BGRA",0,1)
def flush(self): """temporary interface, must be splitted to different methods, (elif self.imageType == "png":)""" if self.fileName and self.imageType=='png': self.surface.write_to_png(self.fileName) elif self.image is not None: self.image.fromstring(self.surface.get_data(), "raw","RGBA",0,1) self.surface.finish() elif...
color = (int(color[0]*255),int(color[1]*255),int(color[2]*255))
def convertColor(color): color = (int(color[0]*255),int(color[1]*255),int(color[2]*255)) return color
imgd = image.tostring()
imgd = image.tostring("raw","BGRA")
def __init__(self, image=None, # PIL image size=None, ctx=None, imageType=None, # determines file type fileName=None, # if set determines output file name ): """ Canvas can be used in four modes: 1) using the supplied PIL image 2) using the supplied cairo context ctx 3) writing to a file fileName with image type imag...
def convertColor(color): return color
def flush(self): """temporary interface, must be splitted to different methods, (elif self.imageType == "png":)""" if self.fileName and self.imageType=='png': self.surface.write_to_png(self.fileName) elif self.image is not None: # on linux at least it seems like the PIL images are BGRA, not RGBA: self.image.fromstring(...
color = convertColor(color)
def addCanvasLine(canvas,p1,p2,color=(0,0,0),color2=None,**kwargs): canvas.ctx.set_line_width(kwargs.get('linewidth',1)) if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. color = convertColor(color) canvas.ctx.set_source_rgb(*color) _doLine(canvas,p1,mp,**kwargs) canvas.ctx.stroke() color2 = convertCo...
color2 = convertColor(color2)
def addCanvasLine(canvas,p1,p2,color=(0,0,0),color2=None,**kwargs): canvas.ctx.set_line_width(kwargs.get('linewidth',1)) if color2 and color2!=color: mp = (p1[0]+p2[0])/2.,(p1[1]+p2[1])/2. color = convertColor(color) canvas.ctx.set_source_rgb(*color) _doLine(canvas,p1,mp,**kwargs) canvas.ctx.stroke() color2 = convertCo...
color = convertColor(color)
def addCanvasText(canvas,text,pos,font,color=(0,0,0),**kwargs): color = convertColor(color) canvas.ctx.select_font_face("Georgia", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) canvas.ctx.set_font_size(font.size) w,h=canvas.ctx.text_extents(text)[2:4] bw,bh=w*1.8,h*1.4 dPos = pos[0]-bw/2.,pos[1]-bh/2. bgColor=kwargs...
bgColor = convertColor(bgColor)
def addCanvasText(canvas,text,pos,font,color=(0,0,0),**kwargs): color = convertColor(color) canvas.ctx.select_font_face("Georgia", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) canvas.ctx.set_font_size(font.size) w,h=canvas.ctx.text_extents(text)[2:4] bw,bh=w*1.8,h*1.4 dPos = pos[0]-bw/2.,pos[1]-bh/2. bgColor=kwargs...
color = convertColor(color)
def addCanvasPolygon(canvas,ps,color=(0,0,0),**kwargs): dps = [] color = convertColor(color) canvas.ctx.set_source_rgb(*color) canvas.ctx.move_to(ps[0][0],ps[0][1]) for p in ps[1:]: canvas.ctx.line_to(p[0],p[1]) canvas.ctx.close_path() canvas.ctx.fill()
from aggdraw import Draw2
from aggdraw import Draw
def MolToImage(mol,size=(300,300),kekulize=True, wedgeBonds=True,highlightAtoms=[]): """ returns a PIL image containing a drawing of the molecule """ if not mol: raise ValueError,'Null molecule provided' import MolDrawing try: from aggdraw import Draw2 import Image MolDrawing.registerCanvas('agg') Canvas = Draw useAGG=...
m = Chem.MolFromSmiles(smi)
m = Chem.MolFromSmiles(spelling)
def _testSpellings(self,smiList): for smi,spellings in smiList: m = Chem.MolFromSmiles(smi) canSmi = Chem.MolToSmiles(m) for spelling in spellings: m = Chem.MolFromSmiles(smi) trySmi = Chem.MolToSmiles(m) assert canSmi==trySmi,'Non-canonical: mol %s gave %s (should be %s)'%(spelling,trySmi,canSmi) m2 = Chem.MolFromSmil...
'O=[N+1]([O--1])c1ccc(cc1)[N+1]([O--1])=O', '[O--1][N+1](=O)c1ccc(cc1)[N+1]([O--1])=O')),
'O=[N+1]([O-1])c1ccc(cc1)[N+1]([O-1])=O', '[O-1][N+1](=O)c1ccc(cc1)[N+1]([O-1])=O')),
def testProblems(self): " testing molecules which have been problematic " smiList = [ ('[Al+3]CCC',('CCC[Al+3]','C(C)(C[Al+3])' ) ), ('C(=O)(Cl)CC(=O)Cl',('ClC(CC(Cl)=O)=O','C(Cl)(=O)CC(=O)Cl','C(Cl)(=O)CC(Cl)=O')), ('C(=O)(Cl)c1ccc(C(=O)Cl)cc1',('O=C(Cl)c1ccc(cc1)C(Cl)=O','C(Cl)(=O)C1=CC=C(C=C1)C(Cl)=O', 'ClC(=O)c1ccc...
jsonObject["id"] = entry.id.text[indexOfSlash:]
jsonObject["id"] = entry.id.text[indexOfSlash+1:]
def write_feed_to_file(gd_client): jsonFile = open('my/{0}.contacts.json'.format(GetUIDHash(gd_client)), 'w') query = gdata.contacts.service.ContactsQuery() query.max_results = 3000 feed = gd_client.GetContactsFeed(query.ToUri()) for i, entry in enumerate(feed.entry): jsonObject = {} indexOfSlash = entry.id.text.rfind(...
hosted_image_binary = gd_client.GetPhoto(entry) if hosted_image_binary: image_file = open('my/photos/{0}.jpg'.format(jsonObject["id"]), 'wb') image_file.write(hosted_image_binary) image_file.close()
try: hosted_image_binary = gd_client.GetPhoto(entry) if hosted_image_binary: image_file = open('my/photos/{0}.jpg'.format(jsonObject["id"]), 'wb') image_file.write(hosted_image_binary) image_file.close() except gdata.service.RequestError: pass
def write_feed_to_file(gd_client): jsonFile = open('my/{0}.contacts.json'.format(GetUIDHash(gd_client)), 'w') query = gdata.contacts.service.ContactsQuery() query.max_results = 3000 feed = gd_client.GetContactsFeed(query.ToUri()) for i, entry in enumerate(feed.entry): jsonObject = {} indexOfSlash = entry.id.text.rfind(...
feed = gd_client.GetContactsFeed()
query = gdata.contacts.service.ContactsQuery() query.max_results = 3000 feed = gd_client.GetContactsFeed(query.ToUri())
def write_feed_to_file(gd_client): jsonFile = open('my/{0}.contacts.json'.format(GetUIDHash(gd_client)), 'w') feed = gd_client.GetContactsFeed() for i, entry in enumerate(feed.entry): jsonObject = {} jsonObject["id"] = entry.id.text[-16:] print '%s %s' % (i+1, entry.title.text) jsonObject["name"] = entry.title.text if...
jsonObject["id"] = entry.id.text[-16:]
indexOfSlash = entry.id.text.rfind("/") jsonObject["id"] = entry.id.text[indexOfSlash:]
def write_feed_to_file(gd_client): jsonFile = open('my/{0}.contacts.json'.format(GetUIDHash(gd_client)), 'w') feed = gd_client.GetContactsFeed() for i, entry in enumerate(feed.entry): jsonObject = {} jsonObject["id"] = entry.id.text[-16:] print '%s %s' % (i+1, entry.title.text) jsonObject["name"] = entry.title.text if...
self.dbg.SetAsync(True)
def run(self): print "Running MyListeningThread:", self count = 0 # Let's only try at most 3 times to retrieve any kind of event. while not count > 3: if listener.WaitForEvent(5, event): print "Got a valid event:", event print "Event type:", event.GetType() print "Event broadcaster:", event.GetBroadcaster().GetName() r...
self.process.Continue()
self.process.Kill()
def run(self): print "Running MyListeningThread:", self count = 0 # Let's only try at most 3 times to retrieve any kind of event. while not count > 3: if listener.WaitForEvent(5, event): print "Got a valid event:", event print "Event type:", event.GetType() print "Event broadcaster:", event.GetBroadcaster().GetName() r...
self.runCmd("image dump symtab a.out")
self.runCmd("image dump symtab -s address a.out")
def order_file(self): """Test debug symbols follow the correct order by the order file.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
def test_broadcast_event_with_dsym(self): """Exercise SBBroadcaster.BroadcastEvent() API."""
def test_add_listener_to_broadcaster_dsym(self): """Exercise some SBBroadcaster APIs."""
def test_broadcast_event_with_dsym(self): """Exercise SBBroadcaster.BroadcastEvent() API.""" self.buildDsym() self.do_broadcast_event()
self.do_broadcast_event() @python_api_test def test_broadcast_event_with_dwarf(self): """Exercise SBBroadcaster.BroadcastEvent() API."""
self.do_add_listener_to_broadcaster() @python_api_test def test_add_listener_to_broadcaster_dwarf(self): """Exercise some SBBroadcaster APIs."""
def test_broadcast_event_with_dsym(self): """Exercise SBBroadcaster.BroadcastEvent() API.""" self.buildDsym() self.do_broadcast_event()
self.do_broadcast_event()
self.do_add_listener_to_broadcaster()
def test_broadcast_event_with_dwarf(self): """Exercise SBBroadcaster.BroadcastEvent() API.""" self.buildDwarf() self.do_broadcast_event()
def do_broadcast_event(self): """Get the broadcaster associated with the process and exercise BroadcastEvent API."""
def do_add_listener_to_broadcaster(self): """Get the broadcaster associated with the process and wait for broadcaster events."""
def do_broadcast_event(self): """Get the broadcaster associated with the process and exercise BroadcastEvent API.""" exe = os.path.join(os.getcwd(), "a.out")
if listener.WaitForEvent(5, event):
if listener.WaitForEventForBroadcasterWithType(5, broadcaster, lldb.SBProcess.eBroadcastBitStateChanged, event):
def run(self): #print "Running MyListeningThread:", self
substrs = ["(MyString *) self",
substrs = ["(MyString) *self",
def data_type_and_expr_objc(self): """Lookup objective-c data types and evaluate expressions.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
if self.contains_term(t):
try:
def similar_terms(self, t): """ Returns an iterable over the indices of similar terms. Raises KeyError if the term is not found. """ terms = self.terms
i = self.lookup_term_index(t)
i = self.lookup_term_index(tv) except KeyError: i = None if i is not None:
def similar_terms(self, t): """ Returns an iterable over the indices of similar terms. Raises KeyError if the term is not found. """ terms = self.terms
for i,st in enumerate(self.terms): if terms[i] in t:
for i,st in enumerate(terms): if st in t:
def similar_terms(self, t): """ Returns an iterable over the indices of similar terms. Raises KeyError if the term is not found. """ terms = self.terms
elif t in terms[i]:
elif t in st:
def similar_terms(self, t): """ Returns an iterable over the indices of similar terms. Raises KeyError if the term is not found. """ terms = self.terms
modification_time = time.localtime(os.path.getmtime(self.path)) return time.strftime("%a, %d %b %Y %H:%M:%S %Z", modification_time)
modification_time = time.gmtime(os.path.getmtime(self.path)) return time.strftime("%a, %d %b %Y %H:%M:%S +0000", modification_time)
def last_modified(self): """Get the last time the calendar has been modified.
answer = self._calendar.read().encode(self._encoding)
answer = self._calendar.text.encode(self._encoding)
def do_GET(self): """Manage GET request.""" answer = self._calendar.read().encode(self._encoding)
items = items or self.items
items = items if items is not None else self.items
def write(self, headers=None, items=None): """Write calendar with given parameters.""" headers = headers or self.headers or ( Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"), Header("VERSION:2.0")) items = items or self.items
elements = [calendar]
items = [calendar]
def propfind(path, xml_request, calendar, depth, request): """Read and answer PROPFIND requests. Read rfc4918-9.1 for info. """ # Reading request root = ET.fromstring(xml_request) prop_element = root.find(_tag("D", "prop")) prop_list = prop_element.getchildren() props = [prop.tag for prop in prop_list] # Writing an...
elements = [calendar] + calendar.events + calendar.todos
items = [calendar] + calendar.events + calendar.todos
def propfind(path, xml_request, calendar, depth, request): """Read and answer PROPFIND requests. Read rfc4918-9.1 for info. """ # Reading request root = ET.fromstring(xml_request) prop_element = root.find(_tag("D", "prop")) prop_list = prop_element.getchildren() props = [prop.tag for prop in prop_list] # Writing an...
elements = [calendar] + calendar.events + calendar.todos for element in elements: is_calendar = isinstance(element, ical.Calendar)
items = [calendar] + calendar.events + calendar.todos for item in items: is_calendar = isinstance(item, ical.Calendar)
def propfind(path, xml_request, calendar, depth, request): """Read and answer PROPFIND requests. Read rfc4918-9.1 for info. """ # Reading request root = ET.fromstring(xml_request) prop_element = root.find(_tag("D", "prop")) prop_list = prop_element.getchildren() props = [prop.tag for prop in prop_list] # Writing an...
href.text = path if is_calendar else "%s/%s" % (path, element.name)
href.text = path if is_calendar else "%s/%s" % (path, item.name)
def propfind(path, xml_request, calendar, depth, request): """Read and answer PROPFIND requests. Read rfc4918-9.1 for info. """ # Reading request root = ET.fromstring(xml_request) prop_element = root.find(_tag("D", "prop")) prop_list = prop_element.getchildren() props = [prop.tag for prop in prop_list] # Writing an...
element.text = element.etag
element.text = item.etag
def propfind(path, xml_request, calendar, depth, request): """Read and answer PROPFIND requests. Read rfc4918-9.1 for info. """ # Reading request root = ET.fromstring(xml_request) prop_element = root.find(_tag("D", "prop")) prop_list = prop_element.getchildren() props = [prop.tag for prop in prop_list] # Writing an...
content_type = self.headers["Content-Type"]
content_type = self.headers.get("Content-Type", None)
def _decode(self, text): """Try to decode text according to various parameters.""" # List of charsets to try charsets = []
items = self._calendar.timezones
def do_HEAD(self): """Manage HEAD request.""" item_name = xmlutils.name_from_path(self.path) if item_name: # Get calendar item items = self._calendar.timezones item = self._calendar.get_item(item_name) items.append(item) answer_text = ical.serialize( headers=self._calendar.headers, items=items) etag = item.etag else: #...
items.append(item) answer_text = ical.serialize( headers=self._calendar.headers, items=items) etag = item.etag
if item: items = self._calendar.timezones items.append(item) answer_text = ical.serialize( headers=self._calendar.headers, items=items) etag = item.etag else: self.send_response(client.GONE) return
def do_HEAD(self): """Manage HEAD request.""" item_name = xmlutils.name_from_path(self.path) if item_name: # Get calendar item items = self._calendar.timezones item = self._calendar.get_item(item_name) items.append(item) answer_text = ical.serialize( headers=self._calendar.headers, items=items) etag = item.etag else: #...
if not os.path.exists(self.path): self.write()
def __init__(self, path): """Initialize the calendar with ``cal`` and ``user`` parameters.""" # TODO: Use properties from the calendar configuration self.encoding = "utf-8" self.owner = path.split("/")[0] self.path = os.path.join(FOLDER, path.replace("/", os.path.sep)) # Create calendar if needed, useful for ``self.las...
version="0.1",
version="0.2",
def _should_remove(filename): return (os.path.splitext(filename)[1] == ".pyc" or os.path.splitext(filename)[1] == ".pyo" or filename.endswith("~") or (filename.startswith("#") and filename.endswith("#")))
k += 1
def Solve(self, **kwargs): """ Solve the trust-region subproblem.
def store(self, iter, new_s, new_y):
def store(self, new_s, new_y):
def store(self, iter, new_s, new_y): # Simply swap s and y. InverseLBFGS.store(self, iter, new_y, new_s)
InverseLBFGS.store(self, iter, new_y, new_s)
InverseLBFGS.store(self, new_y, new_s)
def store(self, iter, new_s, new_y): # Simply swap s and y. InverseLBFGS.store(self, iter, new_y, new_s)
iter = kwargs.get('iter', None) if iter is None: raise ValueError, 'Please specify iteration number.' Hv = self.ldfp.matvec(iter, v)
Hv = self.ldfp.matvec(v)
def hprod(self, z, v, **kwargs): """ Compute the matrix-vector product between the limited-memory DFP approximation kept in storage and the vector `v`. The argument `z` is ignored and is only present for compatibility with the original `hprod`. """ self.Hprod += 1 iter = kwargs.get('iter', None) if iter is None: raise ...
return x = zeros(n)
x_is_zero = True istop = 0
def solve(self, rhs, itnlim=0, damp=0.0, atol=1.0e-6, btol=1.0e-7, conlim=1.0e+8, radius=None, show=False, wantvar=False): """ Solve the linear system, linear least-squares problem or regularized linear least-squares problem with specified parameters. All return values below are stored in members of the same name.
while itn < itnlim:
while itn < itnlim and not x_is_zero:
def solve(self, rhs, itnlim=0, damp=0.0, atol=1.0e-6, btol=1.0e-7, conlim=1.0e+8, radius=None, show=False, wantvar=False): """ Solve the linear system, linear least-squares problem or regularized linear least-squares problem with specified parameters. All return values below are stored in members of the same name.
test3 = 1.0 / acond
if acond == 0.0: test3 = inf else: test3 = 1.0 / acond
def solve(self, rhs, itnlim=0, damp=0.0, atol=1.0e-6, btol=1.0e-7, conlim=1.0e+8, radius=None, show=False, wantvar=False): """ Solve the linear system, linear least-squares problem or regularized linear least-squares problem with specified parameters. All return values below are stored in members of the same name.
self.lowerB = np.array(self.nlp.lowerB, dtype=np.int) self.upperB = np.array(self.nlp.upperB, dtype=np.int) self.rangeB = np.array(self.nlp.rangeB, dtype=np.int) self.nlowerB = nlp.nlowerB self.nupperB = nlp.nupperB self.nrangeB = nlp.nrangeB
self.lowerB = np.array(nlp.lowerB) self.upperB = np.array(nlp.upperB) self.rangeB = np.array(nlp.rangeB) self.rlB = np.arange(nlp.nlowerB) self.ruB = np.arange(nlp.nupperB) self.rrB = np.arange(nlp.nrangeB)
def __init__(self, nlp, **kwargs):
self.ndual = self.nlowerB + self.nupperB + 2 * self.nrangeB
self.ndual = nlp.nlowerB + nlp.nupperB + 2 * nlp.nrangeB
def __init__(self, nlp, **kwargs):
n = self.nlp.n Lvar = self.nlp.Lvar ; Uvar = self.nlp.Uvar lB = self.lowerB ; uB = self.upperB ; rB = self.rangeB nlB = self.nlowerB ; nuB = self.nupperB ; nrB = self.nrangeB
nlp = self.nlp ; n = nlp.n Lvar = nlp.Lvar ; Uvar = nlp.Uvar lB = nlp.lowerB ; uB = nlp.upperB ; rB = nlp.rangeB nlB = nlp.nlowerB ; nuB = nlp.nupperB ; nrB = nlp.nrangeB
def obj(self, x, z, **kwargs): """ Evaluate the primal-dual merit function at (x,z):
g = np.empty(n + self.ndual) if gf is None: g[:n] = self.nlp.grad(x) else: g[:n] = gf.copy() if check_optimal: res, self.optimal = self.AtOptimality(x, z, g=g[:n]) self.dRes = res[0] ; self.cRes = res[2] ; self.pRes = res[4]
def grad(self, x, z, **kwargs): """ Evaluate the gradient of the primal-dual merit function at (x,z). The gradient of the objective function at `x`, if known, can be passed via the keyword argument `g`. See :meth:`PDMerit` for a description of `z`. """ mu = kwargs.get('mu', self.mu) check_optimal = kwargs.get('check_op...
g[lB] += -2 * mu / slB + zlB g[uB] += 2 * mu / suB + zuB g[rB] += -2 * mu / srlB + zrlB g[rB] += 2 * mu / sruB + zruB n1 = nlB ; n2 = n1 + nuB ; n3 = n2 + nrB g[n:n+n1] = slB - mu/zlB g[n+n1:n+n2] = suB - mu/zuB g[n+n2:n+n3] = srlB - mu/zrlB g[n+n3:] = sruB - mu/zruB return g def primal_hprod(self, x,...
Hp = np.zeros(n + self.ndual)
def grad(self, x, z, **kwargs): """ Evaluate the gradient of the primal-dual merit function at (x,z). The gradient of the objective function at `x`, if known, can be passed via the keyword argument `g`. See :meth:`PDMerit` for a description of `z`. """ mu = kwargs.get('mu', self.mu) check_optimal = kwargs.get('check_op...
self.maxiter = kwargs.get('maxiter', max(100, 2*self.nlp.n))
self.maxiter = kwargs.get('maxiter', max(100,2*self.merit.nlp.n))
def __init__(self, merit, TR, TrSolver, **kwargs): """ Solve the bound-constrained problem
n = self.nlp.n ; ndual = self.ndual self.B = self.PDHessTemplate()
def __init__(self, merit, TR, TrSolver, **kwargs): """ Solve the bound-constrained problem
def StartingPoint(self, **kwargs):
def get_feasible_point(self, **kwargs):
def StartingPoint(self, **kwargs): """ Compute a strictly feasible initial primal-dual estimate (x,z). By default, x is taken as the starting point given in `nlp` and moved strictly into the bounds, and z is taken as the vector of ones. """ n = self.nlp.n Lvar = self.nlp.Lvar ; lB = self.lowerB Uvar = self.nlp.Uvar ; u...
By default, x is taken as the starting point given in `nlp` and moved strictly into the bounds, and z is taken as the vector of ones. """ n = self.nlp.n Lvar = self.nlp.Lvar ; lB = self.lowerB Uvar = self.nlp.Uvar ; uB = self.upperB ; rB = self.rangeB
By default, x is taken as the starting point given in `nlp` and moved strictly inside the bounds, and z is taken as the vector of ones. """ nlp = self.merit.nlp n = nlp.n Lvar = nlp.Lvar ; lB = nlp.lowerB Uvar = nlp.Uvar ; uB = nlp.upperB ; rB = nlp.rangeB
def StartingPoint(self, **kwargs): """ Compute a strictly feasible initial primal-dual estimate (x,z). By default, x is taken as the starting point given in `nlp` and moved strictly into the bounds, and z is taken as the vector of ones. """ n = self.nlp.n Lvar = self.nlp.Lvar ; lB = self.lowerB Uvar = self.nlp.Uvar ; u...
x = self.nlp.x0[:]
x = nlp.x0[:]
def StartingPoint(self, **kwargs): """ Compute a strictly feasible initial primal-dual estimate (x,z). By default, x is taken as the starting point given in `nlp` and moved strictly into the bounds, and z is taken as the vector of ones. """ n = self.nlp.n Lvar = self.nlp.Lvar ; lB = self.lowerB Uvar = self.nlp.Uvar ; u...
z = np.ones(self.ndual)
z = np.ones(self.merit.ndual)
def StartingPoint(self, **kwargs): """ Compute a strictly feasible initial primal-dual estimate (x,z). By default, x is taken as the starting point given in `nlp` and moved strictly into the bounds, and z is taken as the vector of ones. """ n = self.nlp.n Lvar = self.nlp.Lvar ; lB = self.lowerB Uvar = self.nlp.Uvar ; u...
def PrimalMultipliers(self, x, **kwargs): """ Return the vector of primal multipliers at `x`. The value of the barrier parameter used can either be supplied using the keyword argument `mu` or the current value of the instance is used.
def primal_multipliers(self, x, **kwargs): """ Return the vector of primal multipliers at `x`. The value of the barrier parameter used can either be supplied using the keyword argument `mu` or the current value of the instance is used.
def PrimalMultipliers(self, x, **kwargs): """ Return the vector of primal multipliers at `x`. The value of the barrier parameter used can either be supplied using the keyword argument `mu` or the current value of the instance is used. """ mu = kwargs.get('mu', self.mu) Lvar = self.nlp.Lvar ; Uvar = self.nlp.Uvar lB = s...
from nlpy.optimize.tr.trustregion import TrustRegionFramework, TrustRegionCG
def grad(self, xz, **kwargs): nx = self.nlp.n return PrimalDualMeritFunction.grad(self, xz[:nx], xz[nx:], **kwargs)
TR = TrustRegionFramework(Delta = 1.0, eta1 = 0.0001, eta2 = 0.95, gamma1 = 1.0/3, gamma2 = 2.5) TRIP = PrimalDualInteriorPointFramework( pdmerit, TR, TrustRegionCG, silent = False,
def grad(self, xz, **kwargs): nx = self.nlp.n return PrimalDualMeritFunction.grad(self, xz[:nx], xz[nx:], **kwargs)
(x, z) = (pdmerit.x, pdmerit.z)
) (x, z) = TRIP.get_feasible_point()
def grad(self, xz, **kwargs): nx = self.nlp.n return PrimalDualMeritFunction.grad(self, xz[:nx], xz[nx:], **kwargs)
derchk.check(verbose=True, hess=False, jac=False, chess=False)
derchk.check(verbose=True, hess=True, jac=False, chess=False)
def grad(self, xz, **kwargs): nx = self.nlp.n return PrimalDualMeritFunction.grad(self, xz[:nx], xz[nx:], **kwargs)
def _write( self, msg ): sys.stderr.write( self.prefix + msg )
def _write( self, msg ): sys.stderr.write( self.prefix + msg )
def Factorize( self ):
def _write(self, msg): sys.stderr.write(self.prefix + msg) def Factorize(self):
def Factorize( self ): """ Assemble projection matrix and factorize it
from nlpy.optimize.solvers import lbfgs
def Solve(self, **kwargs):
self.lbfgs = lbfgs_class.LbfgsUpdate(nlp.n, npairs=self.npairs)
self.lbfgs = lbfgs.InverseLBFGS(nlp.n, npairs=self.npairs)
def __init__(self, nlp, TR, TrSolver, **kwargs):
self.silent = kwargs.get('silent', False) self.ny = kwargs.get('ny', False)
self.silent = kwargs.get('silent', False) self.ny = kwargs.get('ny', False) self.nbk = kwargs.get('nbk', 5)
def __init__(self, nlp, TR, TrSolver, **kwargs):
self.nIterNonMonotone = kwargs.get('nIterNonMonotone', 25)
self.nIterNonMono = kwargs.get('nIterNonMono', 25)
def __init__(self, nlp, TR, TrSolver, **kwargs):
if l == self.nIterNonMonotone:
if l == self.nIterNonMono:
def Solve(self, **kwargs):
while bk < 5 and f_trial >= self.f + 1.0e-4 * self.alpha * slope:
while bk < self.nbk and \ f_trial >= self.f + 1.0e-4 * self.alpha * slope:
def Solve(self, **kwargs):
stoptol = self.nlp.stop_d * max(1.0, norms.norm2(self.x))
def solve(self):
def to_boundary(self, s, p, Delta, ss = None): """ Given vectors s and p and a trust-region radius Delta > 0, this function returns the positive scalar sigma such that
def to_boundary(self, s, p, Delta, ss=None): """ Given vectors `s` and `p` and a trust-region radius `Delta` > 0, return the positive scalar sigma such that
def to_boundary(self, s, p, Delta, ss = None): """ Given vectors s and p and a trust-region radius Delta > 0, this function returns the positive scalar sigma such that
in Euclidian norm. If known, supply optional argument ss whose value should be the squared Euclidian norm of argument s. """
in Euclidian norm. If known, supply optional argument `ss` whose value should be the squared Euclidian norm of argument `s`. """ if Delta is None: raise ValueError, 'Radius value must be positive number.'
def to_boundary(self, s, p, Delta, ss = None): """ Given vectors s and p and a trust-region radius Delta > 0, this function returns the positive scalar sigma such that
self.infiniteDescentDir = p onBoundary = True
self.infDescent = True self.dir = p
def Solve( self ): if self.A is not None: if self.factorize and not self.factorized: self.Factorize() if self.b is not None: self.FindFeasible()
z = np.zeros(self.m) ; z[i] = 1
z = np.zeros(self.m) ; z[i] = -1
def hiprod(self, i, v, **kwargs): """ Evaluate matrix-vector product Hi(x) * v. Returns a Numpy array. """ z = np.zeros(self.m) ; z[i] = 1 self.Hprod += 1 return _amplpy.H_prod(z, v, 0.)
if (pHp <= 0 or alpha > sigma) and Delta is not None:
if Delta is not None and (pHp <= 0 or alpha > sigma):
def Solve(self, **kwargs): """ Solve the trust-region subproblem. """ n = self.n g = self.g matvec = self.matvec if matvec is None: H = self.H prec = self.prec
self.stepNorm = self.xNorm2
self.stepNorm = 0.0
def __init__( self, c, **kwargs ): """ Solve the equality-constrained quadratic programming problem
self.xNorm2 = self.stepNorm = xNorm2
self.xNorm2 = xNorm2 self.stepNorm = sqrt(xNorm2)
def Solve(self): if self.A is not None: if self.factorize and not self.factorized: self.Factorize() if self.b is not None: self.FindFeasible()