Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- shared/package-files/08/0802392a2a1c49abdd877f290daf0f0f7ed8670051c793672ff8e3dd167c860d/_sparse_softmax_compositeexplicitautograd_dispatch.hAdded+24
- shared/package-files/08/080568ed7a3da54d12410ffe081a28a8b6cc6948e0aae82daaf4145c07262eb3/models.pyiAdded+21
- shared/package-files/08/0806ef3662b840225106c5f6e7fca2d887bd241dfbc600ec6219a67b2dfe11ff/quantize_per_tensor_native.hAdded+26
- shared/package-files/08/08199dfe00ed822a87d9276841094e05bb4e11ea6b5ad33af18ddfd6c4aa3df2/fontchooser.tclAdded+456
- shared/package-files/08/081ee3b785d24720ac3ab9bbaf7ef597fcb7c9af7e00ddb017b048b575d06825/code.pyAdded+755
- shared/package-files/08/081ef817a8a64aebd16fb7dfceda03dd5a0884c67a72e8add1416bf9da318a69/grammar_analysis.pyAdded+203
- shared/package-files/08/0824daa4f11e187f7b88ab15b0f4855f441195175d4e353f4b9f31ac72f5f5b4/executionengine.pyAdded+330
- shared/package-files/08/0824e40a2e60f1757e0c94f1f125c26a2111d250d97d98e672afac7da09a27ec/add_cuda_dispatch.hAdded+26
- shared/package-files/08/0827b1cd3d6592c4c6fd6bc6bc79faf82b9677f657a05be23469c165dfe113b6/test_mstats_extras.pyAdded+172
- shared/package-files/08/08291913035c258ae6872b8156bf782b03058c7b1b2fa98e259d9fe5a19c0115/diffgeom.pyAdded+2273
- shared/package-files/08/0831778a6e88c5d63732ee9fc114269121019974b79105489d0e29957b285fd7/_datasource.pyAdded+704
- shared/package-files/08/08343747764e4a5814262793cf4d652057a7913863c5950d43297e8e1fdac5b6/contentAdded+17
- shared/package-files/08/08356ef929f04501b2ccaa77effb8f1f36c200703c6a68952f2b86813558c723/__init__.pyAdded+4
- shared/package-files/08/08358a652ec2a49cb967f8a7aaee8b2cf0d5a67856a2e216864ef0e3e335c0c3/test_numpy_generators.pyAdded+38
- shared/package-files/08/083853b6609e1e609b4a6ed178271ec92f73d841a2bdf6ecfe905b34be04ebb2/istft.hAdded+30
- shared/package-files/08/083afd847ede83d6e66eb74533613f08ea57e1e3fc22418ea5a41e38d025c9bb/__init__.pyAdded+7
- shared/package-files/08/083e8c7f3213c8279ab0b5010c25f3265c911ca7489c234cd04ed01a6017fc56/topk_cuda_dispatch.hAdded+28
- shared/package-files/08/0841783816f8f9bc8425953ff5e25b67b58d59231b24eedda06037c95c0d0eee/torchbind.pyAdded+94
- shared/package-files/08/0847db444a04894a6cb0c849c235498b49c8eb1ec6647e28c51abc1ff26e42bd/_kalman_smoother.pxdAdded+491
- shared/package-files/08/084a5c8a445afd8f9267fa05b12695aef9c74b5cfdf58482fed17b56e8ac2d59/registry.pyAdded+141
- shared/package-files/08/084af1309d3205fbbf72f0a828932ef568ea51aa212c8aaa7f6dbc1a6f575892/__init__.pyAdded+131
- shared/package-files/08/084bc0c7c2c9f3dd30b251dddfcccdd19971b76cbe369689f4245ecadb510eaf/RECORDAdded+42
- shared/package-files/08/0852d8ea2cf5f5d00d3e56060c05a8c5ca0d03060290e1a0e4c83b02d7a93615/nord.pyAdded+150
- shared/package-files/08/0855dea48aac25c054c60c36c9f871d630aee355cf8269f977ffba3ade02e35e/minitel12-80Added
- shared/package-files/08/085adcca077cb9d7b9c7a384b5f33f0f0d0a607a31a4f3f3ab8e8aa075718e37/FamagustaAdded
- shared/package-files/08/085b2fe38a29f41c6927adb16d3be8763153f9822fe5980b0fe8db83c1b20a1c/jit_exception.hAdded+38
- shared/package-files/08/085bbee935f102d83dec053bfb5ebc6b6982e5d5fbe91e8fd8605124d1c71e39/empty_like.hAdded+43
- shared/package-files/08/085de63724bef7a53ede2061593f9693dd992eb92f5b1b51bcb6d7cd77f8b613/mach-gnu-colorAdded
- shared/package-files/08/08630ec45901fcdf4d9a6e97dacf70c57a4c4be5c6e81c738d226588b7c71fdf/pyshell.pyAdded+1713
- shared/package-files/08/08633c6992181e578f0dd027475c97dcc7c31aed0e71e66952223f638b5919a5/test_example.txtAdded+24
- shared/package-files/08/086bf2e7d296995f7cc7b486a62ae430fc9949314867e01d65ccf960e0056a4c/_sparse_compressed_tensor_unsafe.hAdded+69
- shared/package-files/08/086e47ff149bb7065a9232f32fe10483e4fd8f618e5329425396202ec6c79b60/test_powsimp.pyAdded+366
- shared/package-files/08/08811d886039522efb63296f01f62f90614d6a0a92a8060e8a5747724f16a3cd/_sfdp_pattern_14.pyAdded+218
- shared/package-files/08/088221112d40daa0dc7aefcd59b4379d2a45816d1f91c1a7c930265b219b1f18/linalg_eigvalsh_native.hAdded+22
- shared/package-files/08/08879f4a4a4dd1d76913bbea6e59db37e743f9236c94f665b851b4030e42620c/_to_sparse_csc_cuda_dispatch.hAdded+23
- shared/package-files/08/0896100ee277cb6b6f25c5ed03b32246387133fdd354f9a756e030738b30bad5/erfc_meta_dispatch.hAdded+26
- shared/package-files/08/0896c48a43618468c73effc245d088849cd6651819167bd75a89f6ad237337f3/guru+rvAdded
- shared/package-files/08/0897b0a6c7147a1b7aa79ed5cc0cdfe026c9623cfa00dafac0f86386b19c3ed8/_cufft_get_plan_cache_size_ops.hAdded+28
- shared/package-files/08/0899037850bf916ff6a2d07c638822698d6140674e8f73f8c4643d6999deb041/cauchy.pyAdded+90
- shared/package-files/08/089949de76f7625218c9bba31312d31054f670ee6422da886b2e5081ce929b7b/target_extension.pyAdded+169
- shared/package-files/08/089a161bb4d6291676b4cec9577aac657a40625076891cdfa20b3bef6d711a5d/_ufuncs.pyAdded+334
- shared/package-files/08/089a4fea064faa4a714c1353f230cf17d7dc49fa1c4ba20023ae61989661efdc/split_with_sizes_copy.hAdded+91
- shared/package-files/08/089b96d30e927700cfb659360e5d788347b0b8272c20a3f0b6798830149812e7/test_scalar_compat.pyAdded+38
- shared/package-files/08/089d0e4c21c88d6034648552e2fa0e440b27d91e11d9c40112d3ec6442690126/_collections.pyAdded+30
- shared/package-files/08/089d2351ad72aee4786bf715a9c151a4e441a5819e6bd0b9bd0e65c067d65192/pyre_extensions.pyiAdded+7
- shared/package-files/08/089dabe5ceebc1d17ea056c605db3f6e4a63e9c91a3d37b1a7eabd8897147aa8/_dirichlet_grad_compositeexplicitautograd_dispatch.hAdded+24
- shared/package-files/08/08a1238a4ed855f48918be1a6ee72d92696421484086ffb1d9a51c5e24d1f5bd/test_fcompiler_nagfor.pyAdded+22
- shared/package-files/08/08a1a12eacafc58d26966cbcfc76f85b391275660f51a536c99621cfed22679c/rewritingsystem_fsm.pyAdded+60
- shared/package-files/08/08a22cd6886ea1ae62ab72dbd00f8510cc2a92eb8e122c3a4c8a04c0cffafc10/_use_cudnn_rnn_flatten_weight.hAdded+30
- shared/package-files/08/08b8092063fe3c24ed22c342ce4a83171d76028507d2b36a2619f6fe90b076fd/Caffe2Config.cmakeAdded+140
123456789101112131415161718192021222324#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace compositeexplicitautograd {
TORCH_API at::Tensor & _sparse_softmax_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool half_to_float);TORCH_API at::Tensor & _sparse_softmax_outf(const at::Tensor & self, int64_t dim, bool half_to_float, at::Tensor & out);
} // namespace compositeexplicitautograd} // namespace at123456789101112131415161718192021from typing import Any, Optional, Tuple, Type
from django.http.request import HttpRequest
from django.db import models
SITE_CACHE: Any
class SiteManager(models.Manager["Site"]): def get_current(self, request: Optional[HttpRequest] = ...) -> Site: ... def clear_cache(self) -> None: ... def get_by_natural_key(self, domain: str) -> Site: ...
class Site(models.Model): objects: SiteManager
domain = models.CharField(max_length=100) name = models.CharField(max_length=50) def natural_key(self) -> Tuple[str]: ...
def clear_site_cache(sender: Type[Site], **kwargs: Any) -> None: ...1234567891011121314151617181920212223242526#pragma once
// @generated by torchgen/gen.py from NativeFunction.h
#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>#include <c10/core/QScheme.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <tuple>#include <vector>
namespace at {namespace native {TORCH_API at::Tensor & quantize_per_tensor_out(const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype, at::Tensor & out);TORCH_API at::Tensor quantize_per_tensor(const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype);TORCH_API at::Tensor & quantize_per_tensor_tensor_qparams_out(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype, at::Tensor & out);TORCH_API at::Tensor quantize_per_tensor_tensor_qparams(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype);TORCH_API void quantize_per_tensor_tensors_out(at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype, at::TensorList out);TORCH_API ::std::vector<at::Tensor> quantize_per_tensor_list_cpu(at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype);} // namespace native} // namespace at123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456# fontchooser.tcl -## A themeable Tk font selection dialog. See TIP #324.## Copyright (C) 2008 Keith Vetter# Copyright (C) 2008 Pat Thoyts <patthoyts@users.sourceforge.net>## See the file "license.terms" for information on usage and redistribution# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
namespace eval ::tk::fontchooser { variable S
set S(W) .__tk__fontchooser set S(fonts) [lsort -dictionary [font families]] set S(styles) [list \ [::msgcat::mc "Regular"] \ [::msgcat::mc "Italic"] \ [::msgcat::mc "Bold"] \ [::msgcat::mc "Bold Italic"] \ ]
set S(sizes) {8 9 10 11 12 14 16 18 20 22 24 26 28 36 48 72} set S(strike) 0 set S(under) 0 set S(first) 1 set S(sampletext) [::msgcat::mc "AaBbYyZz01"] set S(-parent) . set S(-title) [::msgcat::mc "Font"] set S(-command) "" set S(-font) TkDefaultFont}
proc ::tk::fontchooser::Setup {} { variable S
# Canonical versions of font families, styles, etc. for easier searching set S(fonts,lcase) {} foreach font $S(fonts) {lappend S(fonts,lcase) [string tolower $font]} set S(styles,lcase) {} foreach style $S(styles) {lappend S(styles,lcase) [string tolower $style]} set S(sizes,lcase) $S(sizes)
::ttk::style layout FontchooserFrame { Entry.field -sticky news -border true -children { FontchooserFrame.padding -sticky news } } bind [winfo class .] <<ThemeChanged>> \ [list +ttk::style layout FontchooserFrame \ [ttk::style layout FontchooserFrame]]
namespace ensemble create -map { show ::tk::fontchooser::Show hide ::tk::fontchooser::Hide configure ::tk::fontchooser::Configure }}::tk::fontchooser::Setup
proc ::tk::fontchooser::Show {} { variable S if {![winfo exists $S(W)]} { Create wm transient $S(W) [winfo toplevel $S(-parent)] tk::PlaceWindow $S(W) widget $S(-parent) } set S(fonts) [lsort -dictionary [font families]] set S(fonts,lcase) {} foreach font $S(fonts) { lappend S(fonts,lcase) [string tolower $font]} wm deiconify $S(W)}
proc ::tk::fontchooser::Hide {} { variable S wm withdraw $S(W)}
proc ::tk::fontchooser::Configure {args} { variable S
set specs { {-parent "" "" . } {-title "" "" ""} {-font "" "" ""} {-command "" "" ""} }
if {[llength $args] == 0} { set result {} foreach spec $specs { foreach {name xx yy default} $spec break lappend result $name \ [expr {[info exists S($name)] ? $S($name) : $default}] } lappend result -visible \ [expr {[winfo exists $S(W)] && [winfo ismapped $S(W)]}] return $result } if {[llength $args] == 1} { set option [lindex $args 0] if {[string equal $option "-visible"]} { return [expr {[winfo exists $S(W)] && [winfo ismapped $S(W)]}] } elseif {[info exists S($option)]} { return $S($option) } return -code error -errorcode [list TK LOOKUP OPTION $option] \ "bad option \"$option\": must be\ -command, -font, -parent, -title or -visible" }
set cache [dict create -parent $S(-parent) -title $S(-title) \ -font $S(-font) -command $S(-command)] set r [tclParseConfigSpec [namespace which -variable S] $specs DONTSETDEFAULTS $args] if {![winfo exists $S(-parent)]} { set code [list TK LOOKUP WINDOW $S(-parent)] set err "bad window path name \"$S(-parent)\"" array set S $cache return -code error -errorcode $code $err } if {[string trim $S(-title)] eq ""} { set S(-title) [::msgcat::mc "Font"] } if {[winfo exists $S(W)] && ("-font" in $args)} { Init $S(-font) event generate $S(-parent) <<TkFontchooserFontChanged>> } return $r}
proc ::tk::fontchooser::Create {} { variable S set windowName __tk__fontchooser if {$S(-parent) eq "."} { set S(W) .$windowName } else { set S(W) $S(-parent).$windowName }
# Now build the dialog if {![winfo exists $S(W)]} { toplevel $S(W) -class TkFontDialog if {[package provide tcltest] ne {}} {set ::tk_dialog $S(W)} wm withdraw $S(W) wm title $S(W) $S(-title) wm transient $S(W) [winfo toplevel $S(-parent)]
set scaling [tk scaling] set sizeWidth [expr {int([string length [::msgcat::mc "&Size:"]] * $scaling)}]
set outer [::ttk::frame $S(W).outer -padding {10 10}] ::tk::AmpWidget ::ttk::label $S(W).font -text [::msgcat::mc "&Font:"] ::tk::AmpWidget ::ttk::label $S(W).style -text [::msgcat::mc "Font st&yle:"] ::tk::AmpWidget ::ttk::label $S(W).size -text [::msgcat::mc "&Size:"] -width $sizeWidth ttk::entry $S(W).efont -width 18 \ -textvariable [namespace which -variable S](font) ttk::entry $S(W).estyle -width 10 \ -textvariable [namespace which -variable S](style) ttk::entry $S(W).esize -textvariable [namespace which -variable S](size) \ -width 3 -validate key -validatecommand {string is double %P}
ttk_slistbox $S(W).lfonts -height 7 -exportselection 0 \ -selectmode browse -activestyle none \ -listvariable [namespace which -variable S](fonts) ttk_slistbox $S(W).lstyles -width 5 -height 7 -exportselection 0 \ -selectmode browse -activestyle none \ -listvariable [namespace which -variable S](styles) ttk_slistbox $S(W).lsizes -width 4 -height 7 -exportselection 0 \ -selectmode browse -activestyle none \ -listvariable [namespace which -variable S](sizes)
set WE $S(W).effects ::ttk::labelframe $WE -text [::msgcat::mc "Effects"] ::tk::AmpWidget ::ttk::checkbutton $WE.strike \ -variable [namespace which -variable S](strike) \ -text [::msgcat::mc "Stri&keout"] \ -command [namespace code [list Click strike]] ::tk::AmpWidget ::ttk::checkbutton $WE.under \ -variable [namespace which -variable S](under) \ -text [::msgcat::mc "&Underline"] \ -command [namespace code [list Click under]]
set bbox [::ttk::frame $S(W).bbox] ::ttk::button $S(W).ok -text [::msgcat::mc OK] -default active\ -command [namespace code [list Done 1]] ::ttk::button $S(W).cancel -text [::msgcat::mc Cancel] \ -command [namespace code [list Done 0]] ::tk::AmpWidget ::ttk::button $S(W).apply -text [::msgcat::mc "&Apply"] \ -command [namespace code [list Apply]] wm protocol $S(W) WM_DELETE_WINDOW [namespace code [list Done 0]]
# Calculate minimum sizes ttk::scrollbar $S(W).tmpvs set scroll_width [winfo reqwidth $S(W).tmpvs] destroy $S(W).tmpvs set minsize(gap) 10 set minsize(bbox) [winfo reqwidth $S(W).ok] set minsize(fonts) \ [expr {[font measure TkDefaultFont "Helvetica"] + $scroll_width}] set minsize(styles) \ [expr {[font measure TkDefaultFont "Bold Italic"] + $scroll_width}] set minsize(sizes) \ [expr {[font measure TkDefaultFont "-99"] + $scroll_width}] set min [expr {$minsize(gap) * 4}] foreach {what width} [array get minsize] {incr min $width} wm minsize $S(W) $min 260
bind $S(W) <Return> [namespace code [list Done 1]] bind $S(W) <Escape> [namespace code [list Done 0]] bind $S(W) <Map> [namespace code [list Visibility %W 1]] bind $S(W) <Unmap> [namespace code [list Visibility %W 0]] bind $S(W) <Destroy> [namespace code [list Visibility %W 0]] bind $S(W).lfonts.list <<ListboxSelect>> [namespace code [list Click font]] bind $S(W).lstyles.list <<ListboxSelect>> [namespace code [list Click style]] bind $S(W).lsizes.list <<ListboxSelect>> [namespace code [list Click size]] bind $S(W) <Alt-Key> [list ::tk::AltKeyInDialog $S(W) %A] bind $S(W).font <<AltUnderlined>> [list ::focus $S(W).efont] bind $S(W).style <<AltUnderlined>> [list ::focus $S(W).estyle] bind $S(W).size <<AltUnderlined>> [list ::focus $S(W).esize] bind $S(W).apply <<AltUnderlined>> [namespace code [list Apply]] bind $WE.strike <<AltUnderlined>> [list $WE.strike invoke] bind $WE.under <<AltUnderlined>> [list $WE.under invoke]
set WS $S(W).sample ::ttk::labelframe $WS -text [::msgcat::mc "Sample"] ::ttk::label $WS.sample -relief sunken -anchor center \ -textvariable [namespace which -variable S](sampletext) set S(sample) $WS.sample grid $WS.sample -sticky news -padx 6 -pady 4 grid rowconfigure $WS 0 -weight 1 grid columnconfigure $WS 0 -weight 1 grid propagate $WS 0
grid $S(W).ok -in $bbox -sticky new -pady {0 2} grid $S(W).cancel -in $bbox -sticky new -pady 2 if {$S(-command) ne ""} { grid $S(W).apply -in $bbox -sticky new -pady 2 } grid columnconfigure $bbox 0 -weight 1
grid $WE.strike -sticky w -padx 10 grid $WE.under -sticky w -padx 10 -pady {0 30} grid columnconfigure $WE 1 -weight 1
grid $S(W).font x $S(W).style x $S(W).size x -in $outer -sticky w grid $S(W).efont x $S(W).estyle x $S(W).esize x $bbox -in $outer -sticky ew grid $S(W).lfonts x $S(W).lstyles x $S(W).lsizes x ^ -in $outer -sticky news grid $WE x $WS - - x ^ -in $outer -sticky news -pady {15 30} grid configure $bbox -sticky n grid rowconfigure $outer 2 -weight 1 grid columnconfigure $outer {1 3 5} -minsize $minsize(gap) grid columnconfigure $outer {0 2 4} -weight 1 grid columnconfigure $outer 0 -minsize $minsize(fonts) grid columnconfigure $outer 2 -minsize $minsize(styles) grid columnconfigure $outer 4 -minsize $minsize(sizes) grid columnconfigure $outer 6 -minsize $minsize(bbox)
grid $outer -sticky news grid rowconfigure $S(W) 0 -weight 1 grid columnconfigure $S(W) 0 -weight 1
Init $S(-font)
trace add variable [namespace which -variable S](size) \ write [namespace code [list Tracer]] trace add variable [namespace which -variable S](style) \ write [namespace code [list Tracer]] trace add variable [namespace which -variable S](font) \ write [namespace code [list Tracer]] } else { Init $S(-font) }
return}
# ::tk::fontchooser::Done --## Handles teardown of the dialog, calling -command if needed## Arguments:# ok true if user pressed OK#proc ::tk::fontchooser::Done {ok} { variable S
if {! $ok} { set S(result) "" } trace vdelete S(size) w [namespace code [list Tracer]] trace vdelete S(style) w [namespace code [list Tracer]] trace vdelete S(font) w [namespace code [list Tracer]] destroy $S(W) if {$ok && $S(-command) ne ""} { uplevel #0 $S(-command) [list $S(result)] }}
# ::tk::fontchooser::Apply --## Call the -command procedure appending the current font# Errors are reported via the background error mechanism#proc ::tk::fontchooser::Apply {} { variable S if {$S(-command) ne ""} { if {[catch {uplevel #0 $S(-command) [list $S(result)]} err]} { ::bgerror $err } } event generate $S(-parent) <<TkFontchooserFontChanged>>}
# ::tk::fontchooser::Init --## Initializes dialog to a default font## Arguments:# defaultFont font to use as the default#proc ::tk::fontchooser::Init {{defaultFont ""}} { variable S
if {$S(first) || $defaultFont ne ""} { if {$defaultFont eq ""} { set defaultFont [[entry .___e] cget -font] destroy .___e } array set F [font actual $defaultFont] set S(font) $F(-family) set S(size) $F(-size) set S(strike) $F(-overstrike) set S(under) $F(-underline) set S(style) [::msgcat::mc "Regular"] if {$F(-weight) eq "bold" && $F(-slant) eq "italic"} { set S(style) [::msgcat::mc "Bold Italic"] } elseif {$F(-weight) eq "bold"} { set S(style) [::msgcat::mc "Bold"] } elseif {$F(-slant) eq "italic"} { set S(style) [::msgcat::mc "Italic"] }
set S(first) 0 }
Tracer a b c Update}
# ::tk::fontchooser::Click --## Handles all button clicks, updating the appropriate widgets## Arguments:# who which widget got pressed#proc ::tk::fontchooser::Click {who} { variable S
if {$who eq "font"} { set S(font) [$S(W).lfonts get [$S(W).lfonts curselection]] } elseif {$who eq "style"} { set S(style) [$S(W).lstyles get [$S(W).lstyles curselection]] } elseif {$who eq "size"} { set S(size) [$S(W).lsizes get [$S(W).lsizes curselection]] } Update}
# ::tk::fontchooser::Tracer --## Handles traces on key variables, updating the appropriate widgets## Arguments:# standard trace arguments (not used)#proc ::tk::fontchooser::Tracer {var1 var2 op} { variable S
set bad 0 set nstate normal # Make selection in each listbox foreach var {font style size} { set value [string tolower $S($var)] $S(W).l${var}s selection clear 0 end set n [lsearch -exact $S(${var}s,lcase) $value] $S(W).l${var}s selection set $n if {$n >= 0} { set S($var) [lindex $S(${var}s) $n] $S(W).e$var icursor end $S(W).e$var selection clear } else { ;# No match, try prefix # Size is weird: valid numbers are legal but don't display # unless in the font size list set n [lsearch -glob $S(${var}s,lcase) "$value*"] set bad 1 if {$var ne "size" || ! [string is double -strict $value]} { set nstate disabled } } $S(W).l${var}s see $n } if {!$bad} {Update} $S(W).ok configure -state $nstate}
# ::tk::fontchooser::Update --## Shows a sample of the currently selected font#proc ::tk::fontchooser::Update {} { variable S
set S(result) [list $S(font) $S(size)] if {$S(style) eq [::msgcat::mc "Bold"]} {lappend S(result) bold} if {$S(style) eq [::msgcat::mc "Italic"]} {lappend S(result) italic} if {$S(style) eq [::msgcat::mc "Bold Italic"]} {lappend S(result) bold italic} if {$S(strike)} {lappend S(result) overstrike} if {$S(under)} {lappend S(result) underline}
$S(sample) configure -font $S(result)}
# ::tk::fontchooser::Visibility --## Notify the parent when the dialog visibility changes#proc ::tk::fontchooser::Visibility {w visible} { variable S if {$w eq $S(W)} { event generate $S(-parent) <<TkFontchooserVisibility>> }}
# ::tk::fontchooser::ttk_listbox --## Create a properly themed scrolled listbox.# This is exactly right on XP but may need adjusting on other platforms.#proc ::tk::fontchooser::ttk_slistbox {w args} { set f [ttk::frame $w -style FontchooserFrame -padding 2] if {[catch { listbox $f.list -relief flat -highlightthickness 0 -borderwidth 0 {*}$args ttk::scrollbar $f.vs -command [list $f.list yview] $f.list configure -yscrollcommand [list $f.vs set] grid $f.list $f.vs -sticky news grid rowconfigure $f 0 -weight 1 grid columnconfigure $f 0 -weight 1 interp hide {} $w interp alias {} $w {} $f.list } err opt]} { destroy $f return -options $opt $err } return $w}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755"""Implementation of code management magic functions."""#-----------------------------------------------------------------------------# Copyright (c) 2012 The IPython Development Team.## Distributed under the terms of the Modified BSD License.## The full license is in the file COPYING.txt, distributed with this software.#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------
# Stdlibimport inspectimport ioimport osimport reimport sysimport astfrom itertools import chainfrom urllib.request import Request, urlopenfrom urllib.parse import urlencodefrom pathlib import Path
# Our own packagesfrom IPython.core.error import TryNext, StdinNotImplementedError, UsageErrorfrom IPython.core.macro import Macrofrom IPython.core.magic import Magics, magics_class, line_magicfrom IPython.core.oinspect import find_file, find_source_linesfrom IPython.core.release import versionfrom IPython.testing.skipdoctest import skip_doctestfrom IPython.utils.contexts import preserve_keysfrom IPython.utils.path import get_py_filenamefrom warnings import warnfrom logging import errorfrom IPython.utils.text import get_text_list
#-----------------------------------------------------------------------------# Magic implementation classes#-----------------------------------------------------------------------------
# Used for exception handling in magic_editclass MacroToEdit(ValueError): pass
ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
# To match, e.g. 8-10 1:5 :10 3-range_re = re.compile(r"""(?P<start>\d+)?((?P<sep>[\-:]) (?P<end>\d+)?)?$""", re.VERBOSE)
def extract_code_ranges(ranges_str): """Turn a string of range for %%load into 2-tuples of (start, stop) ready to use as a slice of the content split by lines.
Examples -------- list(extract_input_ranges("5-10 2")) [(4, 10), (1, 2)] """ for range_str in ranges_str.split(): rmatch = range_re.match(range_str) if not rmatch: continue sep = rmatch.group("sep") start = rmatch.group("start") end = rmatch.group("end")
if sep == '-': start = int(start) - 1 if start else None end = int(end) if end else None elif sep == ':': start = int(start) - 1 if start else None end = int(end) - 1 if end else None else: end = int(start) start = int(start) - 1 yield (start, end)
def extract_symbols(code, symbols): """ Return a tuple (blocks, not_found) where ``blocks`` is a list of code fragments for each symbol parsed from code, and ``not_found`` are symbols not found in the code.
For example::
In [1]: code = '''a = 10 ...: def b(): return 42 ...: class A: pass'''
In [2]: extract_symbols(code, 'A,b,z') Out[2]: (['class A: pass\\n', 'def b(): return 42\\n'], ['z']) """ symbols = symbols.split(',')
# this will raise SyntaxError if code isn't valid Python py_code = ast.parse(code)
marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body] code = code.split('\n')
symbols_lines = {} # we already know the start_lineno of each symbol (marks). # To find each end_lineno, we traverse in reverse order until each # non-blank line end = len(code) for name, start in reversed(marks): while not code[end - 1].strip(): end -= 1 if name: symbols_lines[name] = (start - 1, end) end = start - 1
# Now symbols_lines is a map # {'symbol_name': (start_lineno, end_lineno), ...} # fill a list with chunks of codes for each requested symbol blocks = [] not_found = [] for symbol in symbols: if symbol in symbols_lines: start, end = symbols_lines[symbol] blocks.append('\n'.join(code[start:end]) + '\n') else: not_found.append(symbol)
return blocks, not_found
def strip_initial_indent(lines): """For %load, strip indent from lines until finding an unindented line.
https://github.com/ipython/ipython/issues/9775 """ indent_re = re.compile(r'\s+')
it = iter(lines) first_line = next(it) indent_match = indent_re.match(first_line)
if indent_match: # First line was indented indent = indent_match.group() yield first_line[len(indent):]
for line in it: if line.startswith(indent): yield line[len(indent):] else: # Less indented than the first line - stop dedenting yield line break else: yield first_line
# Pass the remaining lines through without dedenting for line in it: yield line
class InteractivelyDefined(Exception): """Exception for interactively defined variable in magic_edit""" def __init__(self, index): self.index = index
@magics_classclass CodeMagics(Magics): """Magics related to code management (loading, saving, editing, ...)."""
def __init__(self, *args, **kwargs): self._knowntemps = set() super(CodeMagics, self).__init__(*args, **kwargs)
@line_magic def save(self, parameter_s=''): """Save a set of lines or a macro to a given filename.
Usage:\\ %save [options] filename [history]
Options:
-r: use 'raw' input. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. -f: force overwrite. If file exists, %save will prompt for overwrite unless -f is given.
-a: append to the file instead of overwriting it.
The history argument uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.
If no ranges are specified, saves history of the current session up to this point.
It adds a '.py' extension to the file if you don't do so yourself, and it asks for confirmation before overwriting existing files.
If `-r` option is used, the default extension is `.ipy`. """
opts,args = self.parse_options(parameter_s,'fra',mode='list') if not args: raise UsageError('Missing filename.') raw = 'r' in opts force = 'f' in opts append = 'a' in opts mode = 'a' if append else 'w' ext = '.ipy' if raw else '.py' fname, codefrom = args[0], " ".join(args[1:]) if not fname.endswith(('.py','.ipy')): fname += ext fname = os.path.expanduser(fname) file_exists = os.path.isfile(fname) if file_exists and not force and not append: try: overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') except StdinNotImplementedError: print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)) return if not overwrite : print('Operation cancelled.') return try: cmds = self.shell.find_user_code(codefrom,raw) except (TypeError, ValueError) as e: print(e.args[0]) return with io.open(fname, mode, encoding="utf-8") as f: if not file_exists or not append: f.write("# coding: utf-8\n") f.write(cmds) # make sure we end on a newline if not cmds.endswith('\n'): f.write('\n') print('The following commands were written to file `%s`:' % fname) print(cmds)
@line_magic def pastebin(self, parameter_s=''): """Upload code to dpaste.com, returning the URL.
Usage:\\ %pastebin [-d "Custom description"][-e 24] 1-7
The argument can be an input history range, a filename, or the name of a string or macro.
If no arguments are given, uploads the history of this session up to this point.
Options:
-d: Pass a custom description. The default will say "Pasted from IPython". -e: Pass number of days for the link to be expired. The default will be 7 days. """ opts, args = self.parse_options(parameter_s, "d:e:")
try: code = self.shell.find_user_code(args) except (ValueError, TypeError) as e: print(e.args[0]) return
expiry_days = 7 try: expiry_days = int(opts.get("e", 7)) except ValueError as e: print(e.args[0].capitalize()) return if expiry_days < 1 or expiry_days > 365: print("Expiry days should be in range of 1 to 365") return
post_data = urlencode( { "title": opts.get("d", "Pasted from IPython"), "syntax": "python", "content": code, "expiry_days": expiry_days, } ).encode("utf-8")
request = Request( "https://dpaste.com/api/v2/", headers={"User-Agent": "IPython v{}".format(version)}, ) response = urlopen(request, post_data) return response.headers.get('Location')
@line_magic def loadpy(self, arg_s): """Alias of `%load`
`%loadpy` has gained some flexibility and dropped the requirement of a `.py` extension. So it has been renamed simply into %load. You can look at `%load`'s docstring for more info. """ self.load(arg_s)
@line_magic def load(self, arg_s): """Load code into the current frontend.
Usage:\\ %load [options] source
where source can be a filename, URL, input history range, macro, or element in the user namespace
If no arguments are given, loads the history of this session up to this point.
Options:
-r <lines>: Specify lines or ranges of lines to load from the source. Ranges could be specified as x-y (x..y) or in python-style x:y (x..(y-1)). Both limits x and y can be left blank (meaning the beginning and end of the file, respectively).
-s <symbols>: Specify function or classes to load from python source.
-y : Don't ask confirmation for loading source above 200 000 characters.
-n : Include the user's namespace when searching for source code.
This magic command can either take a local filename, a URL, an history range (see %history) or a macro as argument, it will prompt for confirmation before loading source with more than 200 000 characters, unless -y flag is passed or if the frontend does not support raw_input::
%load %load myscript.py %load 7-27 %load myMacro %load http://www.example.com/myscript.py %load -r 5-10 myscript.py %load -r 10-20,30,40: foo.py %load -s MyClass,wonder_function myscript.py %load -n MyClass %load -n my_module.wonder_function """ opts,args = self.parse_options(arg_s,'yns:r:') search_ns = 'n' in opts contents = self.shell.find_user_code(args, search_ns=search_ns)
if 's' in opts: try: blocks, not_found = extract_symbols(contents, opts['s']) except SyntaxError: # non python code error("Unable to parse the input as valid Python code") return
if len(not_found) == 1: warn('The symbol `%s` was not found' % not_found[0]) elif len(not_found) > 1: warn('The symbols %s were not found' % get_text_list(not_found, wrap_item_with='`') )
contents = '\n'.join(blocks)
if 'r' in opts: ranges = opts['r'].replace(',', ' ') lines = contents.split('\n') slices = extract_code_ranges(ranges) contents = [lines[slice(*slc)] for slc in slices] contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
l = len(contents)
# 200 000 is ~ 2500 full 80 character lines # so in average, more than 5000 lines if l > 200000 and 'y' not in opts: try: ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\ " (%d characters). Continue (y/[N]) ?" % l), default='n' ) except StdinNotImplementedError: #assume yes if raw input not implemented ans = True
if ans is False : print('Operation cancelled.') return
contents = "# %load {}\n".format(arg_s) + contents
self.shell.set_next_input(contents, replace=True)
@staticmethod def _find_edit_target(shell, args, opts, last_call): """Utility method used by magic_edit to find what to edit."""
def make_filename(arg): "Make a filename from the given args" try: filename = get_py_filename(arg) except IOError: # If it ends with .py but doesn't already exist, assume we want # a new file. if arg.endswith('.py'): filename = arg else: filename = None return filename
# Set a few locals from the options for convenience: opts_prev = 'p' in opts opts_raw = 'r' in opts
# custom exceptions class DataIsObject(Exception): pass
# Default line number value lineno = opts.get('n',None)
if opts_prev: args = '_%s' % last_call[0] if args not in shell.user_ns: args = last_call[1]
# by default this is done with temp files, except when the given # arg is a filename use_temp = True
data = ''
# First, see if the arguments should be a filename. filename = make_filename(args) if filename: use_temp = False elif args: # Mode where user specifies ranges of lines, like in %macro. data = shell.extract_input_lines(args, opts_raw) if not data: try: # Load the parameter given as a variable. If not a string, # process it as an object instead (below)
#print '*** args',args,'type',type(args) # dbg data = eval(args, shell.user_ns) if not isinstance(data, str): raise DataIsObject
except (NameError,SyntaxError): # given argument is not a variable, try as a filename filename = make_filename(args) if filename is None: warn("Argument given (%s) can't be found as a variable " "or as a filename." % args) return (None, None, None) use_temp = False
except DataIsObject as e: # macros have a special edit function if isinstance(data, Macro): raise MacroToEdit(data) from e
# For objects, try to edit the file where they are defined filename = find_file(data) if filename: if 'fakemodule' in filename.lower() and \ inspect.isclass(data): # class created by %edit? Try to find source # by looking for method definitions instead, the # __module__ in those classes is FakeModule. attrs = [getattr(data, aname) for aname in dir(data)] for attr in attrs: if not inspect.ismethod(attr): continue filename = find_file(attr) if filename and \ 'fakemodule' not in filename.lower(): # change the attribute to be the edit # target instead data = attr break m = ipython_input_pat.match(os.path.basename(filename)) if m: raise InteractivelyDefined(int(m.groups()[0])) from e
datafile = 1 if filename is None: filename = make_filename(args) datafile = 1 if filename is not None: # only warn about this if we get a real name warn('Could not find file where `%s` is defined.\n' 'Opening a file named `%s`' % (args, filename)) # Now, make sure we can actually read the source (if it was # in a temp file it's gone by now). if datafile: if lineno is None: lineno = find_source_lines(data) if lineno is None: filename = make_filename(args) if filename is None: warn('The file where `%s` was defined ' 'cannot be read or found.' % data) return (None, None, None) use_temp = False
if use_temp: filename = shell.mktempfile(data) print('IPython will make a temporary file named:',filename)
# use last_call to remember the state of the previous call, but don't # let it be clobbered by successive '-p' calls. try: last_call[0] = shell.displayhook.prompt_count if not opts_prev: last_call[1] = args except: pass
return filename, lineno, use_temp
def _edit_macro(self,mname,macro): """open an editor with the macro data in a file""" filename = self.shell.mktempfile(macro.value) self.shell.hooks.editor(filename)
# and make a new macro object, to replace the old one mvalue = Path(filename).read_text(encoding="utf-8") self.shell.user_ns[mname] = Macro(mvalue)
@skip_doctest @line_magic def edit(self, parameter_s='',last_call=['','']): """Bring up an editor and execute the resulting code.
Usage: %edit [options] [args]
%edit runs IPython's editor hook. The default version of this hook is set to call the editor specified by your $EDITOR environment variable. If this isn't found, it will default to vi under Linux/Unix and to notepad under Windows. See the end of this docstring for how to change the editor hook.
You can also set the value of this editor via the ``TerminalInteractiveShell.editor`` option in your configuration file. This is useful if you wish to use a different editor from your typical default with IPython (and for Windows users who typically don't set environment variables).
This command allows you to conveniently edit multi-line code right in your IPython session.
If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don't forget to save it!).
Options:
-n <number>: open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax 'editor +N filename', but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax.
-p: this will call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was.
-r: use 'raw' input. This option only applies to input taken from the user's history. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython's own processor.
-x: do not execute the edited code immediately upon exit. This is mainly useful if you are editing programs which need to be called with command line arguments, which you can then do using %run.
Arguments:
If arguments are given, the following possibilities exist:
- If the argument is a filename, IPython will load that into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace.
- The arguments are ranges of input history, e.g. "7 ~1/4-6". The syntax is the same as in the %history magic.
- If the argument is a string variable, its contents are loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits).
- If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use `%edit function` to load an editor exactly at the point where 'function' is defined, edit it and have the file be executed automatically.
- If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro's data. Upon exit, the macro is reloaded with the contents of the file.
Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the '+NUMBER' parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do.
After executing your code, %edit will return as output the code you typed in the editor (except when it was an existing file). This way you can reload the code in further invocations of %edit as a variable, via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the output.
Note that %edit is also available through the alias %ed.
This is an example of creating a simple function inside the editor and then modifying it. First, start up the editor::
In [1]: edit Editing... done. Executing edited code... Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
We can then call the function foo()::
In [2]: foo() foo() was defined in an editing session
Now we edit foo. IPython automatically loads the editor with the (temporary) file where foo() was previously defined::
In [3]: edit foo Editing... done. Executing edited code...
And if we call foo() again we get the modified version::
In [4]: foo() foo() has now been changed!
Here is an example of how to edit a code snippet successive times. First we call the editor::
In [5]: edit Editing... done. Executing edited code... hello Out[5]: "print 'hello'\\n"
Now we call it again with the previous output (stored in _)::
In [6]: edit _ Editing... done. Executing edited code... hello world Out[6]: "print 'hello world'\\n"
Now we call it with the output #8 (stored in _8, also as Out[8])::
In [7]: edit _8 Editing... done. Executing edited code... hello again Out[7]: "print 'hello again'\\n"
Changing the default editor hook:
If you wish to write your own editor hook, you can put it in a configuration file which you load at startup time. The default hook is defined in the IPython.core.hooks module, and you can use that as a starting example for further modifications. That file also has general instructions on how to set a new hook for use once you've defined it.""" opts,args = self.parse_options(parameter_s,'prxn:')
try: filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) except MacroToEdit as e: self._edit_macro(args, e.args[0]) return except InteractivelyDefined as e: print("Editing In[%i]" % e.index) args = str(e.index) filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) if filename is None: # nothing was found, warnings have already been issued, # just give up. return
if is_temp: self._knowntemps.add(filename) elif (filename in self._knowntemps): is_temp = True
# do actual editing here print('Editing...', end=' ') sys.stdout.flush() filepath = Path(filename) try: # Quote filenames that may have spaces in them when opening # the editor quoted = filename = str(filepath.absolute()) if " " in quoted: quoted = "'%s'" % quoted self.shell.hooks.editor(quoted, lineno) except TryNext: warn('Could not open editor') return
# XXX TODO: should this be generalized for all string vars? # For now, this is special-cased to blocks created by cpaste if args.strip() == "pasted_block": self.shell.user_ns["pasted_block"] = filepath.read_text(encoding="utf-8")
if 'x' in opts: # -x prevents actual execution print() else: print('done. Executing edited code...') with preserve_keys(self.shell.user_ns, '__file__'): if not is_temp: self.shell.user_ns["__file__"] = filename if "r" in opts: # Untranslated IPython code source = filepath.read_text(encoding="utf-8") self.shell.run_cell(source, store_history=False) else: self.shell.safe_execfile(filename, self.shell.user_ns, self.shell.user_ns)
if is_temp: try: return filepath.read_text(encoding="utf-8") except IOError as msg: if Path(msg.filename) == filepath: warn('File not found. Did you forget to save?') return else: self.shell.showtraceback()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"Provides for superficial grammar analysis."
from collections import Counter, defaultdict
from typing import List, Dict, Iterator, FrozenSet, Set
from ..utils import bfs, fzset, classify
from ..exceptions import GrammarError
from ..grammar import Rule, Terminal, NonTerminal, Symbol
from ..common import ParserConf
class RulePtr:
__slots__ = ('rule', 'index')
rule: Rule
index: int
def __init__(self, rule: Rule, index: int):
assert isinstance(rule, Rule)
assert index <= len(rule.expansion)
self.rule = rule
self.index = index
def __repr__(self):
before = [x.name for x in self.rule.expansion[:self.index]]
after = [x.name for x in self.rule.expansion[self.index:]]
return '<%s : %s * %s>' % (self.rule.origin.name, ' '.join(before), ' '.join(after))
@property
def next(self) -> Symbol:
return self.rule.expansion[self.index]
def advance(self, sym: Symbol) -> 'RulePtr':
assert self.next == sym
return RulePtr(self.rule, self.index+1)
@property
def is_satisfied(self) -> bool:
return self.index == len(self.rule.expansion)
def __eq__(self, other) -> bool:
if not isinstance(other, RulePtr):
return NotImplemented
return self.rule == other.rule and self.index == other.index
def __hash__(self) -> int:
return hash((self.rule, self.index))
State = FrozenSet[RulePtr]
# state generation ensures no duplicate LR0ItemSets
class LR0ItemSet:
__slots__ = ('kernel', 'closure', 'transitions', 'lookaheads')
kernel: State
closure: State
transitions: Dict[Symbol, 'LR0ItemSet']
lookaheads: Dict[Symbol, Set[Rule]]
def __init__(self, kernel, closure):
self.kernel = fzset(kernel)
self.closure = fzset(closure)
self.transitions = {}
self.lookaheads = defaultdict(set)
def __repr__(self):
return '{%s | %s}' % (', '.join([repr(r) for r in self.kernel]), ', '.join([repr(r) for r in self.closure]))
def update_set(set1, set2):
if not set2 or set1 > set2:
return False
copy = set(set1)
set1 |= set2
return set1 != copy
def calculate_sets(rules):
"""Calculate FOLLOW sets.
Adapted from: http://lara.epfl.ch/w/cc09:algorithm_for_first_and_follow_sets"""
symbols = {sym for rule in rules for sym in rule.expansion} | {rule.origin for rule in rules}
# foreach grammar rule X ::= Y(1) ... Y(k)
# if k=0 or {Y(1),...,Y(k)} subset of NULLABLE then
# NULLABLE = NULLABLE union {X}
# for i = 1 to k
# if i=1 or {Y(1),...,Y(i-1)} subset of NULLABLE then
# FIRST(X) = FIRST(X) union FIRST(Y(i))
# for j = i+1 to k
# if i=k or {Y(i+1),...Y(k)} subset of NULLABLE then
# FOLLOW(Y(i)) = FOLLOW(Y(i)) union FOLLOW(X)
# if i+1=j or {Y(i+1),...,Y(j-1)} subset of NULLABLE then
# FOLLOW(Y(i)) = FOLLOW(Y(i)) union FIRST(Y(j))
# until none of NULLABLE,FIRST,FOLLOW changed in last iteration
NULLABLE = set()
FIRST = {}
FOLLOW = {}
for sym in symbols:
FIRST[sym]={sym} if sym.is_term else set()
FOLLOW[sym]=set()
# Calculate NULLABLE and FIRST
changed = True
while changed:
changed = False
for rule in rules:
if set(rule.expansion) <= NULLABLE:
if update_set(NULLABLE, {rule.origin}):
changed = True
for i, sym in enumerate(rule.expansion):
if set(rule.expansion[:i]) <= NULLABLE:
if update_set(FIRST[rule.origin], FIRST[sym]):
changed = True
else:
break
# Calculate FOLLOW
changed = True
while changed:
changed = False
for rule in rules:
for i, sym in enumerate(rule.expansion):
if i==len(rule.expansion)-1 or set(rule.expansion[i+1:]) <= NULLABLE:
if update_set(FOLLOW[sym], FOLLOW[rule.origin]):
changed = True
for j in range(i+1, len(rule.expansion)):
if set(rule.expansion[i+1:j]) <= NULLABLE:
if update_set(FOLLOW[sym], FIRST[rule.expansion[j]]):
changed = True
return FIRST, FOLLOW, NULLABLE
class GrammarAnalyzer:
def __init__(self, parser_conf: ParserConf, debug: bool=False, strict: bool=False):
self.debug = debug
self.strict = strict
root_rules = {start: Rule(NonTerminal('$root_' + start), [NonTerminal(start), Terminal('$END')])
for start in parser_conf.start}
rules = parser_conf.rules + list(root_rules.values())
self.rules_by_origin: Dict[NonTerminal, List[Rule]] = classify(rules, lambda r: r.origin)
if len(rules) != len(set(rules)):
duplicates = [item for item, count in Counter(rules).items() if count > 1]
raise GrammarError("Rules defined twice: %s" % ', '.join(str(i) for i in duplicates))
for r in rules:
for sym in r.expansion:
if not (sym.is_term or sym in self.rules_by_origin):
raise GrammarError("Using an undefined rule: %s" % sym)
self.start_states = {start: self.expand_rule(root_rule.origin)
for start, root_rule in root_rules.items()}
self.end_states = {start: fzset({RulePtr(root_rule, len(root_rule.expansion))})
for start, root_rule in root_rules.items()}
lr0_root_rules = {start: Rule(NonTerminal('$root_' + start), [NonTerminal(start)])
for start in parser_conf.start}
lr0_rules = parser_conf.rules + list(lr0_root_rules.values())
assert(len(lr0_rules) == len(set(lr0_rules)))
self.lr0_rules_by_origin = classify(lr0_rules, lambda r: r.origin)
# cache RulePtr(r, 0) in r (no duplicate RulePtr objects)
self.lr0_start_states = {start: LR0ItemSet([RulePtr(root_rule, 0)], self.expand_rule(root_rule.origin, self.lr0_rules_by_origin))
for start, root_rule in lr0_root_rules.items()}
self.FIRST, self.FOLLOW, self.NULLABLE = calculate_sets(rules)
def expand_rule(self, source_rule: NonTerminal, rules_by_origin=None) -> State:
"Returns all init_ptrs accessible by rule (recursive)"
if rules_by_origin is None:
rules_by_origin = self.rules_by_origin
init_ptrs = set()
def _expand_rule(rule: NonTerminal) -> Iterator[NonTerminal]:
assert not rule.is_term, rule
for r in rules_by_origin[rule]:
init_ptr = RulePtr(r, 0)
init_ptrs.add(init_ptr)
if r.expansion: # if not empty rule
new_r = init_ptr.next
if not new_r.is_term:
assert isinstance(new_r, NonTerminal)
yield new_r
for _ in bfs([source_rule], _expand_rule):
pass
return fzset(init_ptrs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330import platformfrom ctypes import (POINTER, c_char_p, c_bool, c_void_p, c_int, c_uint64, c_size_t, CFUNCTYPE, string_at, cast, py_object, Structure)
from llvmlite.binding import ffi, targets, object_file
# Just check these weren't optimized out of the DLL.ffi.lib.LLVMPY_LinkInMCJIT
def create_mcjit_compiler(module, target_machine, use_lmm=None): """ Create a MCJIT ExecutionEngine from the given *module* and *target_machine*.
*lmm* controls whether the llvmlite memory manager is used. If not supplied, the default choice for the platform will be used (``True`` on 64-bit ARM systems, ``False`` otherwise). """ if use_lmm is None: use_lmm = platform.machine().lower() in ('arm64', 'aarch64')
with ffi.OutputString() as outerr: engine = ffi.lib.LLVMPY_CreateMCJITCompiler( module, target_machine, use_lmm, outerr) if not engine: raise RuntimeError(str(outerr))
target_machine._owned = True return ExecutionEngine(engine, module=module)
def check_jit_execution(): """ Check the system allows execution of in-memory JITted functions. An exception is raised otherwise. """ errno = ffi.lib.LLVMPY_TryAllocateExecutableMemory() if errno != 0: raise OSError(errno, "cannot allocate executable memory. " "This may be due to security restrictions on your " "system, such as SELinux or similar mechanisms." )
class ExecutionEngine(ffi.ObjectRef): """An ExecutionEngine owns all Modules associated with it. Deleting the engine will remove all associated modules. It is an error to delete the associated modules. """ _object_cache = None
def __init__(self, ptr, module): """ Module ownership is transferred to the EE """ self._modules = set([module]) self._td = None module._owned = True ffi.ObjectRef.__init__(self, ptr)
def get_function_address(self, name): """ Return the address of the function named *name* as an integer.
It's a fatal error in LLVM if the symbol of *name* doesn't exist. """ return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii"))
def get_global_value_address(self, name): """ Return the address of the global value named *name* as an integer.
It's a fatal error in LLVM if the symbol of *name* doesn't exist. """ return ffi.lib.LLVMPY_GetGlobalValueAddress(self, name.encode("ascii"))
def add_global_mapping(self, gv, addr): ffi.lib.LLVMPY_AddGlobalMapping(self, gv, addr)
def add_module(self, module): """ Ownership of module is transferred to the execution engine """ if module in self._modules: raise KeyError("module already added to this engine") ffi.lib.LLVMPY_AddModule(self, module) module._owned = True self._modules.add(module)
def finalize_object(self): """ Make sure all modules owned by the execution engine are fully processed and "usable" for execution. """ ffi.lib.LLVMPY_FinalizeObject(self)
def run_static_constructors(self): """ Run static constructors which initialize module-level static objects. """ ffi.lib.LLVMPY_RunStaticConstructors(self)
def run_static_destructors(self): """ Run static destructors which perform module-level cleanup of static resources. """ ffi.lib.LLVMPY_RunStaticDestructors(self)
def remove_module(self, module): """ Ownership of module is returned """ with ffi.OutputString() as outerr: if ffi.lib.LLVMPY_RemoveModule(self, module, outerr): raise RuntimeError(str(outerr)) self._modules.remove(module) module._owned = False
@property def target_data(self): """ The TargetData for this execution engine. """ if self._td is not None: return self._td ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self) self._td = targets.TargetData(ptr) self._td._owned = True return self._td
def enable_jit_events(self): """ Enable JIT events for profiling of generated code. Return value indicates whether connection to profiling tool was successful. """ ret = ffi.lib.LLVMPY_EnableJITEvents(self) return ret
def _find_module_ptr(self, module_ptr): """ Find the ModuleRef corresponding to the given pointer. """ ptr = cast(module_ptr, c_void_p).value for module in self._modules: if cast(module._ptr, c_void_p).value == ptr: return module return None
def add_object_file(self, obj_file): """ Add object file to the jit. object_file can be instance of :class:ObjectFile or a string representing file system path """ if isinstance(obj_file, str): obj_file = object_file.ObjectFileRef.from_path(obj_file)
ffi.lib.LLVMPY_MCJITAddObjectFile(self, obj_file)
def set_object_cache(self, notify_func=None, getbuffer_func=None): """ Set the object cache "notifyObjectCompiled" and "getBuffer" callbacks to the given Python functions. """ self._object_cache_notify = notify_func self._object_cache_getbuffer = getbuffer_func # Lifetime of the object cache is managed by us. self._object_cache = _ObjectCacheRef(self) # Note this doesn't keep a reference to self, to avoid reference # cycles. ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache)
def _raw_object_cache_notify(self, data): """ Low-level notify hook. """ if self._object_cache_notify is None: return module_ptr = data.contents.module_ptr buf_ptr = data.contents.buf_ptr buf_len = data.contents.buf_len buf = string_at(buf_ptr, buf_len) module = self._find_module_ptr(module_ptr) if module is None: # The LLVM EE should only give notifications for modules # known by us. raise RuntimeError("object compilation notification " "for unknown module %s" % (module_ptr,)) self._object_cache_notify(module, buf)
def _raw_object_cache_getbuffer(self, data): """ Low-level getbuffer hook. """ if self._object_cache_getbuffer is None: return module_ptr = data.contents.module_ptr module = self._find_module_ptr(module_ptr) if module is None: # The LLVM EE should only give notifications for modules # known by us. raise RuntimeError("object compilation notification " "for unknown module %s" % (module_ptr,))
buf = self._object_cache_getbuffer(module) if buf is not None: # Create a copy, which will be freed by the caller data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf)) data[0].buf_len = len(buf)
def _dispose(self): # The modules will be cleaned up by the EE for mod in self._modules: mod.detach() if self._td is not None: self._td.detach() self._modules.clear() self._object_cache = None self._capi.LLVMPY_DisposeExecutionEngine(self)
class _ObjectCacheRef(ffi.ObjectRef): """ Internal: an ObjectCache instance for use within an ExecutionEngine. """
def __init__(self, obj): ptr = ffi.lib.LLVMPY_CreateObjectCache(_notify_c_hook, _getbuffer_c_hook, obj) ffi.ObjectRef.__init__(self, ptr)
def _dispose(self): self._capi.LLVMPY_DisposeObjectCache(self)
# ============================================================================# FFI
ffi.lib.LLVMPY_CreateMCJITCompiler.argtypes = [ ffi.LLVMModuleRef, ffi.LLVMTargetMachineRef, c_bool, POINTER(c_char_p),]ffi.lib.LLVMPY_CreateMCJITCompiler.restype = ffi.LLVMExecutionEngineRef
ffi.lib.LLVMPY_RemoveModule.argtypes = [ ffi.LLVMExecutionEngineRef, ffi.LLVMModuleRef, POINTER(c_char_p),]ffi.lib.LLVMPY_RemoveModule.restype = c_bool
ffi.lib.LLVMPY_AddModule.argtypes = [ ffi.LLVMExecutionEngineRef, ffi.LLVMModuleRef]
ffi.lib.LLVMPY_AddGlobalMapping.argtypes = [ffi.LLVMExecutionEngineRef, ffi.LLVMValueRef, c_void_p]
ffi.lib.LLVMPY_FinalizeObject.argtypes = [ffi.LLVMExecutionEngineRef]
ffi.lib.LLVMPY_GetExecutionEngineTargetData.argtypes = [ ffi.LLVMExecutionEngineRef]ffi.lib.LLVMPY_GetExecutionEngineTargetData.restype = ffi.LLVMTargetDataRef
ffi.lib.LLVMPY_TryAllocateExecutableMemory.argtypes = []ffi.lib.LLVMPY_TryAllocateExecutableMemory.restype = c_int
ffi.lib.LLVMPY_GetFunctionAddress.argtypes = [ ffi.LLVMExecutionEngineRef, c_char_p]ffi.lib.LLVMPY_GetFunctionAddress.restype = c_uint64
ffi.lib.LLVMPY_GetGlobalValueAddress.argtypes = [ ffi.LLVMExecutionEngineRef, c_char_p]ffi.lib.LLVMPY_GetGlobalValueAddress.restype = c_uint64
ffi.lib.LLVMPY_MCJITAddObjectFile.argtypes = [ ffi.LLVMExecutionEngineRef, ffi.LLVMObjectFileRef]
class _ObjectCacheData(Structure): _fields_ = [ ('module_ptr', ffi.LLVMModuleRef), ('buf_ptr', c_void_p), ('buf_len', c_size_t), ]
_ObjectCacheNotifyFunc = CFUNCTYPE(None, py_object, POINTER(_ObjectCacheData))_ObjectCacheGetBufferFunc = CFUNCTYPE(None, py_object, POINTER(_ObjectCacheData))
# XXX The ctypes function wrappers are created at the top-level, otherwise# there are issues when creating CFUNCTYPEs in child processes on CentOS 5# 32 bits._notify_c_hook = _ObjectCacheNotifyFunc( ExecutionEngine._raw_object_cache_notify)_getbuffer_c_hook = _ObjectCacheGetBufferFunc( ExecutionEngine._raw_object_cache_getbuffer)
ffi.lib.LLVMPY_CreateObjectCache.argtypes = [_ObjectCacheNotifyFunc, _ObjectCacheGetBufferFunc, py_object]ffi.lib.LLVMPY_CreateObjectCache.restype = ffi.LLVMObjectCacheRef
ffi.lib.LLVMPY_DisposeObjectCache.argtypes = [ffi.LLVMObjectCacheRef]
ffi.lib.LLVMPY_SetObjectCache.argtypes = [ffi.LLVMExecutionEngineRef, ffi.LLVMObjectCacheRef]
ffi.lib.LLVMPY_CreateByteString.restype = c_void_pffi.lib.LLVMPY_CreateByteString.argtypes = [c_void_p, c_size_t]1234567891011121314151617181920212223242526#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cuda {
TORCH_API at::Tensor add(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1);TORCH_API at::Tensor & add_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1);TORCH_API at::Tensor & add_outf(const at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha, at::Tensor & out);TORCH_API at::Tensor & add_(at::Tensor & self, const at::Tensor & other, const at::Scalar & alpha=1);
} // namespace cuda} // namespace at123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import numpy as npimport numpy.ma as maimport scipy.stats.mstats as ms
from numpy.testing import (assert_equal, assert_almost_equal, assert_, assert_allclose)
def test_compare_medians_ms(): x = np.arange(7) y = x + 10 assert_almost_equal(ms.compare_medians_ms(x, y), 0)
y2 = np.linspace(0, 1, num=10) assert_almost_equal(ms.compare_medians_ms(x, y2), 0.017116406778)
def test_hdmedian(): # 1-D array x = ma.arange(11) assert_allclose(ms.hdmedian(x), 5, rtol=1e-14) x.mask = ma.make_mask(x) x.mask[:7] = False assert_allclose(ms.hdmedian(x), 3, rtol=1e-14)
# Check that `var` keyword returns a value. TODO: check whether returned # value is actually correct. assert_(ms.hdmedian(x, var=True).size == 2)
# 2-D array x2 = ma.arange(22).reshape((11, 2)) assert_allclose(ms.hdmedian(x2, axis=0), [10, 11]) x2.mask = ma.make_mask(x2) x2.mask[:7, :] = False assert_allclose(ms.hdmedian(x2, axis=0), [6, 7])
def test_rsh(): np.random.seed(132345) x = np.random.randn(100) res = ms.rsh(x) # Just a sanity check that the code runs and output shape is correct. # TODO: check that implementation is correct. assert_(res.shape == x.shape)
# Check points keyword res = ms.rsh(x, points=[0, 1.]) assert_(res.size == 2)
def test_mjci(): # Tests the Marits-Jarrett estimator data = ma.array([77, 87, 88,114,151,210,219,246,253,262, 296,299,306,376,428,515,666,1310,2611]) assert_almost_equal(ms.mjci(data),[55.76819,45.84028,198.87875],5)
def test_trimmed_mean_ci(): # Tests the confidence intervals of the trimmed mean. data = ma.array([545,555,558,572,575,576,578,580, 594,605,635,651,653,661,666]) assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1) assert_equal(np.round(ms.trimmed_mean_ci(data,(0.2,0.2)),1), [561.8, 630.6])
def test_idealfourths(): # Tests ideal-fourths test = np.arange(100) assert_almost_equal(np.asarray(ms.idealfourths(test)), [24.416667,74.583333],6) test_2D = test.repeat(3).reshape(-1,3) assert_almost_equal(ms.idealfourths(test_2D, axis=0), [[24.416667,24.416667,24.416667], [74.583333,74.583333,74.583333]],6) assert_almost_equal(ms.idealfourths(test_2D, axis=1), test.repeat(2).reshape(-1,2)) test = [0, 0] _result = ms.idealfourths(test) assert_(np.isnan(_result).all())
class TestQuantiles: data = [0.706560797,0.727229578,0.990399276,0.927065621,0.158953014, 0.887764025,0.239407086,0.349638551,0.972791145,0.149789972, 0.936947700,0.132359948,0.046041972,0.641675031,0.945530547, 0.224218684,0.771450991,0.820257774,0.336458052,0.589113496, 0.509736129,0.696838829,0.491323573,0.622767425,0.775189248, 0.641461450,0.118455200,0.773029450,0.319280007,0.752229111, 0.047841438,0.466295911,0.583850781,0.840581845,0.550086491, 0.466470062,0.504765074,0.226855960,0.362641207,0.891620942, 0.127898691,0.490094097,0.044882048,0.041441695,0.317976349, 0.504135618,0.567353033,0.434617473,0.636243375,0.231803616, 0.230154113,0.160011327,0.819464108,0.854706985,0.438809221, 0.487427267,0.786907310,0.408367937,0.405534192,0.250444460, 0.995309248,0.144389588,0.739947527,0.953543606,0.680051621, 0.388382017,0.863530727,0.006514031,0.118007779,0.924024803, 0.384236354,0.893687694,0.626534881,0.473051932,0.750134705, 0.241843555,0.432947602,0.689538104,0.136934797,0.150206859, 0.474335206,0.907775349,0.525869295,0.189184225,0.854284286, 0.831089744,0.251637345,0.587038213,0.254475554,0.237781276, 0.827928620,0.480283781,0.594514455,0.213641488,0.024194386, 0.536668589,0.699497811,0.892804071,0.093835427,0.731107772]
def test_hdquantiles(self): data = self.data assert_almost_equal(ms.hdquantiles(data,[0., 1.]), [0.006514031, 0.995309248]) hdq = ms.hdquantiles(data,[0.25, 0.5, 0.75]) assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,])
data = np.array(data).reshape(10,10) hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0) assert_almost_equal(hdq[:,0], ms.hdquantiles(data[:,0],[0.25,0.5,0.75])) assert_almost_equal(hdq[:,-1], ms.hdquantiles(data[:,-1],[0.25,0.5,0.75])) hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True) assert_almost_equal(hdq[...,0], ms.hdquantiles(data[:,0],[0.25,0.5,0.75],var=True)) assert_almost_equal(hdq[...,-1], ms.hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True))
def test_hdquantiles_sd(self): # Standard deviation is a jackknife estimator, so we can check if # the efficient version (hdquantiles_sd) matches a rudimentary, # but clear version here.
hd_std_errs = ms.hdquantiles_sd(self.data)
# jacknnife standard error, Introduction to the Bootstrap Eq. 11.5 n = len(self.data) jdata = np.broadcast_to(self.data, (n, n)) jselector = np.logical_not(np.eye(n)) # leave out one sample each row jdata = jdata[jselector].reshape(n, n-1) jdist = ms.hdquantiles(jdata, axis=1) jdist_mean = np.mean(jdist, axis=0) jstd = ((n-1)/n * np.sum((jdist - jdist_mean)**2, axis=0))**.5
assert_almost_equal(hd_std_errs, jstd) # Test actual values for good measure assert_almost_equal(hd_std_errs, [0.0379258, 0.0380656, 0.0380013])
two_data_points = ms.hdquantiles_sd([1, 2]) assert_almost_equal(two_data_points, [0.5, 0.5, 0.5])
def test_mquantiles_cimj(self): # Only test that code runs, implementation not checked for correctness ci_lower, ci_upper = ms.mquantiles_cimj(self.data) assert_(ci_lower.size == ci_upper.size == 3)
def test_median_cihs(): # Basic test against R library EnvStats function `eqnpar`, e.g. # library(EnvStats) # options(digits=8) # x = c(0.88612955, 0.35242375, 0.66240904, 0.94617974, 0.10929913, # 0.76699506, 0.88550655, 0.62763754, 0.76818588, 0.68506508, # 0.88043148, 0.03911248, 0.93805564, 0.95326961, 0.25291112, # 0.16128487, 0.49784577, 0.24588924, 0.6597, 0.92239679) # eqnpar(x, p=0.5, # ci.method = "interpolate", approx.conf.level = 0.95, ci = TRUE) rng = np.random.default_rng(8824288259505800535) x = rng.random(size=20) assert_allclose(ms.median_cihs(x), (0.38663198, 0.88431272))
# SciPy's 90% CI upper limit doesn't match that of EnvStats eqnpar. SciPy # doesn't look wrong, and it agrees with a different reference, # `median_confint_hs` from `hoehleatsu/quantileCI`. # In (e.g.) Colab with R runtime: # devtools::install_github("hoehleatsu/quantileCI") # library(quantileCI) # median_confint_hs(x=x, conf.level=0.90, interpolate=TRUE) assert_allclose(ms.median_cihs(x, 0.1), (0.48319773366, 0.88094268050))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273from __future__ import annotationsfrom typing import Any
from functools import reducefrom itertools import permutations
from sympy.combinatorics import Permutationfrom sympy.core import ( Basic, Expr, Function, diff, Pow, Mul, Add, Lambda, S, Tuple, Dict)from sympy.core.cache import cacheit
from sympy.core.symbol import Symbol, Dummyfrom sympy.core.symbol import Strfrom sympy.core.sympify import _sympifyfrom sympy.functions import factorialfrom sympy.matrices import ImmutableDenseMatrix as Matrixfrom sympy.solvers import solve
from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings)
# TODO you are a bit excessive in the use of Dummies# TODO dummy point, literal field# TODO too often one needs to call doit or simplify on the output, check the# tests and find out whyfrom sympy.tensor.array import ImmutableDenseNDimArray
class Manifold(Basic): """ A mathematical manifold.
Explanation ===========
A manifold is a topological space that locally resembles Euclidean space near each point [1]. This class does not provide any means to study the topological characteristics of the manifold that it represents, though.
Parameters ==========
name : str The name of the manifold.
dim : int The dimension of the manifold.
Examples ========
>>> from sympy.diffgeom import Manifold >>> m = Manifold('M', 2) >>> m M >>> m.dim 2
References ==========
.. [1] https://en.wikipedia.org/wiki/Manifold """
def __new__(cls, name, dim, **kwargs): if not isinstance(name, Str): name = Str(name) dim = _sympify(dim) obj = super().__new__(cls, name, dim)
obj.patches = _deprecated_list( """ Manifold.patches is deprecated. The Manifold object is now immutable. Instead use a separate list to keep track of the patches. """, []) return obj
@property def name(self): return self.args[0]
@property def dim(self): return self.args[1]
class Patch(Basic): """ A patch on a manifold.
Explanation ===========
Coordinate patch, or patch in short, is a simply-connected open set around a point in the manifold [1]. On a manifold one can have many patches that do not always include the whole manifold. On these patches coordinate charts can be defined that permit the parameterization of any point on the patch in terms of a tuple of real numbers (the coordinates).
This class does not provide any means to study the topological characteristics of the patch that it represents.
Parameters ==========
name : str The name of the patch.
manifold : Manifold The manifold on which the patch is defined.
Examples ========
>>> from sympy.diffgeom import Manifold, Patch >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> p P >>> p.dim 2
References ==========
.. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry (2013)
""" def __new__(cls, name, manifold, **kwargs): if not isinstance(name, Str): name = Str(name) obj = super().__new__(cls, name, manifold)
obj.manifold.patches.append(obj) # deprecated obj.coord_systems = _deprecated_list( """ Patch.coord_systms is deprecated. The Patch class is now immutable. Instead use a separate list to keep track of coordinate systems. """, []) return obj
@property def name(self): return self.args[0]
@property def manifold(self): return self.args[1]
@property def dim(self): return self.manifold.dim
class CoordSystem(Basic): """ A coordinate system defined on the patch.
Explanation ===========
Coordinate system is a system that uses one or more coordinates to uniquely determine the position of the points or other geometric elements on a manifold [1].
By passing ``Symbols`` to *symbols* parameter, user can define the name and assumptions of coordinate symbols of the coordinate system. If not passed, these symbols are generated automatically and are assumed to be real valued.
By passing *relations* parameter, user can define the transform relations of coordinate systems. Inverse transformation and indirect transformation can be found automatically. If this parameter is not passed, coordinate transformation cannot be done.
Parameters ==========
name : str The name of the coordinate system.
patch : Patch The patch where the coordinate system is defined.
symbols : list of Symbols, optional Defines the names and assumptions of coordinate symbols.
relations : dict, optional Key is a tuple of two strings, who are the names of the systems where the coordinates transform from and transform to. Value is a tuple of the symbols before transformation and a tuple of the expressions after transformation.
Examples ========
We define two-dimensional Cartesian coordinate system and polar coordinate system.
>>> from sympy import symbols, pi, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))], ... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))] ... } >>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict) >>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict)
``symbols`` property returns ``CoordinateSymbol`` instances. These symbols are not same with the symbols used to construct the coordinate system.
>>> Car2D Car2D >>> Car2D.dim 2 >>> Car2D.symbols (x, y) >>> _[0].func <class 'sympy.diffgeom.diffgeom.CoordinateSymbol'>
``transformation()`` method returns the transformation function from one coordinate system to another. ``transform()`` method returns the transformed coordinates.
>>> Car2D.transformation(Pol) Lambda((x, y), Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]])) >>> Car2D.transform(Pol) Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> Car2D.transform(Pol, [1, 2]) Matrix([ [sqrt(5)], [atan(2)]])
``jacobian()`` method returns the Jacobian matrix of coordinate transformation between two systems. ``jacobian_determinant()`` method returns the Jacobian determinant of coordinate transformation between two systems.
>>> Pol.jacobian(Car2D) Matrix([ [cos(theta), -r*sin(theta)], [sin(theta), r*cos(theta)]]) >>> Pol.jacobian(Car2D, [1, pi/2]) Matrix([ [0, -1], [1, 0]]) >>> Car2D.jacobian_determinant(Pol) 1/sqrt(x**2 + y**2) >>> Car2D.jacobian_determinant(Pol, [1,0]) 1
References ==========
.. [1] https://en.wikipedia.org/wiki/Coordinate_system
""" def __new__(cls, name, patch, symbols=None, relations={}, **kwargs): if not isinstance(name, Str): name = Str(name)
# canonicallize the symbols if symbols is None: names = kwargs.get('names', None) if names is None: symbols = Tuple( *[Symbol('%s_%s' % (name.name, i), real=True) for i in range(patch.dim)] ) else: sympy_deprecation_warning( f"""The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. Thatis, replace
CoordSystem(..., names={names})
with
CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}]) """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) symbols = Tuple( *[Symbol(n, real=True) for n in names] ) else: syms = [] for s in symbols: if isinstance(s, Symbol): syms.append(Symbol(s.name, **s._assumptions.generator)) elif isinstance(s, str): sympy_deprecation_warning( f"""
Passing a string as the coordinate symbol name to CoordSystem is deprecated.Pass a Symbol with the appropriate name and assumptions instead.
That is, replace {s} with Symbol({s!r}, real=True). """,
deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) syms.append(Symbol(s, real=True)) symbols = Tuple(*syms)
# canonicallize the relations rel_temp = {} for k,v in relations.items(): s1, s2 = k if not isinstance(s1, Str): s1 = Str(s1) if not isinstance(s2, Str): s2 = Str(s2) key = Tuple(s1, s2)
# Old version used Lambda as a value. if isinstance(v, Lambda): v = (tuple(v.signature), tuple(v.expr)) else: v = (tuple(v[0]), tuple(v[1])) rel_temp[key] = v relations = Dict(rel_temp)
# construct the object obj = super().__new__(cls, name, patch, symbols, relations)
# Add deprecated attributes obj.transforms = _deprecated_dict( """ CoordSystem.transforms is deprecated. The CoordSystem class is now immutable. Use the 'relations' keyword argument to the CoordSystems() constructor to specify relations. """, {}) obj._names = [str(n) for n in symbols] obj.patch.coord_systems.append(obj) # deprecated obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated obj._dummy = Dummy()
return obj
@property def name(self): return self.args[0]
@property def patch(self): return self.args[1]
@property def manifold(self): return self.patch.manifold
@property def symbols(self): return tuple(CoordinateSymbol(self, i, **s._assumptions.generator) for i,s in enumerate(self.args[2]))
@property def relations(self): return self.args[3]
@property def dim(self): return self.patch.dim
########################################################################## # Finding transformation relation ##########################################################################
def transformation(self, sys): """ Return coordinate transformation function from *self* to *sys*.
Parameters ==========
sys : CoordSystem
Returns =======
sympy.Lambda
Examples ========
>>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.transformation(R2_p) Lambda((x, y), Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]))
""" signature = self.args[2]
key = Tuple(self.name, sys.name) if self == sys: expr = Matrix(self.symbols) elif key in self.relations: expr = Matrix(self.relations[key][1]) elif key[::-1] in self.relations: expr = Matrix(self._inverse_transformation(sys, self)) else: expr = Matrix(self._indirect_transformation(self, sys)) return Lambda(signature, expr)
@staticmethod def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name): ret = solve( [t[0] - t[1] for t in zip(sym2, exprs)], list(sym1), dict=True)
if len(ret) == 0: temp = "Cannot solve inverse relation from {} to {}." raise NotImplementedError(temp.format(sys1_name, sys2_name)) elif len(ret) > 1: temp = "Obtained multiple inverse relation from {} to {}." raise ValueError(temp.format(sys1_name, sys2_name))
return ret[0]
@classmethod def _inverse_transformation(cls, sys1, sys2): # Find the transformation relation from sys2 to sys1 forward = sys1.transform(sys2) inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward, sys1.name, sys2.name) signature = tuple(sys1.symbols) return [inv_results[s] for s in signature]
@classmethod @cacheit def _indirect_transformation(cls, sys1, sys2): # Find the transformation relation between two indirectly connected # coordinate systems rel = sys1.relations path = cls._dijkstra(sys1, sys2)
transforms = [] for s1, s2 in zip(path, path[1:]): if (s1, s2) in rel: transforms.append(rel[(s1, s2)]) else: sym2, inv_exprs = rel[(s2, s1)] sym1 = tuple(Dummy() for i in sym2) ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1) ret = tuple(ret[s] for s in sym2) transforms.append((sym1, ret)) syms = sys1.args[2] exprs = syms for newsyms, newexprs in transforms: exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs) return exprs
@staticmethod def _dijkstra(sys1, sys2): # Use Dijkstra algorithm to find the shortest path between two indirectly-connected # coordinate systems # return value is the list of the names of the systems. relations = sys1.relations graph = {} for s1, s2 in relations.keys(): if s1 not in graph: graph[s1] = {s2} else: graph[s1].add(s2) if s2 not in graph: graph[s2] = {s1} else: graph[s2].add(s1)
path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited
def visit(sys): path_dict[sys][2] = 1 for newsys in graph[sys]: distance = path_dict[sys][0] + 1 if path_dict[newsys][0] >= distance or not path_dict[newsys][1]: path_dict[newsys][0] = distance path_dict[newsys][1] = list(path_dict[sys][1]) path_dict[newsys][1].append(sys)
visit(sys1.name)
while True: min_distance = max(path_dict.values(), key=lambda x:x[0])[0] newsys = None for sys, lst in path_dict.items(): if 0 < lst[0] <= min_distance and not lst[2]: min_distance = lst[0] newsys = sys if newsys is None: break visit(newsys)
result = path_dict[sys2.name][1] result.append(sys2.name)
if result == [sys2.name]: raise KeyError("Two coordinate systems are not connected.") return result
def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False): sympy_deprecation_warning( """ The CoordSystem.connect_to() method is deprecated. Instead, generate a new instance of CoordSystem with the 'relations' keyword argument (CoordSystem classes are now immutable). """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", )
from_coords, to_exprs = dummyfy(from_coords, to_exprs) self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
if inverse: to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
if fill_in_gaps: self._fill_gaps_in_transformations()
@staticmethod def _inv_transf(from_coords, to_exprs): # Will be removed when connect_to is removed inv_from = [i.as_dummy() for i in from_coords] inv_to = solve( [t[0] - t[1] for t in zip(inv_from, to_exprs)], list(from_coords), dict=True)[0] inv_to = [inv_to[fc] for fc in from_coords] return Matrix(inv_from), Matrix(inv_to)
@staticmethod def _fill_gaps_in_transformations(): # Will be removed when connect_to is removed raise NotImplementedError
########################################################################## # Coordinate transformations ##########################################################################
def transform(self, sys, coordinates=None): """ Return the result of coordinate transformation from *self* to *sys*. If coordinates are not given, coordinate symbols of *self* are used.
Parameters ==========
sys : CoordSystem
coordinates : Any iterable, optional.
Returns =======
sympy.ImmutableDenseMatrix containing CoordinateSymbol
Examples ========
>>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.transform(R2_p) Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> R2_r.transform(R2_p, [0, 1]) Matrix([ [ 1], [pi/2]])
""" if coordinates is None: coordinates = self.symbols if self != sys: transf = self.transformation(sys) coordinates = transf(*coordinates) else: coordinates = Matrix(coordinates) return coordinates
def coord_tuple_transform_to(self, to_sys, coords): """Transform ``coords`` to coord system ``to_sys``.""" sympy_deprecation_warning( """ The CoordSystem.coord_tuple_transform_to() method is deprecated. Use the CoordSystem.transform() method instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", )
coords = Matrix(coords) if self != to_sys: with ignore_warnings(SymPyDeprecationWarning): transf = self.transforms[to_sys] coords = transf[1].subs(list(zip(transf[0], coords))) return coords
def jacobian(self, sys, coordinates=None): """ Return the jacobian matrix of a transformation on given coordinates. If coordinates are not given, coordinate symbols of *self* are used.
Parameters ==========
sys : CoordSystem
coordinates : Any iterable, optional.
Returns =======
sympy.ImmutableDenseMatrix
Examples ========
>>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_p.jacobian(R2_r) Matrix([ [cos(theta), -rho*sin(theta)], [sin(theta), rho*cos(theta)]]) >>> R2_p.jacobian(R2_r, [1, 0]) Matrix([ [1, 0], [0, 1]])
""" result = self.transform(sys).jacobian(self.symbols) if coordinates is not None: result = result.subs(list(zip(self.symbols, coordinates))) return result jacobian_matrix = jacobian
def jacobian_determinant(self, sys, coordinates=None): """ Return the jacobian determinant of a transformation on given coordinates. If coordinates are not given, coordinate symbols of *self* are used.
Parameters ==========
sys : CoordSystem
coordinates : Any iterable, optional.
Returns =======
sympy.Expr
Examples ========
>>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.jacobian_determinant(R2_p) 1/sqrt(x**2 + y**2) >>> R2_r.jacobian_determinant(R2_p, [1, 0]) 1
""" return self.jacobian(sys, coordinates).det()
########################################################################## # Points ##########################################################################
def point(self, coords): """Create a ``Point`` with coordinates given in this coord system.""" return Point(self, coords)
def point_to_coords(self, point): """Calculate the coordinates of a point in this coord system.""" return point.coords(self)
########################################################################## # Base fields. ##########################################################################
def base_scalar(self, coord_index): """Return ``BaseScalarField`` that takes a point and returns one of the coordinates.""" return BaseScalarField(self, coord_index) coord_function = base_scalar
def base_scalars(self): """Returns a list of all coordinate functions. For more details see the ``base_scalar`` method of this class.""" return [self.base_scalar(i) for i in range(self.dim)] coord_functions = base_scalars
def base_vector(self, coord_index): """Return a basis vector field. The basis vector field for this coordinate system. It is also an operator on scalar fields.""" return BaseVectorField(self, coord_index)
def base_vectors(self): """Returns a list of all base vectors. For more details see the ``base_vector`` method of this class.""" return [self.base_vector(i) for i in range(self.dim)]
def base_oneform(self, coord_index): """Return a basis 1-form field. The basis one-form field for this coordinate system. It is also an operator on vector fields.""" return Differential(self.coord_function(coord_index))
def base_oneforms(self): """Returns a list of all base oneforms. For more details see the ``base_oneform`` method of this class.""" return [self.base_oneform(i) for i in range(self.dim)]
class CoordinateSymbol(Symbol): """A symbol which denotes an abstract value of i-th coordinate of the coordinate system with given context.
Explanation ===========
Each coordinates in coordinate system are represented by unique symbol, such as x, y, z in Cartesian coordinate system.
You may not construct this class directly. Instead, use `symbols` method of CoordSystem.
Parameters ==========
coord_sys : CoordSystem
index : integer
Examples ========
>>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])), ... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)])) ... } >>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict) >>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict) >>> x, y = Car2D.symbols
``CoordinateSymbol`` contains its coordinate symbol and index.
>>> x.name 'x' >>> x.coord_sys == Car2D True >>> x.index 0 >>> x.is_real True
You can transform ``CoordinateSymbol`` into other coordinate system using ``rewrite()`` method.
>>> x.rewrite(Pol) r*cos(theta) >>> sqrt(x**2 + y**2).rewrite(Pol).simplify() r
""" def __new__(cls, coord_sys, index, **assumptions): name = coord_sys.args[2][index].name obj = super().__new__(cls, name, **assumptions) obj.coord_sys = coord_sys obj.index = index return obj
def __getnewargs__(self): return (self.coord_sys, self.index)
def _hashable_content(self): return ( self.coord_sys, self.index ) + tuple(sorted(self.assumptions0.items()))
def _eval_rewrite(self, rule, args, **hints): if isinstance(rule, CoordSystem): return rule.transform(self.coord_sys)[self.index] return super()._eval_rewrite(rule, args, **hints)
class Point(Basic): """Point defined in a coordinate system.
Explanation ===========
Mathematically, point is defined in the manifold and does not have any coordinates by itself. Coordinate system is what imbues the coordinates to the point by coordinate chart. However, due to the difficulty of realizing such logic, you must supply a coordinate system and coordinates to define a Point here.
The usage of this object after its definition is independent of the coordinate system that was used in order to define it, however due to limitations in the simplification routines you can arrive at complicated expressions if you use inappropriate coordinate systems.
Parameters ==========
coord_sys : CoordSystem
coords : list The coordinates of the point.
Examples ========
>>> from sympy import pi >>> from sympy.diffgeom import Point >>> from sympy.diffgeom.rn import R2, R2_r, R2_p >>> rho, theta = R2_p.symbols
>>> p = Point(R2_p, [rho, 3*pi/4])
>>> p.manifold == R2 True
>>> p.coords() Matrix([ [ rho], [3*pi/4]]) >>> p.coords(R2_r) Matrix([ [-sqrt(2)*rho/2], [ sqrt(2)*rho/2]])
"""
def __new__(cls, coord_sys, coords, **kwargs): coords = Matrix(coords) obj = super().__new__(cls, coord_sys, coords) obj._coord_sys = coord_sys obj._coords = coords return obj
@property def patch(self): return self._coord_sys.patch
@property def manifold(self): return self._coord_sys.manifold
@property def dim(self): return self.manifold.dim
def coords(self, sys=None): """ Coordinates of the point in given coordinate system. If coordinate system is not passed, it returns the coordinates in the coordinate system in which the poin was defined. """ if sys is None: return self._coords else: return self._coord_sys.transform(sys, self._coords)
@property def free_symbols(self): return self._coords.free_symbols
class BaseScalarField(Expr): """Base scalar field over a manifold for a given coordinate system.
Explanation ===========
A scalar field takes a point as an argument and returns a scalar. A base scalar field of a coordinate system takes a point and returns one of the coordinates of that point in the coordinate system in question.
To define a scalar field you need to choose the coordinate system and the index of the coordinate.
The use of the scalar field after its definition is independent of the coordinate system in which it was defined, however due to limitations in the simplification routines you may arrive at more complicated expression if you use unappropriate coordinate systems. You can build complicated scalar fields by just building up SymPy expressions containing ``BaseScalarField`` instances.
Parameters ==========
coord_sys : CoordSystem
index : integer
Examples ========
>>> from sympy import Function, pi >>> from sympy.diffgeom import BaseScalarField >>> from sympy.diffgeom.rn import R2_r, R2_p >>> rho, _ = R2_p.symbols >>> point = R2_p.point([rho, 0]) >>> fx, fy = R2_r.base_scalars() >>> ftheta = BaseScalarField(R2_r, 1)
>>> fx(point) rho >>> fy(point) 0
>>> (fx**2+fy**2).rcall(point) rho**2
>>> g = Function('g') >>> fg = g(ftheta-pi) >>> fg.rcall(point) g(-pi)
"""
is_commutative = True
def __new__(cls, coord_sys, index, **kwargs): index = _sympify(index) obj = super().__new__(cls, coord_sys, index) obj._coord_sys = coord_sys obj._index = index return obj
@property def coord_sys(self): return self.args[0]
@property def index(self): return self.args[1]
@property def patch(self): return self.coord_sys.patch
@property def manifold(self): return self.coord_sys.manifold
@property def dim(self): return self.manifold.dim
def __call__(self, *args): """Evaluating the field at a point or doing nothing. If the argument is a ``Point`` instance, the field is evaluated at that point. The field is returned itself if the argument is any other object. It is so in order to have working recursive calling mechanics for all fields (check the ``__call__`` method of ``Expr``). """ point = args[0] if len(args) != 1 or not isinstance(point, Point): return self coords = point.coords(self._coord_sys) # XXX Calling doit is necessary with all the Subs expressions # XXX Calling simplify is necessary with all the trig expressions return simplify(coords[self._index]).doit()
# XXX Workaround for limitations on the content of args free_symbols: set[Any] = set()
class BaseVectorField(Expr): r"""Base vector field over a manifold for a given coordinate system.
Explanation ===========
A vector field is an operator taking a scalar field and returning a directional derivative (which is also a scalar field). A base vector field is the same type of operator, however the derivation is specifically done with respect to a chosen coordinate.
To define a base vector field you need to choose the coordinate system and the index of the coordinate.
The use of the vector field after its definition is independent of the coordinate system in which it was defined, however due to limitations in the simplification routines you may arrive at more complicated expression if you use unappropriate coordinate systems.
Parameters ========== coord_sys : CoordSystem
index : integer
Examples ========
>>> from sympy import Function >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import BaseVectorField >>> from sympy import pprint
>>> x, y = R2_r.symbols >>> rho, theta = R2_p.symbols >>> fx, fy = R2_r.base_scalars() >>> point_p = R2_p.point([rho, theta]) >>> point_r = R2_r.point([x, y])
>>> g = Function('g') >>> s_field = g(fx, fy)
>>> v = BaseVectorField(R2_r, 1) >>> pprint(v(s_field)) / d \| |---(g(x, xi))|| \dxi /|xi=y >>> pprint(v(s_field).rcall(point_r).doit()) d --(g(x, y)) dy >>> pprint(v(s_field).rcall(point_p)) / d \| |---(g(rho*cos(theta), xi))|| \dxi /|xi=rho*sin(theta)
"""
is_commutative = False
def __new__(cls, coord_sys, index, **kwargs): index = _sympify(index) obj = super().__new__(cls, coord_sys, index) obj._coord_sys = coord_sys obj._index = index return obj
@property def coord_sys(self): return self.args[0]
@property def index(self): return self.args[1]
@property def patch(self): return self.coord_sys.patch
@property def manifold(self): return self.coord_sys.manifold
@property def dim(self): return self.manifold.dim
def __call__(self, scalar_field): """Apply on a scalar field. The action of a vector field on a scalar field is a directional differentiation. If the argument is not a scalar field an error is raised. """ if covariant_order(scalar_field) or contravariant_order(scalar_field): raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
if scalar_field is None: return self
base_scalars = list(scalar_field.atoms(BaseScalarField))
# First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r) d_var = self._coord_sys._dummy # TODO: you need a real dummy function for the next line d_funcs = [Function('_#_%s' % i)(d_var) for i, b in enumerate(base_scalars)] d_result = scalar_field.subs(list(zip(base_scalars, d_funcs))) d_result = d_result.diff(d_var)
# Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y)) coords = self._coord_sys.symbols d_funcs_deriv = [f.diff(d_var) for f in d_funcs] d_funcs_deriv_sub = [] for b in base_scalars: jac = self._coord_sys.jacobian(b._coord_sys, coords) d_funcs_deriv_sub.append(jac[b._index, self._index]) d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
# Remove the dummies result = d_result.subs(list(zip(d_funcs, base_scalars))) result = result.subs(list(zip(coords, self._coord_sys.coord_functions()))) return result.doit()
def _find_coords(expr): # Finds CoordinateSystems existing in expr fields = expr.atoms(BaseScalarField, BaseVectorField) result = set() for f in fields: result.add(f._coord_sys) return result
class Commutator(Expr): r"""Commutator of two vector fields.
Explanation ===========
The commutator of two vector fields `v_1` and `v_2` is defined as the vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal to `v_1(v_2(f)) - v_2(v_1(f))`.
Examples ========
>>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import Commutator >>> from sympy import simplify
>>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> e_r = R2_p.base_vector(0)
>>> c_xy = Commutator(e_x, e_y) >>> c_xr = Commutator(e_x, e_r) >>> c_xy 0
Unfortunately, the current code is not able to compute everything:
>>> c_xr Commutator(e_x, e_rho) >>> simplify(c_xr(fy**2)) -2*cos(theta)*y**2/(x**2 + y**2)
""" def __new__(cls, v1, v2): if (covariant_order(v1) or contravariant_order(v1) != 1 or covariant_order(v2) or contravariant_order(v2) != 1): raise ValueError( 'Only commutators of vector fields are supported.') if v1 == v2: return S.Zero coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)]) if len(coord_sys) == 1: # Only one coordinate systems is used, hence it is easy enough to # actually evaluate the commutator. if all(isinstance(v, BaseVectorField) for v in (v1, v2)): return S.Zero bases_1, bases_2 = [list(v.atoms(BaseVectorField)) for v in (v1, v2)] coeffs_1 = [v1.expand().coeff(b) for b in bases_1] coeffs_2 = [v2.expand().coeff(b) for b in bases_2] res = 0 for c1, b1 in zip(coeffs_1, bases_1): for c2, b2 in zip(coeffs_2, bases_2): res += c1*b1(c2)*b2 - c2*b2(c1)*b1 return res else: obj = super().__new__(cls, v1, v2) obj._v1 = v1 # deprecated assignment obj._v2 = v2 # deprecated assignment return obj
@property def v1(self): return self.args[0]
@property def v2(self): return self.args[1]
def __call__(self, scalar_field): """Apply on a scalar field. If the argument is not a scalar field an error is raised. """ return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field))
class Differential(Expr): r"""Return the differential (exterior derivative) of a form field.
Explanation ===========
The differential of a form (i.e. the exterior derivative) has a complicated definition in the general case. The differential `df` of the 0-form `f` is defined for any vector field `v` as `df(v) = v(f)`.
Examples ========
>>> from sympy import Function >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import Differential >>> from sympy import pprint
>>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> g = Function('g') >>> s_field = g(fx, fy) >>> dg = Differential(s_field)
>>> dg d(g(x, y)) >>> pprint(dg(e_x)) / d \| |---(g(xi, y))|| \dxi /|xi=x >>> pprint(dg(e_y)) / d \| |---(g(x, xi))|| \dxi /|xi=y
Applying the exterior derivative operator twice always results in:
>>> Differential(dg) 0 """
is_commutative = False
def __new__(cls, form_field): if contravariant_order(form_field): raise ValueError( 'A vector field was supplied as an argument to Differential.') if isinstance(form_field, Differential): return S.Zero else: obj = super().__new__(cls, form_field) obj._form_field = form_field # deprecated assignment return obj
@property def form_field(self): return self.args[0]
def __call__(self, *vector_fields): """Apply on a list of vector_fields.
Explanation ===========
If the number of vector fields supplied is not equal to 1 + the order of the form field inside the differential the result is undefined.
For 1-forms (i.e. differentials of scalar fields) the evaluation is done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector field, the differential is returned unchanged. This is done in order to permit partial contractions for higher forms.
In the general case the evaluation is done by applying the form field inside the differential on a list with one less elements than the number of elements in the original list. Lowering the number of vector fields is achieved through replacing each pair of fields by their commutator.
If the arguments are not vectors or ``None``s an error is raised. """ if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None for a in vector_fields): raise ValueError('The arguments supplied to Differential should be vector fields or Nones.') k = len(vector_fields) if k == 1: if vector_fields[0]: return vector_fields[0].rcall(self._form_field) return self else: # For higher form it is more complicated: # Invariant formula: # https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula # df(v1, ... vn) = +/- vi(f(v1..no i..vn)) # +/- f([vi,vj],v1..no i, no j..vn) f = self._form_field v = vector_fields ret = 0 for i in range(k): t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:])) ret += (-1)**i*t for j in range(i + 1, k): c = Commutator(v[i], v[j]) if c: # TODO this is ugly - the Commutator can be Zero and # this causes the next line to fail t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:]) ret += (-1)**(i + j)*t return ret
class TensorProduct(Expr): """Tensor product of forms.
Explanation ===========
The tensor product permits the creation of multilinear functionals (i.e. higher order tensors) out of lower order fields (e.g. 1-forms and vector fields). However, the higher tensors thus created lack the interesting features provided by the other type of product, the wedge product, namely they are not antisymmetric and hence are not form fields.
Examples ========
>>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import TensorProduct
>>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms()
>>> TensorProduct(dx, dy)(e_x, e_y) 1 >>> TensorProduct(dx, dy)(e_y, e_x) 0 >>> TensorProduct(dx, fx*dy)(fx*e_x, e_y) x**2 >>> TensorProduct(e_x, e_y)(fx**2, fy**2) 4*x*y >>> TensorProduct(e_y, dx)(fy) dx
You can nest tensor products.
>>> tp1 = TensorProduct(dx, dy) >>> TensorProduct(tp1, dx)(e_x, e_y, e_x) 1
You can make partial contraction for instance when 'raising an index'. Putting ``None`` in the second argument of ``rcall`` means that the respective position in the tensor product is left as it is.
>>> TP = TensorProduct >>> metric = TP(dx, dx) + 3*TP(dy, dy) >>> metric.rcall(e_y, None) 3*dy
Or automatically pad the args with ``None`` without specifying them.
>>> metric.rcall(e_y) 3*dy
""" def __new__(cls, *args): scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0]) multifields = [m for m in args if covariant_order(m) + contravariant_order(m)] if multifields: if len(multifields) == 1: return scalar*multifields[0] return scalar*super().__new__(cls, *multifields) else: return scalar
def __call__(self, *fields): """Apply on a list of fields.
If the number of input fields supplied is not equal to the order of the tensor product field, the list of arguments is padded with ``None``'s.
The list of arguments is divided in sublists depending on the order of the forms inside the tensor product. The sublists are provided as arguments to these forms and the resulting expressions are given to the constructor of ``TensorProduct``.
""" tot_order = covariant_order(self) + contravariant_order(self) tot_args = len(fields) if tot_args != tot_order: fields = list(fields) + [None]*(tot_order - tot_args) orders = [covariant_order(f) + contravariant_order(f) for f in self._args] indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)] fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])] multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)] return TensorProduct(*multipliers)
class WedgeProduct(TensorProduct): """Wedge product of forms.
Explanation ===========
In the context of integration only completely antisymmetric forms make sense. The wedge product permits the creation of such forms.
Examples ========
>>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import WedgeProduct
>>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms()
>>> WedgeProduct(dx, dy)(e_x, e_y) 1 >>> WedgeProduct(dx, dy)(e_y, e_x) -1 >>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y) x**2 >>> WedgeProduct(e_x, e_y)(fy, None) -e_x
You can nest wedge products.
>>> wp1 = WedgeProduct(dx, dy) >>> WedgeProduct(wp1, dx)(e_x, e_y, e_x) 0
""" # TODO the calculation of signatures is slow # TODO you do not need all these permutations (neither the prefactor) def __call__(self, *fields): """Apply on a list of vector_fields. The expression is rewritten internally in terms of tensor products and evaluated.""" orders = (covariant_order(e) + contravariant_order(e) for e in self.args) mul = 1/Mul(*(factorial(o) for o in orders)) perms = permutations(fields) perms_par = (Permutation( p).signature() for p in permutations(range(len(fields)))) tensor_prod = TensorProduct(*self.args) return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
class LieDerivative(Expr): """Lie derivative with respect to a vector field.
Explanation ===========
The transport operator that defines the Lie derivative is the pushforward of the field to be derived along the integral curve of the field with respect to which one derives.
Examples ========
>>> from sympy.diffgeom.rn import R2_r, R2_p >>> from sympy.diffgeom import (LieDerivative, TensorProduct)
>>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> e_rho, e_theta = R2_p.base_vectors() >>> dx, dy = R2_r.base_oneforms()
>>> LieDerivative(e_x, fy) 0 >>> LieDerivative(e_x, fx) 1 >>> LieDerivative(e_x, e_x) 0
The Lie derivative of a tensor field by another tensor field is equal to their commutator:
>>> LieDerivative(e_x, e_rho) Commutator(e_x, e_rho) >>> LieDerivative(e_x + e_y, fx) 1
>>> tp = TensorProduct(dx, dy) >>> LieDerivative(e_x, tp) LieDerivative(e_x, TensorProduct(dx, dy)) >>> LieDerivative(e_x, tp) LieDerivative(e_x, TensorProduct(dx, dy))
""" def __new__(cls, v_field, expr): expr_form_ord = covariant_order(expr) if contravariant_order(v_field) != 1 or covariant_order(v_field): raise ValueError('Lie derivatives are defined only with respect to' ' vector fields. The supplied argument was not a ' 'vector field.') if expr_form_ord > 0: obj = super().__new__(cls, v_field, expr) # deprecated assignments obj._v_field = v_field obj._expr = expr return obj if expr.atoms(BaseVectorField): return Commutator(v_field, expr) else: return v_field.rcall(expr)
@property def v_field(self): return self.args[0]
@property def expr(self): return self.args[1]
def __call__(self, *args): v = self.v_field expr = self.expr lead_term = v(expr(*args)) rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:]) for i in range(len(args))]) return lead_term - rest
class BaseCovarDerivativeOp(Expr): """Covariant derivative operator with respect to a base vector.
Examples ========
>>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import BaseCovarDerivativeOp >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
>>> TP = TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms()
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy)) >>> ch [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch) >>> cvd(fx) 1 >>> cvd(fx*e_x) e_x """
def __new__(cls, coord_sys, index, christoffel): index = _sympify(index) christoffel = ImmutableDenseNDimArray(christoffel) obj = super().__new__(cls, coord_sys, index, christoffel) # deprecated assignments obj._coord_sys = coord_sys obj._index = index obj._christoffel = christoffel return obj
@property def coord_sys(self): return self.args[0]
@property def index(self): return self.args[1]
@property def christoffel(self): return self.args[2]
def __call__(self, field): """Apply on a scalar field.
The action of a vector field on a scalar field is a directional differentiation. If the argument is not a scalar field the behaviour is undefined. """ if covariant_order(field) != 0: raise NotImplementedError()
field = vectors_in_basis(field, self._coord_sys)
wrt_vector = self._coord_sys.base_vector(self._index) wrt_scalar = self._coord_sys.coord_function(self._index) vectors = list(field.atoms(BaseVectorField))
# First step: replace all vectors with something susceptible to # derivation and do the derivation # TODO: you need a real dummy function for the next line d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i, b in enumerate(vectors)] d_result = field.subs(list(zip(vectors, d_funcs))) d_result = wrt_vector(d_result)
# Second step: backsubstitute the vectors in d_result = d_result.subs(list(zip(d_funcs, vectors)))
# Third step: evaluate the derivatives of the vectors derivs = [] for v in vectors: d = Add(*[(self._christoffel[k, wrt_vector._index, v._index] *v._coord_sys.base_vector(k)) for k in range(v._coord_sys.dim)]) derivs.append(d) to_subs = [wrt_vector(d) for d in d_funcs] # XXX: This substitution can fail when there are Dummy symbols and the # cache is disabled: https://github.com/sympy/sympy/issues/17794 result = d_result.subs(list(zip(to_subs, derivs)))
# Remove the dummies result = result.subs(list(zip(d_funcs, vectors))) return result.doit()
class CovarDerivativeOp(Expr): """Covariant derivative operator.
Examples ========
>>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import CovarDerivativeOp >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
>>> ch [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> cvd = CovarDerivativeOp(fx*e_x, ch) >>> cvd(fx) x >>> cvd(fx*e_x) x*e_x
"""
def __new__(cls, wrt, christoffel): if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1: raise NotImplementedError() if contravariant_order(wrt) != 1 or covariant_order(wrt): raise ValueError('Covariant derivatives are defined only with ' 'respect to vector fields. The supplied argument ' 'was not a vector field.') christoffel = ImmutableDenseNDimArray(christoffel) obj = super().__new__(cls, wrt, christoffel) # deprecated assignments obj._wrt = wrt obj._christoffel = christoffel return obj
@property def wrt(self): return self.args[0]
@property def christoffel(self): return self.args[1]
def __call__(self, field): vectors = list(self._wrt.atoms(BaseVectorField)) base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel) for v in vectors] return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
################################################################################ Integral curves on vector fields###############################################################################def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False): r"""Return the series expansion for an integral curve of the field.
Explanation ===========
Integral curve is a function `\gamma` taking a parameter in `R` to a point in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any value `t` for the parameter and any scalar field `f`.
This equation can also be decomposed of a basis of coordinate functions `V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
This function returns a series expansion of `\gamma(t)` in terms of the coordinate system ``coord_sys``. The equations and expansions are necessarily done in coordinate-system-dependent way as there is no other way to represent movement between points on the manifold (i.e. there is no such thing as a difference of points for a general manifold).
Parameters ========== vector_field the vector field for which an integral curve will be given
param the argument of the function `\gamma` from R to the curve
start_point the point which corresponds to `\gamma(0)`
n the order to which to expand
coord_sys the coordinate system in which to expand coeffs (default False) - if True return a list of elements of the expansion
Examples ========
Use the predefined R2 manifold:
>>> from sympy.abc import t, x, y >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import intcurve_series
Specify a starting point and a vector field:
>>> start_point = R2_r.point([x, y]) >>> vector_field = R2_r.e_x
Calculate the series:
>>> intcurve_series(vector_field, t, start_point, n=3) Matrix([ [t + x], [ y]])
Or get the elements of the expansion in a list:
>>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True) >>> series[0] Matrix([ [x], [y]]) >>> series[1] Matrix([ [t], [0]]) >>> series[2] Matrix([ [0], [0]])
The series in the polar coordinate system:
>>> series = intcurve_series(vector_field, t, start_point, ... n=3, coord_sys=R2_p, coeffs=True) >>> series[0] Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> series[1] Matrix([ [t*x/sqrt(x**2 + y**2)], [ -t*y/(x**2 + y**2)]]) >>> series[2] Matrix([ [t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2], [ t**2*x*y/(x**2 + y**2)**2]])
See Also ========
intcurve_diffequ
""" if contravariant_order(vector_field) != 1 or covariant_order(vector_field): raise ValueError('The supplied field was not a vector field.')
def iter_vfield(scalar_field, i): """Return ``vector_field`` called `i` times on ``scalar_field``.""" return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
def taylor_terms_per_coord(coord_function): """Return the series for one of the coordinates.""" return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i) for i in range(n)] coord_sys = coord_sys if coord_sys else start_point._coord_sys coord_functions = coord_sys.coord_functions() taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions] if coeffs: return [Matrix(t) for t in zip(*taylor_terms)] else: return Matrix([sum(c) for c in taylor_terms])
def intcurve_diffequ(vector_field, param, start_point, coord_sys=None): r"""Return the differential equation for an integral curve of the field.
Explanation ===========
Integral curve is a function `\gamma` taking a parameter in `R` to a point in the manifold. It verifies the equation:
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
where the given ``vector_field`` is denoted as `V`. This holds for any value `t` for the parameter and any scalar field `f`.
This function returns the differential equation of `\gamma(t)` in terms of the coordinate system ``coord_sys``. The equations and expansions are necessarily done in coordinate-system-dependent way as there is no other way to represent movement between points on the manifold (i.e. there is no such thing as a difference of points for a general manifold).
Parameters ==========
vector_field the vector field for which an integral curve will be given
param the argument of the function `\gamma` from R to the curve
start_point the point which corresponds to `\gamma(0)`
coord_sys the coordinate system in which to give the equations
Returns =======
a tuple of (equations, initial conditions)
Examples ========
Use the predefined R2 manifold:
>>> from sympy.abc import t >>> from sympy.diffgeom.rn import R2, R2_p, R2_r >>> from sympy.diffgeom import intcurve_diffequ
Specify a starting point and a vector field:
>>> start_point = R2_r.point([0, 1]) >>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
Get the equation:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point) >>> equations [f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)] >>> init_cond [f_0(0), f_1(0) - 1]
The series in the polar coordinate system:
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p) >>> equations [Derivative(f_0(t), t), Derivative(f_1(t), t) - 1] >>> init_cond [f_0(0) - 1, f_1(0) - pi/2]
See Also ========
intcurve_series
""" if contravariant_order(vector_field) != 1 or covariant_order(vector_field): raise ValueError('The supplied field was not a vector field.') coord_sys = coord_sys if coord_sys else start_point._coord_sys gammas = [Function('f_%d' % i)(param) for i in range( start_point._coord_sys.dim)] arbitrary_p = Point(coord_sys, gammas) coord_functions = coord_sys.coord_functions() equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p)) for cf in coord_functions] init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point)) for cf in coord_functions] return equations, init_cond
################################################################################ Helpers###############################################################################def dummyfy(args, exprs): # TODO Is this a good idea? d_args = Matrix([s.as_dummy() for s in args]) reps = dict(zip(args, d_args)) d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs]) return d_args, d_exprs
################################################################################ Helpers###############################################################################def contravariant_order(expr, _strict=False): """Return the contravariant order of an expression.
Examples ========
>>> from sympy.diffgeom import contravariant_order >>> from sympy.diffgeom.rn import R2 >>> from sympy.abc import a
>>> contravariant_order(a) 0 >>> contravariant_order(a*R2.x + 2) 0 >>> contravariant_order(a*R2.x*R2.e_y + R2.e_x) 1
""" # TODO move some of this to class methods. # TODO rewrite using the .as_blah_blah methods if isinstance(expr, Add): orders = [contravariant_order(e) for e in expr.args] if len(set(orders)) != 1: raise ValueError('Misformed expression containing contravariant fields of varying order.') return orders[0] elif isinstance(expr, Mul): orders = [contravariant_order(e) for e in expr.args] not_zero = [o for o in orders if o != 0] if len(not_zero) > 1: raise ValueError('Misformed expression containing multiplication between vectors.') return 0 if not not_zero else not_zero[0] elif isinstance(expr, Pow): if covariant_order(expr.base) or covariant_order(expr.exp): raise ValueError( 'Misformed expression containing a power of a vector.') return 0 elif isinstance(expr, BaseVectorField): return 1 elif isinstance(expr, TensorProduct): return sum(contravariant_order(a) for a in expr.args) elif not _strict or expr.atoms(BaseScalarField): return 0 else: # If it does not contain anything related to the diffgeom module and it is _strict return -1
def covariant_order(expr, _strict=False): """Return the covariant order of an expression.
Examples ========
>>> from sympy.diffgeom import covariant_order >>> from sympy.diffgeom.rn import R2 >>> from sympy.abc import a
>>> covariant_order(a) 0 >>> covariant_order(a*R2.x + 2) 0 >>> covariant_order(a*R2.x*R2.dy + R2.dx) 1
""" # TODO move some of this to class methods. # TODO rewrite using the .as_blah_blah methods if isinstance(expr, Add): orders = [covariant_order(e) for e in expr.args] if len(set(orders)) != 1: raise ValueError('Misformed expression containing form fields of varying order.') return orders[0] elif isinstance(expr, Mul): orders = [covariant_order(e) for e in expr.args] not_zero = [o for o in orders if o != 0] if len(not_zero) > 1: raise ValueError('Misformed expression containing multiplication between forms.') return 0 if not not_zero else not_zero[0] elif isinstance(expr, Pow): if covariant_order(expr.base) or covariant_order(expr.exp): raise ValueError( 'Misformed expression containing a power of a form.') return 0 elif isinstance(expr, Differential): return covariant_order(*expr.args) + 1 elif isinstance(expr, TensorProduct): return sum(covariant_order(a) for a in expr.args) elif not _strict or expr.atoms(BaseScalarField): return 0 else: # If it does not contain anything related to the diffgeom module and it is _strict return -1
################################################################################ Coordinate transformation functions###############################################################################def vectors_in_basis(expr, to_sys): """Transform all base vectors in base vectors of a specified coord basis. While the new base vectors are in the new coordinate system basis, any coefficients are kept in the old system.
Examples ========
>>> from sympy.diffgeom import vectors_in_basis >>> from sympy.diffgeom.rn import R2_r, R2_p
>>> vectors_in_basis(R2_r.e_x, R2_p) -y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2) >>> vectors_in_basis(R2_p.e_r, R2_r) sin(theta)*e_y + cos(theta)*e_x
""" vectors = list(expr.atoms(BaseVectorField)) new_vectors = [] for v in vectors: cs = v._coord_sys jac = cs.jacobian(to_sys, cs.coord_functions()) new = (jac.T*Matrix(to_sys.base_vectors()))[v._index] new_vectors.append(new) return expr.subs(list(zip(vectors, new_vectors)))
################################################################################ Coordinate-dependent functions###############################################################################def twoform_to_matrix(expr): """Return the matrix representing the twoform.
For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`, where `e_i` is the i-th base vector field for the coordinate system in which the expression of `w` is given.
Examples ========
>>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import twoform_to_matrix, TensorProduct >>> TP = TensorProduct
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) Matrix([ [1, 0], [0, 1]]) >>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) Matrix([ [x, 0], [0, 1]]) >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2) Matrix([ [ 1, 0], [-1/2, 1]])
""" if covariant_order(expr) != 2 or contravariant_order(expr): raise ValueError('The input expression is not a two-form.') coord_sys = _find_coords(expr) if len(coord_sys) != 1: raise ValueError('The input expression concerns more than one ' 'coordinate systems, hence there is no unambiguous ' 'way to choose a coordinate system for the matrix.') coord_sys = coord_sys.pop() vectors = coord_sys.base_vectors() expr = expr.expand() matrix_content = [[expr.rcall(v1, v2) for v1 in vectors] for v2 in vectors] return Matrix(matrix_content)
def metric_to_Christoffel_1st(expr): """Return the nested list of Christoffel symbols for the given metric. This returns the Christoffel symbol of first kind that represents the Levi-Civita connection for the given metric.
Examples ========
>>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct >>> TP = TensorProduct
>>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]]
""" matrix = twoform_to_matrix(expr) if not matrix.is_symmetric(): raise ValueError( 'The two-form representing the metric is not symmetric.') coord_sys = _find_coords(expr).pop() deriv_matrices = [matrix.applyfunc(d) for d in coord_sys.base_vectors()] indices = list(range(coord_sys.dim)) christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2 for k in indices] for j in indices] for i in indices] return ImmutableDenseNDimArray(christoffel)
def metric_to_Christoffel_2nd(expr): """Return the nested list of Christoffel symbols for the given metric. This returns the Christoffel symbol of second kind that represents the Levi-Civita connection for the given metric.
Examples ========
>>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct
>>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]]
""" ch_1st = metric_to_Christoffel_1st(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) # XXX workaround, inverting a matrix does not work if it contains non # symbols #matrix = twoform_to_matrix(expr).inv() matrix = twoform_to_matrix(expr) s_fields = set() for e in matrix: s_fields.update(e.atoms(BaseScalarField)) s_fields = list(s_fields) dums = coord_sys.symbols matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields))) # XXX end of workaround christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices]) for k in indices] for j in indices] for i in indices] return ImmutableDenseNDimArray(christoffel)
def metric_to_Riemann_components(expr): """Return the components of the Riemann tensor expressed in a given basis.
Given a metric it calculates the components of the Riemann tensor in the canonical basis of the coordinate system in which the metric expression is given.
Examples ========
>>> from sympy import exp >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct >>> TP = TensorProduct
>>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]] >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \ R2.r**2*TP(R2.dtheta, R2.dtheta) >>> non_trivial_metric exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta) >>> riemann = metric_to_Riemann_components(non_trivial_metric) >>> riemann[0, :, :, :] [[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]] >>> riemann[1, :, :, :] [[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]]
""" ch_2nd = metric_to_Christoffel_2nd(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) deriv_ch = [[[[d(ch_2nd[i, j, k]) for d in coord_sys.base_vectors()] for k in indices] for j in indices] for i in indices] riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu] for nu in indices] for mu in indices] for sig in indices] for rho in indices] riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices]) for nu in indices] for mu in indices] for sig in indices] for rho in indices] riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu] for nu in indices] for mu in indices] for sig in indices] for rho in indices] return ImmutableDenseNDimArray(riemann)
def metric_to_Ricci_components(expr):
"""Return the components of the Ricci tensor expressed in a given basis.
Given a metric it calculates the components of the Ricci tensor in the canonical basis of the coordinate system in which the metric expression is given.
Examples ========
>>> from sympy import exp >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct >>> TP = TensorProduct
>>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[0, 0], [0, 0]] >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \ R2.r**2*TP(R2.dtheta, R2.dtheta) >>> non_trivial_metric exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta) >>> metric_to_Ricci_components(non_trivial_metric) [[1/rho, 0], [0, exp(-2*rho)*rho]]
""" riemann = metric_to_Riemann_components(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) ricci = [[Add(*[riemann[k, i, k, j] for k in indices]) for j in indices] for i in indices] return ImmutableDenseNDimArray(ricci)
################################################################################ Classes for deprecation###############################################################################
class _deprecated_container: # This class gives deprecation warning. # When deprecated features are completely deleted, this should be removed as well. # See https://github.com/sympy/sympy/pull/19368 def __init__(self, message, data): super().__init__(data) self.message = message
def warn(self): sympy_deprecation_warning( self.message, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", stacklevel=4 )
def __iter__(self): self.warn() return super().__iter__()
def __getitem__(self, key): self.warn() return super().__getitem__(key)
def __contains__(self, key): self.warn() return super().__contains__(key)
class _deprecated_list(_deprecated_container, list): pass
class _deprecated_dict(_deprecated_container, dict): pass
# Import at end to avoid cyclic importsfrom sympy.simplify.simplify import simplify123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704"""A file interface for handling local and remote data files.
The goal of datasource is to abstract some of the file system operationswhen dealing with data files so the researcher doesn't have to know all thelow-level details. Through datasource, a researcher can obtain and use afile with one function call, regardless of location of the file.
DataSource is meant to augment standard python libraries, not replace them.It should work seamlessly with standard file IO operations and the osmodule.
DataSource files can originate locally or remotely:
- local files : '/home/guido/src/local/data.txt'- URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt'
DataSource files can also be compressed or uncompressed. Currently onlygzip, bz2 and xz are supported.
Example::
>>> # Create a DataSource, use os.curdir (default) for local storage. >>> from numpy import DataSource >>> ds = DataSource() >>> >>> # Open a remote file. >>> # DataSource downloads the file, stores it locally in: >>> # './www.google.com/index.html' >>> # opens the file and returns a file object. >>> fp = ds.open('http://www.google.com/') # doctest: +SKIP >>> >>> # Use the file as you normally would >>> fp.read() # doctest: +SKIP >>> fp.close() # doctest: +SKIP
"""import osimport io
from .._utils import set_module
_open = open
def _check_mode(mode, encoding, newline): """Check mode and that encoding and newline are compatible.
Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files.
""" if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode")
# Using a class instead of a module-level dictionary# to reduce the initial 'import numpy' overhead by# deferring the import of lzma, bz2 and gzip until needed
# TODO: .zip support, .tar support?class _FileOpeners: """ Container for different methods to open (un-)compressed files.
`_FileOpeners` contains a dictionary that holds one method for each supported file format. Attribute lookup is implemented in such a way that an instance of `_FileOpeners` itself can be indexed with the keys of that dictionary. Currently uncompressed files as well as files compressed with ``gzip``, ``bz2`` or ``xz`` compression are supported.
Notes ----- `_file_openers`, an instance of `_FileOpeners`, is made available for use in the `_datasource` module.
Examples -------- >>> import gzip >>> np.lib._datasource._file_openers.keys() [None, '.bz2', '.gz', '.xz', '.lzma'] >>> np.lib._datasource._file_openers['.gz'] is gzip.open True
"""
def __init__(self): self._loaded = False self._file_openers = {None: io.open}
def _load(self): if self._loaded: return
try: import bz2 self._file_openers[".bz2"] = bz2.open except ImportError: pass
try: import gzip self._file_openers[".gz"] = gzip.open except ImportError: pass
try: import lzma self._file_openers[".xz"] = lzma.open self._file_openers[".lzma"] = lzma.open except (ImportError, AttributeError): # There are incompatible backports of lzma that do not have the # lzma.open attribute, so catch that as well as ImportError. pass
self._loaded = True
def keys(self): """ Return the keys of currently supported file openers.
Parameters ---------- None
Returns ------- keys : list The keys are None for uncompressed files and the file extension strings (i.e. ``'.gz'``, ``'.xz'``) for supported compression methods.
""" self._load() return list(self._file_openers.keys())
def __getitem__(self, key): self._load() return self._file_openers[key]
_file_openers = _FileOpeners()
def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None): """ Open `path` with `mode` and return the file object.
If ``path`` is an URL, it will be downloaded, stored in the `DataSource` `destpath` directory and opened from there.
Parameters ---------- path : str Local file path or URL to open. mode : str, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by path. Default is 'r'. destpath : str, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file.
Returns ------- out : file object The opened file.
Notes ----- This is a convenience function that instantiates a `DataSource` and returns the file object from ``DataSource.open(path)``.
"""
ds = DataSource(destpath) return ds.open(path, mode, encoding=encoding, newline=newline)
@set_module('numpy')class DataSource: """ DataSource(destpath='.')
A generic data source file (file, http, ftp, ...).
DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object.
Parameters ---------- destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory.
Notes ----- URLs require a scheme string (``http://``) to be used, without it they will fail::
>>> repos = np.DataSource() >>> repos.exists('www.google.com/index.html') False >>> repos.exists('http://www.google.com/index.html') True
Temporary directories are deleted when the DataSource is deleted.
Examples -------- ::
>>> ds = np.DataSource('/home/guido') >>> urlname = 'http://www.google.com/' >>> gfile = ds.open('http://www.google.com/') >>> ds.abspath(urlname) '/home/guido/www.google.com/index.html'
>>> ds = np.DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') <open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430> >>> ds.abspath('/home/guido/foobar.txt') '/tmp/.../home/guido/foobar.txt'
"""
def __init__(self, destpath=os.curdir): """Create a DataSource with a local path at destpath.""" if destpath: self._destpath = os.path.abspath(destpath) self._istmpdest = False else: import tempfile # deferring import to improve startup time self._destpath = tempfile.mkdtemp() self._istmpdest = True
def __del__(self): # Remove temp directories if hasattr(self, '_istmpdest') and self._istmpdest: import shutil
shutil.rmtree(self._destpath)
def _iszip(self, filename): """Test if the filename is a zip file by looking at the file extension.
""" fname, ext = os.path.splitext(filename) return ext in _file_openers.keys()
def _iswritemode(self, mode): """Test if the given mode will open a file for writing."""
# Currently only used to test the bz2 files. _writemodes = ("w", "+") for c in mode: if c in _writemodes: return True return False
def _splitzipext(self, filename): """Split zip extension from filename and return filename.
Returns ------- base, zip_ext : {tuple}
"""
if self._iszip(filename): return os.path.splitext(filename) else: return filename, None
def _possible_names(self, filename): """Return a tuple containing compressed filename variations.""" names = [filename] if not self._iszip(filename): for zipext in _file_openers.keys(): if zipext: names.append(filename+zipext) return names
def _isurl(self, path): """Test if path is a net location. Tests the scheme and netloc."""
# We do this here to reduce the 'import numpy' initial import time. from urllib.parse import urlparse
# BUG : URLs require a scheme string ('http://') to be used. # www.google.com will fail. # Should we prepend the scheme for those that don't have it and # test that also? Similar to the way we append .gz and test for # for compressed versions of files.
scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) return bool(scheme and netloc)
def _cache(self, path): """Cache the file specified by path.
Creates a copy of the file in the datasource cache.
""" # We import these here because importing them is slow and # a significant fraction of numpy's total import time. import shutil from urllib.request import urlopen
upath = self.abspath(path)
# ensure directory exists if not os.path.exists(os.path.dirname(upath)): os.makedirs(os.path.dirname(upath))
# TODO: Doesn't handle compressed files! if self._isurl(path): with urlopen(path) as openedurl: with _open(upath, 'wb') as f: shutil.copyfileobj(openedurl, f) else: shutil.copyfile(path, upath) return upath
def _findfile(self, path): """Searches for ``path`` and returns full path if found.
If path is an URL, _findfile will cache a local copy and return the path to the cached file. If path is a local file, _findfile will return a path to that local file.
The search will include possible compressed versions of the file and return the first occurrence found.
"""
# Build list of possible local file paths if not self._isurl(path): # Valid local paths filelist = self._possible_names(path) # Paths in self._destpath filelist += self._possible_names(self.abspath(path)) else: # Cached URLs in self._destpath filelist = self._possible_names(self.abspath(path)) # Remote URLs filelist = filelist + self._possible_names(path)
for name in filelist: if self.exists(name): if self._isurl(name): name = self._cache(name) return name return None
def abspath(self, path): """ Return absolute path of file in the DataSource directory.
If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method.
Parameters ---------- path : str Can be a local file or a remote URL.
Returns ------- out : str Complete path, including the `DataSource` destination directory.
Notes ----- The functionality is based on `os.path.abspath`.
""" # We do this here to reduce the 'import numpy' initial import time. from urllib.parse import urlparse
# TODO: This should be more robust. Handles case where path includes # the destpath, but not other sub-paths. Failing case: # path = /home/guido/datafile.txt # destpath = /home/alex/ # upath = self.abspath(path) # upath == '/home/alex/home/guido/datafile.txt'
# handle case where path includes self._destpath splitpath = path.split(self._destpath, 2) if len(splitpath) > 1: path = splitpath[1] scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) netloc = self._sanitize_relative_path(netloc) upath = self._sanitize_relative_path(upath) return os.path.join(self._destpath, netloc, upath)
def _sanitize_relative_path(self, path): """Return a sanitised relative path for which os.path.abspath(os.path.join(base, path)).startswith(base) """ last = None path = os.path.normpath(path) while path != last: last = path # Note: os.path.join treats '/' as os.sep on Windows path = path.lstrip(os.sep).lstrip('/') path = path.lstrip(os.pardir).lstrip('..') drive, path = os.path.splitdrive(path) # for Windows return path
def exists(self, path): """ Test if path exists.
Test if `path` exists as (and in this order):
- a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible.
Parameters ---------- path : str Can be a local file or a remote URL.
Returns ------- out : bool True if `path` exists.
Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location.
"""
# First test for local path if os.path.exists(path): return True
# We import this here because importing urllib is slow and # a significant fraction of numpy's total import time. from urllib.request import urlopen from urllib.error import URLError
# Test cached url upath = self.abspath(path) if os.path.exists(upath): return True
# Test remote url if self._isurl(path): try: netfile = urlopen(path) netfile.close() del(netfile) return True except URLError: return False return False
def open(self, path, mode='r', encoding=None, newline=None): """ Open and return file-like object.
If `path` is an URL, it will be downloaded, stored in the `DataSource` directory and opened from there.
Parameters ---------- path : str Local file path or URL to open. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file.
Returns ------- out : file object File object.
"""
# TODO: There is no support for opening a file for writing which # doesn't exist yet (creating a file). Should there be?
# TODO: Add a ``subdir`` parameter for specifying the subdirectory # used to store URLs in self._destpath.
if self._isurl(path) and self._iswritemode(mode): raise ValueError("URLs are not writeable")
# NOTE: _findfile will fail on a new file opened for writing. found = self._findfile(path) if found: _fname, ext = self._splitzipext(found) if ext == 'bz2': mode.replace("+", "") return _file_openers[ext](found, mode=mode, encoding=encoding, newline=newline) else: raise FileNotFoundError(f"{path} not found.")
class Repository (DataSource): """ Repository(baseurl, destpath='.')
A data repository where multiple DataSource's share a base URL/directory.
`Repository` extends `DataSource` by prepending a base URL (or directory) to all the files it handles. Use `Repository` when you will be working with multiple files from one base URL. Initialize `Repository` with the base URL, then refer to each file by its filename only.
Parameters ---------- baseurl : str Path to the local directory or remote location that contains the data files. destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory.
Examples -------- To analyze all files in the repository, do something like this (note: this is not self-contained code)::
>>> repos = np.lib._datasource.Repository('/home/user/data/dir/') >>> for filename in filelist: ... fp = repos.open(filename) ... fp.analyze() ... fp.close()
Similarly you could use a URL for a repository::
>>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data')
"""
def __init__(self, baseurl, destpath=os.curdir): """Create a Repository with a shared url or directory of baseurl.""" DataSource.__init__(self, destpath=destpath) self._baseurl = baseurl
def __del__(self): DataSource.__del__(self)
def _fullpath(self, path): """Return complete path for path. Prepends baseurl if necessary.""" splitpath = path.split(self._baseurl, 2) if len(splitpath) == 1: result = os.path.join(self._baseurl, path) else: result = path # path contains baseurl already return result
def _findfile(self, path): """Extend DataSource method to prepend baseurl to ``path``.""" return DataSource._findfile(self, self._fullpath(path))
def abspath(self, path): """ Return absolute path of file in the Repository directory.
If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method.
Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized.
Returns ------- out : str Complete path, including the `DataSource` destination directory.
""" return DataSource.abspath(self, self._fullpath(path))
def exists(self, path): """ Test if path exists prepending Repository base URL to path.
Test if `path` exists as (and in this order):
- a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible.
Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized.
Returns ------- out : bool True if `path` exists.
Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location.
""" return DataSource.exists(self, self._fullpath(path))
def open(self, path, mode='r', encoding=None, newline=None): """ Open and return file-like object prepending Repository base URL.
If `path` is an URL, it will be downloaded, stored in the DataSource directory and opened from there.
Parameters ---------- path : str Local file path or URL to open. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file.
Returns ------- out : file object File object.
""" return DataSource.open(self, self._fullpath(path), mode, encoding=encoding, newline=newline)
def listdir(self): """ List files in the source Repository.
Returns ------- files : list of str List of file names (not containing a directory part).
Notes ----- Does not currently work for remote repositories.
""" if self._isurl(self._baseurl): raise NotImplementedError( "Directory listing of URLs, not supported yet.") else: return os.listdir(self._baseurl)1234567891011121314151617{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://json-schema.org/draft/2020-12/meta/content", "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, "$dynamicAnchor": "meta",
"title": "Content vocabulary meta-schema",
"type": ["object", "boolean"], "properties": { "contentEncoding": { "type": "string" }, "contentMediaType": { "type": "string" }, "contentSchema": { "$dynamicRef": "#meta" } }}1234import torchif torch.distributed.rpc.is_available(): from .api.remote_module import RemoteModulefrom .functional import * # noqa: F4031234567891011121314151617181920212223242526272829303132333435363738# "magictoken" is used for markers as beginning and ending of example text.
import unittestimport numpy as npimport numba
class NumpyGeneratorUsageTest(unittest.TestCase):
def test_numpy_gen_usage(self): # magictoken.npgen_usage.begin x = np.random.default_rng(1) y = np.random.default_rng(1)
size = 10
@numba.njit def do_stuff(gen): return gen.random(size=int(size / 2))
original = x.random(size=size) # [0.51182162 0.9504637 0.14415961 0.94864945 0.31183145 # 0.42332645 0.82770259 0.40919914 0.54959369 0.02755911]
numba_func_res = do_stuff(y) # [0.51182162 0.9504637 0.14415961 0.94864945 0.31183145]
after_numba = y.random(size=int(size / 2)) # [0.42332645 0.82770259 0.40919914 0.54959369 0.02755911]
# magictoken.npgen_usage.end numba_res = np.concatenate((numba_func_res, after_numba)) for _np_res, _nb_res in zip(original, numba_res): self.assertEqual(_np_res, _nb_res)
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>
#include <ATen/ops/istft_ops.h>
namespace at {
// aten::istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensorinline at::Tensor istft(const at::Tensor & self, int64_t n_fft, c10::optional<int64_t> hop_length=c10::nullopt, c10::optional<int64_t> win_length=c10::nullopt, const c10::optional<at::Tensor> & window={}, bool center=true, bool normalized=false, c10::optional<bool> onesided=c10::nullopt, c10::optional<int64_t> length=c10::nullopt, bool return_complex=false) { return at::_ops::istft::call(self, n_fft, hop_length, win_length, window, center, normalized, onesided, length, return_complex);}
}1234567from .base_data_sparsifier import BaseDataSparsifierfrom .data_norm_sparsifier import DataNormSparsifier
__all__ = [ "BaseDataSparsifier", "DataNormSparsifier",]12345678910111213141516171819202122232425262728#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cuda {
TORCH_API ::std::tuple<at::Tensor,at::Tensor> topk(const at::Tensor & self, int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true);TORCH_API ::std::tuple<at::Tensor,at::Tensor> topk_symint(const at::Tensor & self, c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true);TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> topk_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true);TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> topk_outf(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices);TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> topk_symint_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true);TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> topk_symint_outf(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices);
} // namespace cuda} // namespace at12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from contextlib import contextmanager
import torchfrom torch._C import DispatchKey # @manualfrom torch._functorch._aot_autograd.utils import KNOWN_TYPESfrom torch._higher_order_ops.utils import autograd_not_implementedfrom torch._ops import HigherOrderOperatorfrom torch._subclasses.fake_tensor import FakeTensorModefrom torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_treefrom torch.fx.node import has_side_effectfrom torch.utils import _pytree as pytree
# The call_torchbind operator represents a method invocation on a torchbind# object. The calling convention is:# call_torchbind(self: ScriptObject, method_name: str, *method_args, **method_kwargs)# We do not expect users to write this operator directly. Instead it will be# emitted by Dynamo when tracing encounters a torchbind object.call_torchbind = HigherOrderOperator("call_torchbind")
# Register this operator as side-effectful with FX.# TODO: this is not really sufficient. While passes (hopefully) check# Node.is_impure() and make good decisions, we also assume we can execute the# graph as many times as we want without changing behavior, which is NOT true of# ops that mutate torchbind object state.has_side_effect(call_torchbind)
_orig_scriptmethod_call = torch.ScriptMethod.__call__
def torchbind_method_redispatch(self, *args, **kwargs): if isinstance(self.raw_owner, torch.ScriptObject): return call_torchbind(self.raw_owner, self.name, *args, **kwargs) return _orig_scriptmethod_call(self, *args, **kwargs)
@contextmanagerdef enable_torchbind_tracing(): """Context manager that acts as a feature flag to enable torchbind tracing behavior. Once torchbind tracing has been stabilized, we can remove this and turn it always on. """ try: KNOWN_TYPES.append(torch.ScriptObject) torch.ScriptMethod.__call__ = torchbind_method_redispatch # type: ignore[method-assign] yield finally: assert ( KNOWN_TYPES.pop() is torch.ScriptObject ), "Someone else messed with KNOWN_TYPES during tracing, exploding." torch.ScriptMethod.__call__ = _orig_scriptmethod_call # type: ignore[method-assign]
@call_torchbind.py_impl(DispatchKey.CompositeExplicitAutograd)def call_torchbind_impl(obj, method, *args, **kwargs): return _orig_scriptmethod_call(getattr(obj, method), *args, **kwargs)
@call_torchbind.py_impl(ProxyTorchDispatchMode)def inner(mode, *args, **kwargs): if mode.enable_tracing: proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
out_proxy = mode.tracer.create_proxy( "call_function", call_torchbind, proxy_args, proxy_kwargs, ) out = call_torchbind_impl(*args, **kwargs)
return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) else: return call_torchbind(*args, **kwargs)
# TODO: currently we just run the C++ implementation with fake tensors.# But we should make it possible to register a fake torchbind implementation.@call_torchbind.py_impl(FakeTensorMode)def call_torchbind_fake(mode, *args, **kwargs): with mode: return call_torchbind_impl(*args, **kwargs)
call_torchbind.py_impl(DispatchKey.Autograd)( autograd_not_implemented(call_torchbind, deferred_error=True))
@call_torchbind.py_functionalize_impldef call_torchbind_func(ctx, *args, **kwargs): args = ctx.unwrap_tensors(args) with ctx.redispatch_to_next(): return ctx.wrap_tensors(call_torchbind(*args, **kwargs))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491#cython: boundscheck=False#cython: wraparound=False#cython: cdivision=False"""State Space Model Smoother declarations
Author: Chad Fulton License: Simplified-BSD"""
cdef int SMOOTHER_STATE # Durbin and Koopman (2012), Chapter 4.4.2cdef int SMOOTHER_STATE_COV # Durbin and Koopman (2012), Chapter 4.4.3cdef int SMOOTHER_DISTURBANCE # Durbin and Koopman (2012), Chapter 4.5cdef int SMOOTHER_DISTURBANCE_COV # Durbin and Koopman (2012), Chapter 4.5cdef int SMOOTHER_STATE_AUTOCOV # Durbin and Koopman (2012), Chapter 4.7cdef int SMOOTHER_ALL
cdef int SMOOTH_CONVENTIONALcdef int SMOOTH_CLASSICALcdef int SMOOTH_ALTERNATIVEcdef int SMOOTH_UNIVARIATE
# Typical imports
cimport numpy as np
from statsmodels.tsa.statespace._kalman_filter cimport ( cKalmanFilter, dKalmanFilter, sKalmanFilter, zKalmanFilter,)from statsmodels.tsa.statespace._representation cimport ( cStatespace, dStatespace, sStatespace, zStatespace,)
# Single precisioncdef class sKalmanSmoother(object): # Statespace object cdef readonly sStatespace model # Kalman filter cdef readonly sKalmanFilter kfilter
cdef readonly int t cdef readonly int smoother_output cdef readonly int smooth_method cdef readonly int _smooth_method cdef readonly int filter_method
cdef readonly np.float32_t [::1,:] scaled_smoothed_estimator cdef readonly np.float32_t [::1,:,:] scaled_smoothed_estimator_cov cdef readonly np.float32_t [::1,:] smoothing_error cdef readonly np.float32_t [::1,:] smoothed_state cdef readonly np.float32_t [::1,:,:] smoothed_state_cov cdef readonly np.float32_t [::1,:] smoothed_measurement_disturbance cdef readonly np.float32_t [::1,:] smoothed_state_disturbance cdef readonly np.float32_t [::1,:,:] smoothed_measurement_disturbance_cov cdef readonly np.float32_t [::1,:,:] smoothed_state_disturbance_cov
cdef readonly np.float32_t [::1,:,:] smoothed_state_autocov, innovations_transition cdef readonly np.float32_t [::1,:] tmp_autocov
cdef readonly np.float32_t [::1,:] scaled_smoothed_diffuse_estimator cdef readonly np.float32_t [::1,:,:] scaled_smoothed_diffuse1_estimator_cov cdef readonly np.float32_t [::1,:,:] scaled_smoothed_diffuse2_estimator_cov
cdef readonly np.float32_t [:] selected_design cdef readonly np.float32_t [:] selected_obs_cov
cdef readonly np.float32_t [::1,:] tmpL, tmpL2, tmp0, tmp00, tmp000
# Statespace # cdef np.float32_t * _design # cdef np.float32_t * _obs_cov # cdef np.float32_t * _transition # cdef np.float32_t * _selection # cdef np.float32_t * _state_cov
# Kalman filter # cdef np.float32_t * _predicted_state # cdef np.float32_t * _predicted_state_cov # cdef np.float32_t * _kalman_gain
# cdef np.float32_t * _tmp1 # cdef np.float32_t * _tmp2 # cdef np.float32_t * _tmp3 # cdef np.float32_t * _tmp4
# Kalman smoother cdef np.float32_t * _input_scaled_smoothed_estimator cdef np.float32_t * _input_scaled_smoothed_estimator_cov
cdef np.float32_t * _scaled_smoothed_estimator cdef np.float32_t * _scaled_smoothed_estimator_cov cdef np.float32_t * _smoothing_error cdef np.float32_t * _smoothed_state cdef np.float32_t * _smoothed_state_cov cdef np.float32_t * _smoothed_measurement_disturbance cdef np.float32_t * _smoothed_state_disturbance cdef np.float32_t * _smoothed_measurement_disturbance_cov cdef np.float32_t * _smoothed_state_disturbance_cov
cdef np.float32_t * _innovations_transition cdef np.float32_t * _smoothed_state_autocov cdef np.float32_t * _tmp_autocov
cdef np.float32_t * _input_scaled_smoothed_diffuse_estimator cdef np.float32_t * _input_scaled_smoothed_diffuse1_estimator_cov cdef np.float32_t * _input_scaled_smoothed_diffuse2_estimator_cov cdef np.float32_t * _scaled_smoothed_diffuse_estimator cdef np.float32_t * _scaled_smoothed_diffuse1_estimator_cov cdef np.float32_t * _scaled_smoothed_diffuse2_estimator_cov
# Temporary cdef np.float32_t * _tmpL cdef np.float32_t * _tmpL2 cdef np.float32_t * _tmp0 cdef np.float32_t * _tmp00 cdef np.float32_t * _tmp000
# Functions cdef int (*smooth_estimators_measurement)( sKalmanSmoother, sKalmanFilter, sStatespace ) except * cdef int (*smooth_estimators_time)( sKalmanSmoother, sKalmanFilter, sStatespace ) cdef int (*smooth_state)( sKalmanSmoother, sKalmanFilter, sStatespace ) cdef int (*smooth_disturbances)( sKalmanSmoother, sKalmanFilter, sStatespace )
# cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef
cdef allocate_arrays(self) cdef int check_filter_method_changed(self) cdef int reset_filter_method(self, int force_reset=*) cpdef set_smoother_output(self, int smoother_output, int force_reset=*) cpdef set_smooth_method(self, int smooth_method) cpdef reset(self, int force_reset=*) cpdef seek(self, unsigned int t) cdef void initialize_statespace_object_pointers(self) except * cdef void initialize_filter_object_pointers(self) cdef void initialize_smoother_object_pointers(self) except * cdef void initialize_function_pointers(self) except * cdef void _initialize_temp_pointers(self) except *
# Double precisioncdef class dKalmanSmoother(object): # Statespace object cdef readonly dStatespace model # Kalman filter cdef readonly dKalmanFilter kfilter
cdef readonly int t cdef readonly int smoother_output cdef readonly int smooth_method cdef readonly int _smooth_method cdef readonly int filter_method
cdef readonly np.float64_t [::1,:] scaled_smoothed_estimator cdef readonly np.float64_t [::1,:,:] scaled_smoothed_estimator_cov cdef readonly np.float64_t [::1,:] smoothing_error cdef readonly np.float64_t [::1,:] smoothed_state cdef readonly np.float64_t [::1,:,:] smoothed_state_cov cdef readonly np.float64_t [::1,:] smoothed_measurement_disturbance cdef readonly np.float64_t [::1,:] smoothed_state_disturbance cdef readonly np.float64_t [::1,:,:] smoothed_measurement_disturbance_cov cdef readonly np.float64_t [::1,:,:] smoothed_state_disturbance_cov
cdef readonly np.float64_t [::1,:,:] smoothed_state_autocov, innovations_transition cdef readonly np.float64_t [::1,:] tmp_autocov
cdef readonly np.float64_t [::1,:] scaled_smoothed_diffuse_estimator cdef readonly np.float64_t [::1,:,:] scaled_smoothed_diffuse1_estimator_cov cdef readonly np.float64_t [::1,:,:] scaled_smoothed_diffuse2_estimator_cov
cdef readonly np.float64_t [:] selected_design cdef readonly np.float64_t [:] selected_obs_cov
cdef readonly np.float64_t [::1,:] tmpL, tmpL2, tmp0, tmp00, tmp000
# Statespace # cdef np.float64_t * _design # cdef np.float64_t * _obs_cov # cdef np.float64_t * _transition # cdef np.float64_t * _selection # cdef np.float64_t * _state_cov
# Kalman filter # cdef np.float64_t * _predicted_state # cdef np.float64_t * _predicted_state_cov # cdef np.float64_t * _kalman_gain
# cdef np.float64_t * _tmp1 # cdef np.float64_t * _tmp2 # cdef np.float64_t * _tmp3 # cdef np.float64_t * _tmp4
# Kalman smoother cdef np.float64_t * _input_scaled_smoothed_estimator cdef np.float64_t * _input_scaled_smoothed_estimator_cov
cdef np.float64_t * _scaled_smoothed_estimator cdef np.float64_t * _scaled_smoothed_estimator_cov cdef np.float64_t * _smoothing_error cdef np.float64_t * _smoothed_state cdef np.float64_t * _smoothed_state_cov cdef np.float64_t * _smoothed_measurement_disturbance cdef np.float64_t * _smoothed_state_disturbance cdef np.float64_t * _smoothed_measurement_disturbance_cov cdef np.float64_t * _smoothed_state_disturbance_cov
cdef np.float64_t * _innovations_transition cdef np.float64_t * _smoothed_state_autocov cdef np.float64_t * _tmp_autocov
cdef np.float64_t * _input_scaled_smoothed_diffuse_estimator cdef np.float64_t * _input_scaled_smoothed_diffuse1_estimator_cov cdef np.float64_t * _input_scaled_smoothed_diffuse2_estimator_cov cdef np.float64_t * _scaled_smoothed_diffuse_estimator cdef np.float64_t * _scaled_smoothed_diffuse1_estimator_cov cdef np.float64_t * _scaled_smoothed_diffuse2_estimator_cov
# Temporary cdef np.float64_t * _tmpL cdef np.float64_t * _tmpL2 cdef np.float64_t * _tmp0 cdef np.float64_t * _tmp00 cdef np.float64_t * _tmp000
# Functions cdef int (*smooth_estimators_measurement)( dKalmanSmoother, dKalmanFilter, dStatespace ) except * cdef int (*smooth_estimators_time)( dKalmanSmoother, dKalmanFilter, dStatespace ) cdef int (*smooth_state)( dKalmanSmoother, dKalmanFilter, dStatespace ) cdef int (*smooth_disturbances)( dKalmanSmoother, dKalmanFilter, dStatespace )
# cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef
cdef allocate_arrays(self) cdef int check_filter_method_changed(self) cdef int reset_filter_method(self, int force_reset=*) cpdef set_smoother_output(self, int smoother_output, int force_reset=*) cpdef set_smooth_method(self, int smooth_method) cpdef reset(self, int force_reset=*) cpdef seek(self, unsigned int t) cdef void initialize_statespace_object_pointers(self) except * cdef void initialize_filter_object_pointers(self) cdef void initialize_smoother_object_pointers(self) except * cdef void initialize_function_pointers(self) except * cdef void _initialize_temp_pointers(self) except *
# Single precision complexcdef class cKalmanSmoother(object): # Statespace object cdef readonly cStatespace model # Kalman filter cdef readonly cKalmanFilter kfilter
cdef readonly int t cdef readonly int smoother_output cdef readonly int smooth_method cdef readonly int _smooth_method cdef readonly int filter_method
cdef readonly np.complex64_t [::1,:] scaled_smoothed_estimator cdef readonly np.complex64_t [::1,:,:] scaled_smoothed_estimator_cov cdef readonly np.complex64_t [::1,:] smoothing_error cdef readonly np.complex64_t [::1,:] smoothed_state cdef readonly np.complex64_t [::1,:,:] smoothed_state_cov cdef readonly np.complex64_t [::1,:] smoothed_measurement_disturbance cdef readonly np.complex64_t [::1,:] smoothed_state_disturbance cdef readonly np.complex64_t [::1,:,:] smoothed_measurement_disturbance_cov cdef readonly np.complex64_t [::1,:,:] smoothed_state_disturbance_cov
cdef readonly np.complex64_t [::1,:,:] smoothed_state_autocov, innovations_transition cdef readonly np.complex64_t [::1,:] tmp_autocov
cdef readonly np.complex64_t [::1,:] scaled_smoothed_diffuse_estimator cdef readonly np.complex64_t [::1,:,:] scaled_smoothed_diffuse1_estimator_cov cdef readonly np.complex64_t [::1,:,:] scaled_smoothed_diffuse2_estimator_cov
cdef readonly np.complex64_t [:] selected_design cdef readonly np.complex64_t [:] selected_obs_cov
cdef readonly np.complex64_t [::1,:] tmpL, tmpL2, tmp0, tmp00, tmp000
# Statespace # cdef np.complex64_t * _design # cdef np.complex64_t * _obs_cov # cdef np.complex64_t * _transition # cdef np.complex64_t * _selection # cdef np.complex64_t * _state_cov
# Kalman filter # cdef np.complex64_t * _predicted_state # cdef np.complex64_t * _predicted_state_cov # cdef np.complex64_t * _kalman_gain
# cdef np.complex64_t * _tmp1 # cdef np.complex64_t * _tmp2 # cdef np.complex64_t * _tmp3 # cdef np.complex64_t * _tmp4
# Kalman smoother cdef np.complex64_t * _input_scaled_smoothed_estimator cdef np.complex64_t * _input_scaled_smoothed_estimator_cov
cdef np.complex64_t * _scaled_smoothed_estimator cdef np.complex64_t * _scaled_smoothed_estimator_cov cdef np.complex64_t * _smoothing_error cdef np.complex64_t * _smoothed_state cdef np.complex64_t * _smoothed_state_cov cdef np.complex64_t * _smoothed_measurement_disturbance cdef np.complex64_t * _smoothed_state_disturbance cdef np.complex64_t * _smoothed_measurement_disturbance_cov cdef np.complex64_t * _smoothed_state_disturbance_cov
cdef np.complex64_t * _innovations_transition cdef np.complex64_t * _smoothed_state_autocov cdef np.complex64_t * _tmp_autocov
cdef np.complex64_t * _input_scaled_smoothed_diffuse_estimator cdef np.complex64_t * _input_scaled_smoothed_diffuse1_estimator_cov cdef np.complex64_t * _input_scaled_smoothed_diffuse2_estimator_cov cdef np.complex64_t * _scaled_smoothed_diffuse_estimator cdef np.complex64_t * _scaled_smoothed_diffuse1_estimator_cov cdef np.complex64_t * _scaled_smoothed_diffuse2_estimator_cov
# Temporary cdef np.complex64_t * _tmpL cdef np.complex64_t * _tmpL2 cdef np.complex64_t * _tmp0 cdef np.complex64_t * _tmp00 cdef np.complex64_t * _tmp000
# Functions cdef int (*smooth_estimators_measurement)( cKalmanSmoother, cKalmanFilter, cStatespace ) except * cdef int (*smooth_estimators_time)( cKalmanSmoother, cKalmanFilter, cStatespace ) cdef int (*smooth_state)( cKalmanSmoother, cKalmanFilter, cStatespace ) cdef int (*smooth_disturbances)( cKalmanSmoother, cKalmanFilter, cStatespace )
# cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef
cdef allocate_arrays(self) cdef int check_filter_method_changed(self) cdef int reset_filter_method(self, int force_reset=*) cpdef set_smoother_output(self, int smoother_output, int force_reset=*) cpdef set_smooth_method(self, int smooth_method) cpdef reset(self, int force_reset=*) cpdef seek(self, unsigned int t) cdef void initialize_statespace_object_pointers(self) except * cdef void initialize_filter_object_pointers(self) cdef void initialize_smoother_object_pointers(self) except * cdef void initialize_function_pointers(self) except * cdef void _initialize_temp_pointers(self) except *
# Double precision complexcdef class zKalmanSmoother(object): # Statespace object cdef readonly zStatespace model # Kalman filter cdef readonly zKalmanFilter kfilter
cdef readonly int t cdef readonly int smoother_output cdef readonly int smooth_method cdef readonly int _smooth_method cdef readonly int filter_method
cdef readonly np.complex128_t [::1,:] scaled_smoothed_estimator cdef readonly np.complex128_t [::1,:,:] scaled_smoothed_estimator_cov cdef readonly np.complex128_t [::1,:] smoothing_error cdef readonly np.complex128_t [::1,:] smoothed_state cdef readonly np.complex128_t [::1,:,:] smoothed_state_cov cdef readonly np.complex128_t [::1,:] smoothed_measurement_disturbance cdef readonly np.complex128_t [::1,:] smoothed_state_disturbance cdef readonly np.complex128_t [::1,:,:] smoothed_measurement_disturbance_cov cdef readonly np.complex128_t [::1,:,:] smoothed_state_disturbance_cov
cdef readonly np.complex128_t [::1,:,:] smoothed_state_autocov, innovations_transition cdef readonly np.complex128_t [::1,:] tmp_autocov
cdef readonly np.complex128_t [::1,:] scaled_smoothed_diffuse_estimator cdef readonly np.complex128_t [::1,:,:] scaled_smoothed_diffuse1_estimator_cov cdef readonly np.complex128_t [::1,:,:] scaled_smoothed_diffuse2_estimator_cov
cdef readonly np.complex128_t [:] selected_design cdef readonly np.complex128_t [:] selected_obs_cov
cdef readonly np.complex128_t [::1,:] tmpL, tmpL2, tmp0, tmp00, tmp000
# Statespace # cdef np.complex128_t * _design # cdef np.complex128_t * _obs_cov # cdef np.complex128_t * _transition # cdef np.complex128_t * _selection # cdef np.complex128_t * _state_cov
# Kalman filter # cdef np.complex128_t * _predicted_state # cdef np.complex128_t * _predicted_state_cov # cdef np.complex128_t * _kalman_gain
# cdef np.complex128_t * _tmp1 # cdef np.complex128_t * _tmp2 # cdef np.complex128_t * _tmp3 # cdef np.complex128_t * _tmp4
# Kalman smoother cdef np.complex128_t * _input_scaled_smoothed_estimator cdef np.complex128_t * _input_scaled_smoothed_estimator_cov
cdef np.complex128_t * _scaled_smoothed_estimator cdef np.complex128_t * _scaled_smoothed_estimator_cov cdef np.complex128_t * _smoothing_error cdef np.complex128_t * _smoothed_state cdef np.complex128_t * _smoothed_state_cov cdef np.complex128_t * _smoothed_measurement_disturbance cdef np.complex128_t * _smoothed_state_disturbance cdef np.complex128_t * _smoothed_measurement_disturbance_cov cdef np.complex128_t * _smoothed_state_disturbance_cov
cdef np.complex128_t * _innovations_transition cdef np.complex128_t * _smoothed_state_autocov cdef np.complex128_t * _tmp_autocov
cdef np.complex128_t * _input_scaled_smoothed_diffuse_estimator cdef np.complex128_t * _input_scaled_smoothed_diffuse1_estimator_cov cdef np.complex128_t * _input_scaled_smoothed_diffuse2_estimator_cov cdef np.complex128_t * _scaled_smoothed_diffuse_estimator cdef np.complex128_t * _scaled_smoothed_diffuse1_estimator_cov cdef np.complex128_t * _scaled_smoothed_diffuse2_estimator_cov
# Temporary cdef np.complex128_t * _tmpL cdef np.complex128_t * _tmpL2 cdef np.complex128_t * _tmp0 cdef np.complex128_t * _tmp00 cdef np.complex128_t * _tmp000
# Functions cdef int (*smooth_estimators_measurement)( zKalmanSmoother, zKalmanFilter, zStatespace ) except * cdef int (*smooth_estimators_time)( zKalmanSmoother, zKalmanFilter, zStatespace ) cdef int (*smooth_state)( zKalmanSmoother, zKalmanFilter, zStatespace ) cdef int (*smooth_disturbances)( zKalmanSmoother, zKalmanFilter, zStatespace )
# cdef readonly int k_endog, k_states, k_posdef, k_endog2, k_states2, k_posdef2, k_endogstates, k_statesposdef
cdef allocate_arrays(self) cdef int check_filter_method_changed(self) cdef int reset_filter_method(self, int force_reset=*) cpdef set_smoother_output(self, int smoother_output, int force_reset=*) cpdef set_smooth_method(self, int smooth_method) cpdef reset(self, int force_reset=*) cpdef seek(self, unsigned int t) cdef void initialize_statespace_object_pointers(self) except * cdef void initialize_filter_object_pointers(self) cdef void initialize_smoother_object_pointers(self) except * cdef void initialize_function_pointers(self) except * cdef void _initialize_temp_pointers(self) except *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141r"""Utilities for Windows Registry manipulation
Notes:
winreg.SetValue -> sets _keys_ with default ("") valueswinreg.SetValueEx -> sets values with named contents
This is important when the argument has backslashes.SetValue will process the backslashes into a path of keysSetValueEx will create a value with name "path\with\keys"
Mnemonic: SetValueEx for "excalars" (scalars, named values)"""import winregfrom logging import getLogger
from ...utils import logged_run
log = getLogger(__name__)
def _reg_exe(*args, check=True): return logged_run(["reg.exe", *args, "/f"], check=True)
def register_file_extension(extension, identifier, command, icon=None, mode="user"): """ We want to achieve this. Entries ending in / denote keys; no trailing / means named value. If the item has a value attached to it, it's written after the : symbol.
HKEY_*/ # current user or local machine Software/ Classes/ .<extension>/ OpenWithProgids/ <extension-handler> ... <extension-handler>/: "a description of the file being handled" DefaultIcon: "path to the app icon" shell/ open/ command/: "the command to be executed when opening a file with this extension" """ with winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE # HKLM if mode == "system" else winreg.HKEY_CURRENT_USER, # HKCU r"Software\Classes", ) as key: # First we associate an extension with a handler winreg.SetValueEx( winreg.CreateKey(key, fr"{extension}\OpenWithProgids"), identifier, 0, winreg.REG_SZ, "", # presence of the key is enough ) log.debug("Created registry entry for extension '%s'", extension)
# Now we register the handler handler_desc = f"{extension} {identifier} handler" winreg.SetValue(key, identifier, winreg.REG_SZ, handler_desc) log.debug("Created registry entry for handler '%s'", identifier)
# and set the 'open' command subkey = rf"{identifier}\shell\open\command" # Use SetValue to create subkeys as necessary winreg.SetValue(key, subkey, winreg.REG_SZ, command) log.debug("Created registry entry for command '%s'", command)
if icon: subkey = winreg.OpenKey(key, identifier) winreg.SetValueEx(subkey, "DefaultIcon", 0, winreg.REG_SZ, icon) log.debug("Created registry entry for icon '%s'", icon)
# TODO: We can add contextual menu items too # via f"{handler_key}\shell\<Command Title>\command"
def unregister_file_extension(extension, identifier, mode="user"): root, root_str = ( (winreg.HKEY_LOCAL_MACHINE, "HKLM") if mode == "system" else (winreg.HKEY_CURRENT_USER, "HKCU") ) _reg_exe("delete", fr"{root_str}\Software\Classes\{identifier}")
try: with winreg.OpenKey( root, fr"Software\Classes\{extension}\OpenWithProgids", 0, winreg.KEY_ALL_ACCESS ) as key: try: winreg.QueryValueEx(key, identifier) except FileNotFoundError: log.debug( "Handler '%s' is not associated with extension '%s'", identifier, extension ) else: winreg.DeleteValue(key, identifier) except Exception as exc: log.exception("Could not check key '%s' for deletion", extension, exc_info=exc) raise
def register_url_protocol(protocol, command, identifier=None, icon=None, mode="user"): if mode == "system": key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, protocol) else: key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, fr"Software\Classes\{protocol}") with key: winreg.SetValueEx(key, "", 0, winreg.REG_SZ, f"URL:{protocol.title()}") winreg.SetValueEx(key, "URL Protocol", 0, winreg.REG_SZ, "") # SetValue creates sub keys when slashes are present; # SetValueEx creates a value with backslashes - we don't want that here winreg.SetValue(key, r"shell\open\command", winreg.REG_SZ, command) if icon: winreg.SetValueEx(key, "DefaultIcon", 0, winreg.REG_SZ, icon) if identifier: # We add this one value for traceability; not required winreg.SetValueEx(key, "_menuinst", 0, winreg.REG_SZ, identifier)
def unregister_url_protocol(protocol, identifier=None, mode="user"): if mode == "system": key_tuple = winreg.HKEY_CLASSES_ROOT, protocol key_str = fr"HKCR\{protocol}" else: key_tuple = winreg.HKEY_CURRENT_USER, fr"Software\Classes\{protocol}" key_str = fr"HKCU\Software\Classes\{protocol}" try: with winreg.OpenKey(*key_tuple) as key: value, _ = winreg.QueryValueEx(key, "_menuinst") delete = identifier is None or value == identifier except OSError as exc: log.exception("Could not check key %s for deletion", protocol, exc_info=exc) return
if delete: _reg_exe("delete", key_str, check=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""=================================================Orthogonal distance regression (:mod:`scipy.odr`)=================================================
.. currentmodule:: scipy.odr
Package Content===============
.. autosummary:: :toctree: generated/
Data -- The data to fit. RealData -- Data with weights as actual std. dev.s and/or covariances. Model -- Stores information about the function to be fit. ODR -- Gathers all info & manages the main fitting routine. Output -- Result from the fit. odr -- Low-level function for ODR.
OdrWarning -- Warning about potential problems when running ODR. OdrError -- Error exception. OdrStop -- Stop exception.
polynomial -- Factory function for a general polynomial model. exponential -- Exponential model multilinear -- Arbitrary-dimensional linear model unilinear -- Univariate linear model quadratic -- Quadratic model
Usage information=================
Introduction------------
Why Orthogonal Distance Regression (ODR)? Sometimes one hasmeasurement errors in the explanatory (a.k.a., "independent")variable(s), not just the response (a.k.a., "dependent") variable(s).Ordinary Least Squares (OLS) fitting procedures treat the data forexplanatory variables as fixed, i.e., not subject to error of any kind.Furthermore, OLS procedures require that the response variables be anexplicit function of the explanatory variables; sometimes making theequation explicit is impractical and/or introduces errors. ODR canhandle both of these cases with ease, and can even reduce to the OLScase if that is sufficient for the problem.
ODRPACK is a FORTRAN-77 library for performing ODR with possiblynon-linear fitting functions. It uses a modified trust-regionLevenberg-Marquardt-type algorithm [1]_ to estimate the functionparameters. The fitting functions are provided by Python functionsoperating on NumPy arrays. The required derivatives may be providedby Python functions as well, or may be estimated numerically. ODRPACKcan do explicit or implicit ODR fits, or it can do OLS. Input andoutput variables may be multidimensional. Weights can be provided toaccount for different variances of the observations, and evencovariances between dimensions of the variables.
The `scipy.odr` package offers an object-oriented interface toODRPACK, in addition to the low-level `odr` function.
Additional background information about ODRPACK can be found in the`ODRPACK User's Guide<https://docs.scipy.org/doc/external/odrpack_guide.pdf>`_, readingwhich is recommended.
Basic usage-----------
1. Define the function you want to fit against.::
def f(B, x): '''Linear function y = m*x + b''' # B is a vector of the parameters. # x is an array of the current x values. # x is in the same format as the x passed to Data or RealData. # # Return an array in the same format as y passed to Data or RealData. return B[0]*x + B[1]
2. Create a Model.::
linear = Model(f)
3. Create a Data or RealData instance.::
mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2))
or, when the actual covariances are known::
mydata = RealData(x, y, sx=sx, sy=sy)
4. Instantiate ODR with your data, model and initial parameter estimate.::
myodr = ODR(mydata, linear, beta0=[1., 2.])
5. Run the fit.::
myoutput = myodr.run()
6. Examine output.::
myoutput.pprint()
References----------.. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression," in "Statistical analysis of measurement error models and applications: proceedings of the AMS-IMS-SIAM joint summer research conference held June 10-16, 1989," Contemporary Mathematics, vol. 112, pg. 186, 1990.
"""# version: 0.7# author: Robert Kern <robert.kern@gmail.com># date: 2006-09-21
from ._odrpack import *from ._models import *from . import _add_newdocs
# Deprecated namespaces, to be removed in v2.0.0from . import models, odrpack
__all__ = [s for s in dir() if not (s.startswith('_') or s in ('odr_stop', 'odr_error'))]
from scipy._lib._testutils import PytestTestertest = PytestTester(__name__)del PytestTester123456789101112131415161718192021222324252627282930313233343536373839404142contourpy-1.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
contourpy-1.3.2.dist-info/LICENSE,sha256=NBcJefxk9PXm36Zu8n3sMU___FhSAAxg9INuwd-_FW4,1534
contourpy-1.3.2.dist-info/METADATA,sha256=DYYPfLivjoUAXCCUmeDKJdqFFbS2eRXui4i4hSwxbAg,5461
contourpy-1.3.2.dist-info/RECORD,,
contourpy-1.3.2.dist-info/WHEEL,sha256=sZM_NeUMz2G4fDenMf11eikcCxcLaQWiYRmjwQBavQs,137
contourpy/__init__.py,sha256=Vi2YbtUhM9VxYPY3PBvxfu0xZYr6fBysl5gQPJEo88k,11831
contourpy/__pycache__/__init__.cpython-310.pyc,,
contourpy/__pycache__/_version.cpython-310.pyc,,
contourpy/__pycache__/array.cpython-310.pyc,,
contourpy/__pycache__/chunk.cpython-310.pyc,,
contourpy/__pycache__/convert.cpython-310.pyc,,
contourpy/__pycache__/dechunk.cpython-310.pyc,,
contourpy/__pycache__/enum_util.cpython-310.pyc,,
contourpy/__pycache__/typecheck.cpython-310.pyc,,
contourpy/__pycache__/types.cpython-310.pyc,,
contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so,sha256=8it_MHwflBYc2jRua5KVBXY14gZO7MuH6GAuQVm8V-E,854312
contourpy/_contourpy.pyi,sha256=fvtccxkiZwGb6qYag7Fp4E8bsFmAIjAmobf8LNxqfgc,7122
contourpy/_version.py,sha256=HgKA3RqZvC7slo8MgLyffCGwJbQ3cY6I7oUMFvGLWps,22
contourpy/array.py,sha256=4WwLuiZe30rizn_raymmY13OzE6hlCsDOO8kuVFOP18,8979
contourpy/chunk.py,sha256=8njDQqlpuD22RjaaCyA75FXQsSQDY5hZGJSrxFpvGGU,3279
contourpy/convert.py,sha256=mhyn7prEoWCnf0igaH-VqDwlk-CegFsZ4qOy2LL-hpU,26154
contourpy/dechunk.py,sha256=EgFL6hw5H54ccuof4tJ2ehdnktT7trgZjiZqppsH8QI,7756
contourpy/enum_util.py,sha256=o8MItJRs08oqzwPP3IwC75BBAY9Qq95saIzjkXBXwqA,1519
contourpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
contourpy/typecheck.py,sha256=t1nvvCuKMYva1Zx4fc30EpdKFcO0Enz3n_UFfXBsq9o,10747
contourpy/types.py,sha256=2K4T5tJpMIjYrkkg1Lqh3C2ZKlnOhnMtYmtwz92l_y8,247
contourpy/util/__init__.py,sha256=eVhJ_crOHL7nkG4Kb0dOo7NL4WHMy_Px665aAN_3d-8,118
contourpy/util/__pycache__/__init__.cpython-310.pyc,,
contourpy/util/__pycache__/_build_config.cpython-310.pyc,,
contourpy/util/__pycache__/bokeh_renderer.cpython-310.pyc,,
contourpy/util/__pycache__/bokeh_util.cpython-310.pyc,,
contourpy/util/__pycache__/data.cpython-310.pyc,,
contourpy/util/__pycache__/mpl_renderer.cpython-310.pyc,,
contourpy/util/__pycache__/mpl_util.cpython-310.pyc,,
contourpy/util/__pycache__/renderer.cpython-310.pyc,,
contourpy/util/_build_config.py,sha256=uFmEfpQ4-HVkN0zZi7c2060J1i2uoaPsvkS4pf0XdiY,1848
contourpy/util/bokeh_renderer.py,sha256=sOAZKyN11296muuLQ4uhQYCM4eaMwjnxUFrbbIxucmY,13959
contourpy/util/bokeh_util.py,sha256=wc-S3ewBUYWyIkEv9jkhFySIergjLQl4Z0UEVnE0HhA,2804
contourpy/util/data.py,sha256=-7SSGMLX_gN-1H2JzpNSEB_EcEF_uMtYdOo_ePRIcg8,2586
contourpy/util/mpl_renderer.py,sha256=qPWMxDL_n-4dg9gOIHX-Va2UQz6n98eJdIRszpYr2AU,20125
contourpy/util/mpl_util.py,sha256=0Jz5f-aA9XMWlpO2pDnHbkVgxIiw4SY_ysxf_gACWEo,3452
contourpy/util/renderer.py,sha256=8CBHzPmVsFPfqsWxqrxGBhqFpJhVeFHFeDzVXAgT8Fc,5118123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150""" pygments.styles.nord ~~~~~~~~~~~~~~~~~~~~
pygments version of the "nord" theme by Arctic Ice Studio https://www.nordtheme.com/
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details."""
from pygments.style import Stylefrom pygments.token import Keyword, Name, Comment, String, Error, Number, \ Operator, Generic, Whitespace, Punctuation, Text, Token
class NordStyle(Style): """ Pygments version of the "nord" theme by Arctic Ice Studio. """
line_number_color = "#D8DEE9" line_number_background_color = "#242933" line_number_special_color = "#242933" line_number_special_background_color = "#D8DEE9"
background_color = "#2E3440" highlight_color = "#3B4252"
styles = { Token: "#d8dee9",
Whitespace: '#d8dee9', Punctuation: '#eceff4',
Comment: 'italic #616e87', Comment.Preproc: '#5e81ac',
Keyword: 'bold #81a1c1', Keyword.Pseudo: 'nobold #81a1c1', Keyword.Type: 'nobold #81a1c1',
Operator: 'bold #81a1c1', Operator.Word: 'bold #81a1c1',
Name: '#d8dee9', Name.Builtin: '#81a1c1', Name.Function: '#88c0d0', Name.Class: '#8fbcbb', Name.Namespace: '#8fbcbb', Name.Exception: '#bf616a', Name.Variable: '#d8dee9', Name.Constant: '#8fbcbb', Name.Entity: '#d08770', Name.Attribute: '#8fbcbb', Name.Tag: '#81a1c1', Name.Decorator: '#d08770',
String: '#a3be8c', String.Doc: '#616e87', String.Interpol: '#a3be8c', String.Escape: '#ebcb8b', String.Regex: '#ebcb8b', String.Symbol: '#a3be8c', String.Other: '#a3be8c',
Number: '#b48ead',
Generic.Heading: 'bold #88c0d0', Generic.Subheading: 'bold #88c0d0', Generic.Deleted: '#bf616a', Generic.Inserted: '#a3be8c', Generic.Error: '#bf616a', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: 'bold #616e88', Generic.Output: '#d8dee9', Generic.Traceback: '#bf616a',
Error: '#bf616a', Text: '#d8dee9', }
class NordDarkerStyle(Style): """ Pygments version of a darker "nord" theme by Arctic Ice Studio """
line_number_color = "#D8DEE9" line_number_background_color = "#242933" line_number_special_color = "#242933" line_number_special_background_color = "#D8DEE9"
background_color = "#242933" highlight_color = "#3B4252"
styles = { Token: "#d8dee9",
Whitespace: '#d8dee9', Punctuation: '#eceff4',
Comment: 'italic #616e87', Comment.Preproc: '#5e81ac',
Keyword: 'bold #81a1c1', Keyword.Pseudo: 'nobold #81a1c1', Keyword.Type: 'nobold #81a1c1',
Operator: 'bold #81a1c1', Operator.Word: 'bold #81a1c1',
Name: '#d8dee9', Name.Builtin: '#81a1c1', Name.Function: '#88c0d0', Name.Class: '#8fbcbb', Name.Namespace: '#8fbcbb', Name.Exception: '#bf616a', Name.Variable: '#d8dee9', Name.Constant: '#8fbcbb', Name.Entity: '#d08770', Name.Attribute: '#8fbcbb', Name.Tag: '#81a1c1', Name.Decorator: '#d08770',
String: '#a3be8c', String.Doc: '#616e87', String.Interpol: '#a3be8c', String.Escape: '#ebcb8b', String.Regex: '#ebcb8b', String.Symbol: '#a3be8c', String.Other: '#a3be8c',
Number: '#b48ead',
Generic.Heading: 'bold #88c0d0', Generic.Subheading: 'bold #88c0d0', Generic.Deleted: '#bf616a', Generic.Inserted: '#a3be8c', Generic.Error: '#bf616a', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: 'bold #616e88', Generic.Output: '#d8dee9', Generic.Traceback: '#bf616a',
Error: '#bf616a', Text: '#d8dee9', }1234567891011121314151617181920212223242526272829303132333435363738#pragma once
#include <stdexcept>
#include <c10/util/Optional.h>#include <torch/csrc/Export.h>#include <string>
namespace torch::jit {
struct TORCH_API JITException : public std::runtime_error { explicit JITException( const std::string& msg, c10::optional<std::string> python_class_name = c10::nullopt, c10::optional<std::string> original_msg = c10::nullopt);
c10::optional<std::string> getPythonClassName() const { return python_class_name_; }
// the original msg if this is from a python exception. The interpretor has // changed the original message by adding "The following operation failed in // the TorchScript interpreter." in front of it in the handleError function. c10::optional<std::string> getOriginalMsg() const { return original_msg_; }
static const std::string& getCaughtOriginalMsg(); static const std::string& getCaughtPythonClassName(); static void setCaughtOriginalMsg(const std::string& msg); static void setCaughtPythonClassName(const std::string& pythonClassName);
private: c10::optional<std::string> python_class_name_; c10::optional<std::string> original_msg_;};
} // namespace torch::jit12345678910111213141516171819202122232425262728293031323334353637383940414243#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>
#include <ATen/ops/empty_like_ops.h>
namespace at {
// aten::empty_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensorinline at::Tensor empty_like(const at::Tensor & self, at::TensorOptions options={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt) { return at::_ops::empty_like::call(self, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), c10::impl::check_tensor_options_and_extract_memory_format(options, memory_format));}// aten::empty_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensorinline at::Tensor empty_like(const at::Tensor & self, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<at::MemoryFormat> memory_format) { return at::_ops::empty_like::call(self, dtype, layout, device, pin_memory, memory_format);}
// aten::empty_like.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & empty_like_out(at::Tensor & out, const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format=c10::nullopt) { return at::_ops::empty_like_out::call(self, memory_format, out);}// aten::empty_like.out(Tensor self, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & empty_like_outf(const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out) { return at::_ops::empty_like_out::call(self, memory_format, out);}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713#! /usr/bin/env python3
import sysif __name__ == "__main__": sys.modules['idlelib.pyshell'] = sys.modules['__main__']
try: from tkinter import *except ImportError: print("** IDLE can't import Tkinter.\n" "Your Python may not be configured for Tk. **", file=sys.__stderr__) raise SystemExit(1)
# Valid arguments for the ...Awareness call below are defined in the following.# https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspxif sys.platform == 'win32': try: import ctypes PROCESS_SYSTEM_DPI_AWARE = 1 # Int required. ctypes.OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE) except (ImportError, AttributeError, OSError): pass
from tkinter import messageboxif TkVersion < 8.5: root = Tk() # otherwise create root in main root.withdraw() from idlelib.run import fix_scaling fix_scaling(root) messagebox.showerror("Idle Cannot Start", "Idle requires tcl/tk 8.5+, not %s." % TkVersion, parent=root) raise SystemExit(1)
from code import InteractiveInterpreterimport itertoolsimport linecacheimport osimport os.pathfrom platform import python_versionimport reimport socketimport subprocessfrom textwrap import TextWrapperimport threadingimport timeimport tokenizeimport warnings
from idlelib.colorizer import ColorDelegatorfrom idlelib.config import idleConffrom idlelib.delegator import Delegatorfrom idlelib import debuggerfrom idlelib import debugger_rfrom idlelib.editor import EditorWindow, fixwordbreaksfrom idlelib.filelist import FileListfrom idlelib.outwin import OutputWindowfrom idlelib import replacefrom idlelib import rpcfrom idlelib.run import idle_formatwarning, StdInputFile, StdOutputFilefrom idlelib.undo import UndoDelegator
# Default for testing; defaults to True in main() for running.use_subprocess = False
HOST = '127.0.0.1' # python execution server on localhost loopbackPORT = 0 # someday pass in host, port for remote debug capability
try: # In case IDLE started with -n. eof = 'Ctrl-D (end-of-file)' exit.eof = eof quit.eof = eofexcept NameError: # In case python started with -S. pass
# Override warnings module to write to warning_stream. Initialize to send IDLE# internal warnings to the console. ScriptBinding.check_syntax() will# temporarily redirect the stream to the shell window to display warnings when# checking user's code.warning_stream = sys.__stderr__ # None, at least on Windows, if no console.
def idle_showwarning( message, category, filename, lineno, file=None, line=None): """Show Idle-format warning (after replacing warnings.showwarning).
The differences are the formatter called, the file=None replacement, which can be None, the capture of the consequence AttributeError, and the output of a hard-coded prompt. """ if file is None: file = warning_stream try: file.write(idle_formatwarning( message, category, filename, lineno, line=line)) file.write(">>> ") except (AttributeError, OSError): pass # if file (probably __stderr__) is invalid, skip warning.
_warnings_showwarning = None
def capture_warnings(capture): "Replace warning.showwarning with idle_showwarning, or reverse."
global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = idle_showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None
capture_warnings(True)
def extended_linecache_checkcache(filename=None, orig_checkcache=linecache.checkcache): """Extend linecache.checkcache to preserve the <pyshell#...> entries
Rather than repeating the linecache code, patch it to save the <pyshell#...> entries, call the original linecache.checkcache() (skipping them), and then restore the saved entries.
orig_checkcache is bound at definition time to the original method, allowing it to be patched. """ cache = linecache.cache save = {} for key in list(cache): if key[:1] + key[-1:] == '<>': save[key] = cache.pop(key) orig_checkcache(filename) cache.update(save)
# Patch linecache.checkcache():linecache.checkcache = extended_linecache_checkcache
class PyShellEditorWindow(EditorWindow): "Regular text edit window in IDLE, supports breakpoints"
def __init__(self, *args): self.breakpoints = [] EditorWindow.__init__(self, *args) self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here) self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here) self.text.bind("<<open-python-shell>>", self.flist.open_shell)
#TODO: don't read/write this from/to .idlerc when testing self.breakpointPath = os.path.join( idleConf.userdir, 'breakpoints.lst') # whenever a file is changed, restore breakpoints def filename_changed_hook(old_hook=self.io.filename_change_hook, self=self): self.restore_file_breaks() old_hook() self.io.set_filename_change_hook(filename_changed_hook) if self.io.filename: self.restore_file_breaks() self.color_breakpoint_text()
rmenu_specs = [ ("Cut", "<<cut>>", "rmenu_check_cut"), ("Copy", "<<copy>>", "rmenu_check_copy"), ("Paste", "<<paste>>", "rmenu_check_paste"), (None, None, None), ("Set Breakpoint", "<<set-breakpoint-here>>", None), ("Clear Breakpoint", "<<clear-breakpoint-here>>", None) ]
def color_breakpoint_text(self, color=True): "Turn colorizing of breakpoint text on or off" if self.io is None: # possible due to update in restore_file_breaks return if color: theme = idleConf.CurrentTheme() cfg = idleConf.GetHighlight(theme, "break") else: cfg = {'foreground': '', 'background': ''} self.text.tag_config('BREAK', cfg)
def set_breakpoint(self, lineno): text = self.text filename = self.io.filename text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1)) try: self.breakpoints.index(lineno) except ValueError: # only add if missing, i.e. do once self.breakpoints.append(lineno) try: # update the subprocess debugger debug = self.flist.pyshell.interp.debugger debug.set_breakpoint_here(filename, lineno) except: # but debugger may not be active right now.... pass
def set_breakpoint_here(self, event=None): text = self.text filename = self.io.filename if not filename: text.bell() return lineno = int(float(text.index("insert"))) self.set_breakpoint(lineno)
def clear_breakpoint_here(self, event=None): text = self.text filename = self.io.filename if not filename: text.bell() return lineno = int(float(text.index("insert"))) try: self.breakpoints.remove(lineno) except: pass text.tag_remove("BREAK", "insert linestart",\ "insert lineend +1char") try: debug = self.flist.pyshell.interp.debugger debug.clear_breakpoint_here(filename, lineno) except: pass
def clear_file_breaks(self): if self.breakpoints: text = self.text filename = self.io.filename if not filename: text.bell() return self.breakpoints = [] text.tag_remove("BREAK", "1.0", END) try: debug = self.flist.pyshell.interp.debugger debug.clear_file_breaks(filename) except: pass
def store_file_breaks(self): "Save breakpoints when file is saved" # XXX 13 Dec 2002 KBK Currently the file must be saved before it can # be run. The breaks are saved at that time. If we introduce # a temporary file save feature the save breaks functionality # needs to be re-verified, since the breaks at the time the # temp file is created may differ from the breaks at the last # permanent save of the file. Currently, a break introduced # after a save will be effective, but not persistent. # This is necessary to keep the saved breaks synched with the # saved file. # # Breakpoints are set as tagged ranges in the text. # Since a modified file has to be saved before it is # run, and since self.breakpoints (from which the subprocess # debugger is loaded) is updated during the save, the visible # breaks stay synched with the subprocess even if one of these # unexpected breakpoint deletions occurs. breaks = self.breakpoints filename = self.io.filename try: with open(self.breakpointPath, "r") as fp: lines = fp.readlines() except OSError: lines = [] try: with open(self.breakpointPath, "w") as new_file: for line in lines: if not line.startswith(filename + '='): new_file.write(line) self.update_breakpoints() breaks = self.breakpoints if breaks: new_file.write(filename + '=' + str(breaks) + '\n') except OSError as err: if not getattr(self.root, "breakpoint_error_displayed", False): self.root.breakpoint_error_displayed = True messagebox.showerror(title='IDLE Error', message='Unable to update breakpoint list:\n%s' % str(err), parent=self.text)
def restore_file_breaks(self): self.text.update() # this enables setting "BREAK" tags to be visible if self.io is None: # can happen if IDLE closes due to the .update() call return filename = self.io.filename if filename is None: return if os.path.isfile(self.breakpointPath): with open(self.breakpointPath, "r") as fp: lines = fp.readlines() for line in lines: if line.startswith(filename + '='): breakpoint_linenumbers = eval(line[len(filename)+1:]) for breakpoint_linenumber in breakpoint_linenumbers: self.set_breakpoint(breakpoint_linenumber)
def update_breakpoints(self): "Retrieves all the breakpoints in the current window" text = self.text ranges = text.tag_ranges("BREAK") linenumber_list = self.ranges_to_linenumbers(ranges) self.breakpoints = linenumber_list
def ranges_to_linenumbers(self, ranges): lines = [] for index in range(0, len(ranges), 2): lineno = int(float(ranges[index].string)) end = int(float(ranges[index+1].string)) while lineno < end: lines.append(lineno) lineno += 1 return lines
# XXX 13 Dec 2002 KBK Not used currently# def saved_change_hook(self):# "Extend base method - clear breaks if module is modified"# if not self.get_saved():# self.clear_file_breaks()# EditorWindow.saved_change_hook(self)
def _close(self): "Extend base method - clear breaks when module is closed" self.clear_file_breaks() EditorWindow._close(self)
class PyShellFileList(FileList): "Extend base class: IDLE supports a shell and breakpoints"
# override FileList's class variable, instances return PyShellEditorWindow # instead of EditorWindow when new edit windows are created. EditorWindow = PyShellEditorWindow
pyshell = None
def open_shell(self, event=None): if self.pyshell: self.pyshell.top.wakeup() else: self.pyshell = PyShell(self) if self.pyshell: if not self.pyshell.begin(): return None return self.pyshell
class ModifiedColorDelegator(ColorDelegator): "Extend base class: colorizer for the shell window itself" def recolorize_main(self): self.tag_remove("TODO", "1.0", "iomark") self.tag_add("SYNC", "1.0", "iomark") ColorDelegator.recolorize_main(self)
def removecolors(self): # Don't remove shell color tags before "iomark" for tag in self.tagdefs: self.tag_remove(tag, "iomark", "end")
class ModifiedUndoDelegator(UndoDelegator): "Extend base class: forbid insert/delete before the I/O mark" def insert(self, index, chars, tags=None): try: if self.delegate.compare(index, "<", "iomark"): self.delegate.bell() return except TclError: pass UndoDelegator.insert(self, index, chars, tags)
def delete(self, index1, index2=None): try: if self.delegate.compare(index1, "<", "iomark"): self.delegate.bell() return except TclError: pass UndoDelegator.delete(self, index1, index2)
def undo_event(self, event): # Temporarily monkey-patch the delegate's .insert() method to # always use the "stdin" tag. This is needed for undo-ing # deletions to preserve the "stdin" tag, because UndoDelegator # doesn't preserve tags for deleted text. orig_insert = self.delegate.insert self.delegate.insert = \ lambda index, chars: orig_insert(index, chars, "stdin") try: super().undo_event(event) finally: self.delegate.insert = orig_insert
class UserInputTaggingDelegator(Delegator): """Delegator used to tag user input with "stdin".""" def insert(self, index, chars, tags=None): if tags is None: tags = "stdin" self.delegate.insert(index, chars, tags)
class MyRPCClient(rpc.RPCClient):
def handle_EOF(self): "Override the base class - just re-raise EOFError" raise EOFError
def restart_line(width, filename): # See bpo-38141. """Return width long restart line formatted with filename.
Fill line with balanced '='s, with any extras and at least one at the beginning. Do not end with a trailing space. """ tag = f"= RESTART: {filename or 'Shell'} =" if width >= len(tag): div, mod = divmod((width -len(tag)), 2) return f"{(div+mod)*'='}{tag}{div*'='}" else: return tag[:-2] # Remove ' ='.
class ModifiedInterpreter(InteractiveInterpreter):
def __init__(self, tkconsole): self.tkconsole = tkconsole locals = sys.modules['__main__'].__dict__ InteractiveInterpreter.__init__(self, locals=locals) self.restarting = False self.subprocess_arglist = None self.port = PORT self.original_compiler_flags = self.compile.compiler.flags
_afterid = None rpcclt = None rpcsubproc = None
def spawn_subprocess(self): if self.subprocess_arglist is None: self.subprocess_arglist = self.build_subprocess_arglist() self.rpcsubproc = subprocess.Popen(self.subprocess_arglist)
def build_subprocess_arglist(self): assert (self.port!=0), ( "Socket should have been assigned a port number.") w = ['-W' + s for s in sys.warnoptions] # Maybe IDLE is installed and is being accessed via sys.path, # or maybe it's not installed and the idle.py script is being # run from the IDLE source directory. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', default=False, type='bool') command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,) return [sys.executable] + w + ["-c", command, str(self.port)]
def start_subprocess(self): addr = (HOST, self.port) # GUI makes several attempts to acquire socket, listens for connection for i in range(3): time.sleep(i) try: self.rpcclt = MyRPCClient(addr) break except OSError: pass else: self.display_port_binding_error() return None # if PORT was 0, system will assign an 'ephemeral' port. Find it out: self.port = self.rpcclt.listening_sock.getsockname()[1] # if PORT was not 0, probably working with a remote execution server if PORT != 0: # To allow reconnection within the 2MSL wait (cf. Stevens TCP # V1, 18.6), set SO_REUSEADDR. Note that this can be problematic # on Windows since the implementation allows two active sockets on # the same address! self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.spawn_subprocess() #time.sleep(20) # test to simulate GUI not accepting connection # Accept the connection from the Python execution server self.rpcclt.listening_sock.settimeout(10) try: self.rpcclt.accept() except TimeoutError: self.display_no_subprocess_error() return None self.rpcclt.register("console", self.tkconsole) self.rpcclt.register("stdin", self.tkconsole.stdin) self.rpcclt.register("stdout", self.tkconsole.stdout) self.rpcclt.register("stderr", self.tkconsole.stderr) self.rpcclt.register("flist", self.tkconsole.flist) self.rpcclt.register("linecache", linecache) self.rpcclt.register("interp", self) self.transfer_path(with_cwd=True) self.poll_subprocess() return self.rpcclt
def restart_subprocess(self, with_cwd=False, filename=''): if self.restarting: return self.rpcclt self.restarting = True # close only the subprocess debugger debug = self.getdebugger() if debug: try: # Only close subprocess debugger, don't unregister gui_adap! debugger_r.close_subprocess_debugger(self.rpcclt) except: pass # Kill subprocess, spawn a new one, accept connection. self.rpcclt.close() self.terminate_subprocess() console = self.tkconsole was_executing = console.executing console.executing = False self.spawn_subprocess() try: self.rpcclt.accept() except TimeoutError: self.display_no_subprocess_error() return None self.transfer_path(with_cwd=with_cwd) console.stop_readline() # annotate restart in shell window and mark it console.text.delete("iomark", "end-1c") console.write('\n') console.write(restart_line(console.width, filename)) console.text.mark_set("restart", "end-1c") console.text.mark_gravity("restart", "left") if not filename: console.showprompt() # restart subprocess debugger if debug: # Restarted debugger connects to current instance of debug GUI debugger_r.restart_subprocess_debugger(self.rpcclt) # reload remote debugger breakpoints for all PyShellEditWindows debug.load_breakpoints() self.compile.compiler.flags = self.original_compiler_flags self.restarting = False return self.rpcclt
def __request_interrupt(self): self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
def interrupt_subprocess(self): threading.Thread(target=self.__request_interrupt).start()
def kill_subprocess(self): if self._afterid is not None: self.tkconsole.text.after_cancel(self._afterid) try: self.rpcclt.listening_sock.close() except AttributeError: # no socket pass try: self.rpcclt.close() except AttributeError: # no socket pass self.terminate_subprocess() self.tkconsole.executing = False self.rpcclt = None
def terminate_subprocess(self): "Make sure subprocess is terminated" try: self.rpcsubproc.kill() except OSError: # process already terminated return else: try: self.rpcsubproc.wait() except OSError: return
def transfer_path(self, with_cwd=False): if with_cwd: # Issue 13506 path = [''] # include Current Working Directory path.extend(sys.path) else: path = sys.path
self.runcommand("""if 1: import sys as _sys _sys.path = %r del _sys \n""" % (path,))
active_seq = None
def poll_subprocess(self): clt = self.rpcclt if clt is None: return try: response = clt.pollresponse(self.active_seq, wait=0.05) except (EOFError, OSError, KeyboardInterrupt): # lost connection or subprocess terminated itself, restart # [the KBI is from rpc.SocketIO.handle_EOF()] if self.tkconsole.closing: return response = None self.restart_subprocess() if response: self.tkconsole.resetoutput() self.active_seq = None how, what = response console = self.tkconsole.console if how == "OK": if what is not None: print(repr(what), file=console) elif how == "EXCEPTION": if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): self.remote_stack_viewer() elif how == "ERROR": errmsg = "pyshell.ModifiedInterpreter: Subprocess ERROR:\n" print(errmsg, what, file=sys.__stderr__) print(errmsg, what, file=console) # we received a response to the currently active seq number: try: self.tkconsole.endexecuting() except AttributeError: # shell may have closed pass # Reschedule myself if not self.tkconsole.closing: self._afterid = self.tkconsole.text.after( self.tkconsole.pollinterval, self.poll_subprocess)
debugger = None
def setdebugger(self, debugger): self.debugger = debugger
def getdebugger(self): return self.debugger
def open_remote_stack_viewer(self): """Initiate the remote stack viewer from a separate thread.
This method is called from the subprocess, and by returning from this method we allow the subprocess to unblock. After a bit the shell requests the subprocess to open the remote stack viewer which returns a static object looking at the last exception. It is queried through the RPC mechanism.
""" self.tkconsole.text.after(300, self.remote_stack_viewer) return
def remote_stack_viewer(self): from idlelib import debugobj_r oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {}) if oid is None: self.tkconsole.root.bell() return item = debugobj_r.StubObjectTreeItem(self.rpcclt, oid) from idlelib.tree import ScrolledCanvas, TreeNode top = Toplevel(self.tkconsole.root) theme = idleConf.CurrentTheme() background = idleConf.GetHighlight(theme, 'normal')['background'] sc = ScrolledCanvas(top, bg=background, highlightthickness=0) sc.frame.pack(expand=1, fill="both") node = TreeNode(sc.canvas, None, item) node.expand() # XXX Should GC the remote tree when closing the window
gid = 0
def execsource(self, source): "Like runsource() but assumes complete exec source" filename = self.stuffsource(source) self.execfile(filename, source)
def execfile(self, filename, source=None): "Execute an existing file" if source is None: with tokenize.open(filename) as fp: source = fp.read() if use_subprocess: source = (f"__file__ = r'''{os.path.abspath(filename)}'''\n" + source + "\ndel __file__") try: code = compile(source, filename, "exec") except (OverflowError, SyntaxError): self.tkconsole.resetoutput() print('*** Error in script or command!\n' 'Traceback (most recent call last):', file=self.tkconsole.stderr) InteractiveInterpreter.showsyntaxerror(self, filename) self.tkconsole.showprompt() else: self.runcode(code)
def runsource(self, source): "Extend base class method: Stuff the source in the line cache first" filename = self.stuffsource(source) # at the moment, InteractiveInterpreter expects str assert isinstance(source, str) # InteractiveInterpreter.runsource() calls its runcode() method, # which is overridden (see below) return InteractiveInterpreter.runsource(self, source, filename)
def stuffsource(self, source): "Stuff source in the filename cache" filename = "<pyshell#%d>" % self.gid self.gid = self.gid + 1 lines = source.split("\n") linecache.cache[filename] = len(source)+1, 0, lines, filename return filename
def prepend_syspath(self, filename): "Prepend sys.path with file's directory if not already included" self.runcommand("""if 1: _filename = %r import sys as _sys from os.path import dirname as _dirname _dir = _dirname(_filename) if not _dir in _sys.path: _sys.path.insert(0, _dir) del _filename, _sys, _dirname, _dir \n""" % (filename,))
def showsyntaxerror(self, filename=None): """Override Interactive Interpreter method: Use Colorizing
Color the offending position instead of printing it and pointing at it with a caret.
""" tkconsole = self.tkconsole text = tkconsole.text text.tag_remove("ERROR", "1.0", "end") type, value, tb = sys.exc_info() msg = getattr(value, 'msg', '') or value or "<no detail available>" lineno = getattr(value, 'lineno', '') or 1 offset = getattr(value, 'offset', '') or 0 if offset == 0: lineno += 1 #mark end of offending line if lineno == 1: pos = "iomark + %d chars" % (offset-1) else: pos = "iomark linestart + %d lines + %d chars" % \ (lineno-1, offset-1) tkconsole.colorize_syntax_error(text, pos) tkconsole.resetoutput() self.write("SyntaxError: %s\n" % msg) tkconsole.showprompt()
def showtraceback(self): "Extend base class method to reset output properly" self.tkconsole.resetoutput() self.checklinecache() InteractiveInterpreter.showtraceback(self) if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): self.tkconsole.open_stack_viewer()
def checklinecache(self): c = linecache.cache for key in list(c.keys()): if key[:1] + key[-1:] != "<>": del c[key]
def runcommand(self, code): "Run the code without invoking the debugger" # The code better not raise an exception! if self.tkconsole.executing: self.display_executing_dialog() return 0 if self.rpcclt: self.rpcclt.remotequeue("exec", "runcode", (code,), {}) else: exec(code, self.locals) return 1
def runcode(self, code): "Override base class method" if self.tkconsole.executing: self.restart_subprocess() self.checklinecache() debugger = self.debugger try: self.tkconsole.beginexecuting() if not debugger and self.rpcclt is not None: self.active_seq = self.rpcclt.asyncqueue("exec", "runcode", (code,), {}) elif debugger: debugger.run(code, self.locals) else: exec(code, self.locals) except SystemExit: if not self.tkconsole.closing: if messagebox.askyesno( "Exit?", "Do you want to exit altogether?", default="yes", parent=self.tkconsole.text): raise else: self.showtraceback() else: raise except: if use_subprocess: print("IDLE internal error in runcode()", file=self.tkconsole.stderr) self.showtraceback() self.tkconsole.endexecuting() else: if self.tkconsole.canceled: self.tkconsole.canceled = False print("KeyboardInterrupt", file=self.tkconsole.stderr) else: self.showtraceback() finally: if not use_subprocess: try: self.tkconsole.endexecuting() except AttributeError: # shell may have closed pass
def write(self, s): "Override base class method" return self.tkconsole.stderr.write(s)
def display_port_binding_error(self): messagebox.showerror( "Port Binding Error", "IDLE can't bind to a TCP/IP port, which is necessary to " "communicate with its Python execution server. This might be " "because no networking is installed on this computer. " "Run IDLE with the -n command line switch to start without a " "subprocess and refer to Help/IDLE Help 'Running without a " "subprocess' for further details.", parent=self.tkconsole.text)
def display_no_subprocess_error(self): messagebox.showerror( "Subprocess Connection Error", "IDLE's subprocess didn't make connection.\n" "See the 'Startup failure' section of the IDLE doc, online at\n" "https://docs.python.org/3/library/idle.html#startup-failure", parent=self.tkconsole.text)
def display_executing_dialog(self): messagebox.showerror( "Already executing", "The Python Shell window is already executing a command; " "please wait until it is finished.", parent=self.tkconsole.text)
class PyShell(OutputWindow): from idlelib.squeezer import Squeezer
shell_title = "IDLE Shell " + python_version()
# Override classes ColorDelegator = ModifiedColorDelegator UndoDelegator = ModifiedUndoDelegator
# Override menus menu_specs = [ ("file", "_File"), ("edit", "_Edit"), ("debug", "_Debug"), ("options", "_Options"), ("window", "_Window"), ("help", "_Help"), ]
# Extend right-click context menu rmenu_specs = OutputWindow.rmenu_specs + [ ("Squeeze", "<<squeeze-current-text>>"), ] _idx = 1 + len(list(itertools.takewhile( lambda rmenu_item: rmenu_item[0] != "Copy", rmenu_specs) )) rmenu_specs.insert(_idx, ("Copy with prompts", "<<copy-with-prompts>>", "rmenu_check_copy")) del _idx
allow_line_numbers = False user_input_insert_tags = "stdin"
# New classes from idlelib.history import History from idlelib.sidebar import ShellSidebar
def __init__(self, flist=None): if use_subprocess: ms = self.menu_specs if ms[2][0] != "shell": ms.insert(2, ("shell", "She_ll")) self.interp = ModifiedInterpreter(self) if flist is None: root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root)
self.shell_sidebar = None # initialized below
OutputWindow.__init__(self, flist, None, None)
self.usetabs = False # indentwidth must be 8 when using tabs. See note in EditorWindow: self.indentwidth = 4
self.sys_ps1 = sys.ps1 if hasattr(sys, 'ps1') else '>>>\n' self.prompt_last_line = self.sys_ps1.split('\n')[-1] self.prompt = self.sys_ps1 # Changes when debug active
text = self.text text.configure(wrap="char") text.bind("<<newline-and-indent>>", self.enter_callback) text.bind("<<plain-newline-and-indent>>", self.linefeed_callback) text.bind("<<interrupt-execution>>", self.cancel_callback) text.bind("<<end-of-file>>", self.eof_callback) text.bind("<<open-stack-viewer>>", self.open_stack_viewer) text.bind("<<toggle-debugger>>", self.toggle_debugger) text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer) text.bind("<<copy-with-prompts>>", self.copy_with_prompts_callback) if use_subprocess: text.bind("<<view-restart>>", self.view_restart_mark) text.bind("<<restart-shell>>", self.restart_shell) self.squeezer = self.Squeezer(self) text.bind("<<squeeze-current-text>>", self.squeeze_current_text_event)
self.save_stdout = sys.stdout self.save_stderr = sys.stderr self.save_stdin = sys.stdin from idlelib import iomenu self.stdin = StdInputFile(self, "stdin", iomenu.encoding, iomenu.errors) self.stdout = StdOutputFile(self, "stdout", iomenu.encoding, iomenu.errors) self.stderr = StdOutputFile(self, "stderr", iomenu.encoding, "backslashreplace") self.console = StdOutputFile(self, "console", iomenu.encoding, iomenu.errors) if not use_subprocess: sys.stdout = self.stdout sys.stderr = self.stderr sys.stdin = self.stdin try: # page help() text to shell. import pydoc # import must be done here to capture i/o rebinding. # XXX KBK 27Dec07 use text viewer someday, but must work w/o subproc pydoc.pager = pydoc.plainpager except: sys.stderr = sys.__stderr__ raise # self.history = self.History(self.text) # self.pollinterval = 50 # millisec
self.shell_sidebar = self.ShellSidebar(self)
# Insert UserInputTaggingDelegator at the top of the percolator, # but make calls to text.insert() skip it. This causes only insert # events generated in Tcl/Tk to go through this delegator. self.text.insert = self.per.top.insert self.per.insertfilter(UserInputTaggingDelegator())
def ResetFont(self): super().ResetFont()
if self.shell_sidebar is not None: self.shell_sidebar.update_font()
def ResetColorizer(self): super().ResetColorizer()
theme = idleConf.CurrentTheme() tag_colors = { "stdin": {'background': None, 'foreground': None}, "stdout": idleConf.GetHighlight(theme, "stdout"), "stderr": idleConf.GetHighlight(theme, "stderr"), "console": idleConf.GetHighlight(theme, "normal"), } for tag, tag_colors_config in tag_colors.items(): self.text.tag_configure(tag, **tag_colors_config)
if self.shell_sidebar is not None: self.shell_sidebar.update_colors()
def replace_event(self, event): replace.replace(self.text, insert_tags="stdin") return "break"
def get_standard_extension_names(self): return idleConf.GetExtensions(shell_only=True)
def get_prompt_text(self, first, last): """Return text between first and last with prompts added.""" text = self.text.get(first, last) lineno_range = range( int(float(first)), int(float(last)) ) prompts = [ self.shell_sidebar.line_prompts.get(lineno) for lineno in lineno_range ] return "\n".join( line if prompt is None else f"{prompt} {line}" for prompt, line in zip(prompts, text.splitlines()) ) + "\n"
def copy_with_prompts_callback(self, event=None): """Copy selected lines to the clipboard, with prompts.
This makes the copied text useful for doc-tests and interactive shell code examples.
This always copies entire lines, even if only part of the first and/or last lines is selected. """ text = self.text selfirst = text.index('sel.first linestart') if selfirst is None: # Should not be possible. return # No selection, do nothing. sellast = text.index('sel.last') if sellast[-1] != '0': sellast = text.index("sel.last+1line linestart") text.clipboard_clear() prompt_text = self.get_prompt_text(selfirst, sellast) text.clipboard_append(prompt_text)
reading = False executing = False canceled = False endoffile = False closing = False _stop_readline_flag = False
def set_warning_stream(self, stream): global warning_stream warning_stream = stream
def get_warning_stream(self): return warning_stream
def toggle_debugger(self, event=None): if self.executing: messagebox.showerror("Don't debug now", "You can only toggle the debugger when idle", parent=self.text) self.set_debugger_indicator() return "break" else: db = self.interp.getdebugger() if db: self.close_debugger() else: self.open_debugger()
def set_debugger_indicator(self): db = self.interp.getdebugger() self.setvar("<<toggle-debugger>>", not not db)
def toggle_jit_stack_viewer(self, event=None): pass # All we need is the variable
def close_debugger(self): db = self.interp.getdebugger() if db: self.interp.setdebugger(None) db.close() if self.interp.rpcclt: debugger_r.close_remote_debugger(self.interp.rpcclt) self.resetoutput() self.console.write("[DEBUG OFF]\n") self.prompt = self.sys_ps1 self.showprompt() self.set_debugger_indicator()
def open_debugger(self): if self.interp.rpcclt: dbg_gui = debugger_r.start_remote_debugger(self.interp.rpcclt, self) else: dbg_gui = debugger.Debugger(self) self.interp.setdebugger(dbg_gui) dbg_gui.load_breakpoints() self.prompt = "[DEBUG ON]\n" + self.sys_ps1 self.showprompt() self.set_debugger_indicator()
def debug_menu_postcommand(self): state = 'disabled' if self.executing else 'normal' self.update_menu_state('debug', '*tack*iewer', state)
def beginexecuting(self): "Helper for ModifiedInterpreter" self.resetoutput() self.executing = True
def endexecuting(self): "Helper for ModifiedInterpreter" self.executing = False self.canceled = False self.showprompt()
def close(self): "Extend EditorWindow.close()" if self.executing: response = messagebox.askokcancel( "Kill?", "Your program is still running!\n Do you want to kill it?", default="ok", parent=self.text) if response is False: return "cancel" self.stop_readline() self.canceled = True self.closing = True return EditorWindow.close(self)
def _close(self): "Extend EditorWindow._close(), shut down debugger and execution server" self.close_debugger() if use_subprocess: self.interp.kill_subprocess() # Restore std streams sys.stdout = self.save_stdout sys.stderr = self.save_stderr sys.stdin = self.save_stdin # Break cycles self.interp = None self.console = None self.flist.pyshell = None self.history = None EditorWindow._close(self)
def ispythonsource(self, filename): "Override EditorWindow method: never remove the colorizer" return True
def short_title(self): return self.shell_title
COPYRIGHT = \ 'Type "help", "copyright", "credits" or "license()" for more information.'
def begin(self): self.text.mark_set("iomark", "insert") self.resetoutput() if use_subprocess: nosub = '' client = self.interp.start_subprocess() if not client: self.close() return False else: nosub = ("==== No Subprocess ====\n\n" + "WARNING: Running IDLE without a Subprocess is deprecated\n" + "and will be removed in a later version. See Help/IDLE Help\n" + "for details.\n\n") sys.displayhook = rpc.displayhook
self.write("Python %s on %s\n%s\n%s" % (sys.version, sys.platform, self.COPYRIGHT, nosub)) self.text.focus_force() self.showprompt() # User code should use separate default Tk root window import tkinter tkinter._support_default_root = True tkinter._default_root = None return True
def stop_readline(self): if not self.reading: # no nested mainloop to exit. return self._stop_readline_flag = True self.top.quit()
def readline(self): save = self.reading try: self.reading = True self.top.mainloop() # nested mainloop() finally: self.reading = save if self._stop_readline_flag: self._stop_readline_flag = False return "" line = self.text.get("iomark", "end-1c") if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C line = "\n" self.resetoutput() if self.canceled: self.canceled = False if not use_subprocess: raise KeyboardInterrupt if self.endoffile: self.endoffile = False line = "" return line
def isatty(self): return True
def cancel_callback(self, event=None): try: if self.text.compare("sel.first", "!=", "sel.last"): return # Active selection -- always use default binding except: pass if not (self.executing or self.reading): self.resetoutput() self.interp.write("KeyboardInterrupt\n") self.showprompt() return "break" self.endoffile = False self.canceled = True if (self.executing and self.interp.rpcclt): if self.interp.getdebugger(): self.interp.restart_subprocess() else: self.interp.interrupt_subprocess() if self.reading: self.top.quit() # exit the nested mainloop() in readline() return "break"
def eof_callback(self, event): if self.executing and not self.reading: return # Let the default binding (delete next char) take over if not (self.text.compare("iomark", "==", "insert") and self.text.compare("insert", "==", "end-1c")): return # Let the default binding (delete next char) take over if not self.executing: self.resetoutput() self.close() else: self.canceled = False self.endoffile = True self.top.quit() return "break"
def linefeed_callback(self, event): # Insert a linefeed without entering anything (still autoindented) if self.reading: self.text.insert("insert", "\n") self.text.see("insert") else: self.newline_and_indent_event(event) return "break"
def enter_callback(self, event): if self.executing and not self.reading: return # Let the default binding (insert '\n') take over # If some text is selected, recall the selection # (but only if this before the I/O mark) try: sel = self.text.get("sel.first", "sel.last") if sel: if self.text.compare("sel.last", "<=", "iomark"): self.recall(sel, event) return "break" except: pass # If we're strictly before the line containing iomark, recall # the current line, less a leading prompt, less leading or # trailing whitespace if self.text.compare("insert", "<", "iomark linestart"): # Check if there's a relevant stdin range -- if so, use it. # Note: "stdin" blocks may include several successive statements, # so look for "console" tags on the newline before each statement # (and possibly on prompts). prev = self.text.tag_prevrange("stdin", "insert") if ( prev and self.text.compare("insert", "<", prev[1]) and # The following is needed to handle empty statements. "console" not in self.text.tag_names("insert") ): prev_cons = self.text.tag_prevrange("console", "insert") if prev_cons and self.text.compare(prev_cons[1], ">=", prev[0]): prev = (prev_cons[1], prev[1]) next_cons = self.text.tag_nextrange("console", "insert") if next_cons and self.text.compare(next_cons[0], "<", prev[1]): prev = (prev[0], self.text.index(next_cons[0] + "+1c")) self.recall(self.text.get(prev[0], prev[1]), event) return "break" next = self.text.tag_nextrange("stdin", "insert") if next and self.text.compare("insert lineend", ">=", next[0]): next_cons = self.text.tag_nextrange("console", "insert lineend") if next_cons and self.text.compare(next_cons[0], "<", next[1]): next = (next[0], self.text.index(next_cons[0] + "+1c")) self.recall(self.text.get(next[0], next[1]), event) return "break" # No stdin mark -- just get the current line, less any prompt indices = self.text.tag_nextrange("console", "insert linestart") if indices and \ self.text.compare(indices[0], "<=", "insert linestart"): self.recall(self.text.get(indices[1], "insert lineend"), event) else: self.recall(self.text.get("insert linestart", "insert lineend"), event) return "break" # If we're between the beginning of the line and the iomark, i.e. # in the prompt area, move to the end of the prompt if self.text.compare("insert", "<", "iomark"): self.text.mark_set("insert", "iomark") # If we're in the current input and there's only whitespace # beyond the cursor, erase that whitespace first s = self.text.get("insert", "end-1c") if s and not s.strip(): self.text.delete("insert", "end-1c") # If we're in the current input before its last line, # insert a newline right at the insert point if self.text.compare("insert", "<", "end-1c linestart"): self.newline_and_indent_event(event) return "break" # We're in the last line; append a newline and submit it self.text.mark_set("insert", "end-1c") if self.reading: self.text.insert("insert", "\n") self.text.see("insert") else: self.newline_and_indent_event(event) self.text.update_idletasks() if self.reading: self.top.quit() # Break out of recursive mainloop() else: self.runit() return "break"
def recall(self, s, event): # remove leading and trailing empty or whitespace lines s = re.sub(r'^\s*\n', '', s) s = re.sub(r'\n\s*$', '', s) lines = s.split('\n') self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") prefix = self.text.get("insert linestart", "insert") if prefix.rstrip().endswith(':'): self.newline_and_indent_event(event) prefix = self.text.get("insert linestart", "insert") self.text.insert("insert", lines[0].strip(), self.user_input_insert_tags) if len(lines) > 1: orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0) new_base_indent = re.search(r'^([ \t]*)', prefix).group(0) for line in lines[1:]: if line.startswith(orig_base_indent): # replace orig base indentation with new indentation line = new_base_indent + line[len(orig_base_indent):] self.text.insert('insert', '\n' + line.rstrip(), self.user_input_insert_tags) finally: self.text.see("insert") self.text.undo_block_stop()
_last_newline_re = re.compile(r"[ \t]*(\n[ \t]*)?\Z") def runit(self): index_before = self.text.index("end-2c") line = self.text.get("iomark", "end-1c") # Strip off last newline and surrounding whitespace. # (To allow you to hit return twice to end a statement.) line = self._last_newline_re.sub("", line) input_is_complete = self.interp.runsource(line) if not input_is_complete: if self.text.get(index_before) == '\n': self.text.tag_remove(self.user_input_insert_tags, index_before) self.shell_sidebar.update_sidebar()
def open_stack_viewer(self, event=None): if self.interp.rpcclt: return self.interp.remote_stack_viewer() try: sys.last_traceback except: messagebox.showerror("No stack trace", "There is no stack trace yet.\n" "(sys.last_traceback is not defined)", parent=self.text) return from idlelib.stackviewer import StackBrowser StackBrowser(self.root, self.flist)
def view_restart_mark(self, event=None): self.text.see("iomark") self.text.see("restart")
def restart_shell(self, event=None): "Callback for Run/Restart Shell Cntl-F6" self.interp.restart_subprocess(with_cwd=True)
def showprompt(self): self.resetoutput()
prompt = self.prompt if self.sys_ps1 and prompt.endswith(self.sys_ps1): prompt = prompt[:-len(self.sys_ps1)] self.text.tag_add("console", "iomark-1c") self.console.write(prompt)
self.shell_sidebar.update_sidebar() self.text.mark_set("insert", "end-1c") self.set_line_and_column() self.io.reset_undo()
def show_warning(self, msg): width = self.interp.tkconsole.width wrapper = TextWrapper(width=width, tabsize=8, expand_tabs=True) wrapped_msg = '\n'.join(wrapper.wrap(msg)) if not wrapped_msg.endswith('\n'): wrapped_msg += '\n' self.per.bottom.insert("iomark linestart", wrapped_msg, "stderr")
def resetoutput(self): source = self.text.get("iomark", "end-1c") if self.history: self.history.store(source) if self.text.get("end-2c") != "\n": self.text.insert("end-1c", "\n") self.text.mark_set("iomark", "end-1c") self.set_line_and_column() self.ctip.remove_calltip_window()
def write(self, s, tags=()): try: self.text.mark_gravity("iomark", "right") count = OutputWindow.write(self, s, tags, "iomark") self.text.mark_gravity("iomark", "left") except: raise ###pass # ### 11Aug07 KBK if we are expecting exceptions # let's find out what they are and be specific. if self.canceled: self.canceled = False if not use_subprocess: raise KeyboardInterrupt return count
def rmenu_check_cut(self): try: if self.text.compare('sel.first', '<', 'iomark'): return 'disabled' except TclError: # no selection, so the index 'sel.first' doesn't exist return 'disabled' return super().rmenu_check_cut()
def rmenu_check_paste(self): if self.text.compare('insert','<','iomark'): return 'disabled' return super().rmenu_check_paste()
def squeeze_current_text_event(self, event=None): self.squeezer.squeeze_current_text() self.shell_sidebar.update_sidebar()
def on_squeezed_expand(self, index, text, tags): self.shell_sidebar.update_sidebar()
def fix_x11_paste(root): "Make paste replace selection on x11. See issue #5124." if root._windowingsystem == 'x11': for cls in 'Text', 'Entry', 'Spinbox': root.bind_class( cls, '<<Paste>>', 'catch {%W delete sel.first sel.last}\n' + root.bind_class(cls, '<<Paste>>'))
usage_msg = """\
USAGE: idle [-deins] [-t title] [file]* idle [-dns] [-t title] (-c cmd | -r file) [arg]* idle [-dns] [-t title] - [arg]*
-h print this help message and exit -n run IDLE without a subprocess (DEPRECATED, see Help/IDLE Help for details)
The following options will override the IDLE 'settings' configuration:
-e open an edit window -i open a shell window
The following options imply -i and will open a shell:
-c cmd run the command in a shell, or -r file run script from file
-d enable the debugger -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else -t title set title of shell window
A default edit window will be bypassed when -c, -r, or - are used.
[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
Examples:
idle Open an edit window or shell depending on IDLE's configuration.
idle foo.py foobar.py Edit the files, also open a shell if configured to start with shell.
idle -est "Baz" foo.py Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell window with the title "Baz".
idle -c "import sys; print(sys.argv)" "foo" Open a shell window and run the command, passing "-c" in sys.argv[0] and "foo" in sys.argv[1].
idle -d -s -r foo.py "Hello World" Open a shell window, run a startup script, enable the debugger, and run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in sys.argv[1].
echo "import sys; print(sys.argv)" | idle - "foobar" Open a shell window, run the script piped in, passing '' in sys.argv[0] and "foobar" in sys.argv[1]."""
def main(): import getopt from platform import system from idlelib import testing # bool value from idlelib import macosx
global flist, root, use_subprocess
capture_warnings(True) use_subprocess = True enable_shell = False enable_edit = False debug = False cmd = None script = None startup = False try: opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:") except getopt.error as msg: print("Error: %s\n%s" % (msg, usage_msg), file=sys.stderr) sys.exit(2) for o, a in opts: if o == '-c': cmd = a enable_shell = True if o == '-d': debug = True enable_shell = True if o == '-e': enable_edit = True if o == '-h': sys.stdout.write(usage_msg) sys.exit() if o == '-i': enable_shell = True if o == '-n': print(" Warning: running IDLE without a subprocess is deprecated.", file=sys.stderr) use_subprocess = False if o == '-r': script = a if os.path.isfile(script): pass else: print("No script file: ", script) sys.exit() enable_shell = True if o == '-s': startup = True enable_shell = True if o == '-t': PyShell.shell_title = a enable_shell = True if args and args[0] == '-': cmd = sys.stdin.read() enable_shell = True # process sys.argv and sys.path: for i in range(len(sys.path)): sys.path[i] = os.path.abspath(sys.path[i]) if args and args[0] == '-': sys.argv = [''] + args[1:] elif cmd: sys.argv = ['-c'] + args elif script: sys.argv = [script] + args elif args: enable_edit = True pathx = [] for filename in args: pathx.append(os.path.dirname(filename)) for dir in pathx: dir = os.path.abspath(dir) if not dir in sys.path: sys.path.insert(0, dir) else: dir = os.getcwd() if dir not in sys.path: sys.path.insert(0, dir) # check the IDLE settings configuration (but command line overrides) edit_start = idleConf.GetOption('main', 'General', 'editor-on-startup', type='bool') enable_edit = enable_edit or edit_start enable_shell = enable_shell or not enable_edit
# Setup root. Don't break user code run in IDLE process. # Don't change environment when testing. if use_subprocess and not testing: NoDefaultRoot() root = Tk(className="Idle") root.withdraw() from idlelib.run import fix_scaling fix_scaling(root)
# set application icon icondir = os.path.join(os.path.dirname(__file__), 'Icons') if system() == 'Windows': iconfile = os.path.join(icondir, 'idle.ico') root.wm_iconbitmap(default=iconfile) elif not macosx.isAquaTk(): if TkVersion >= 8.6: ext = '.png' sizes = (16, 32, 48, 256) else: ext = '.gif' sizes = (16, 32, 48) iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext)) for size in sizes] icons = [PhotoImage(master=root, file=iconfile) for iconfile in iconfiles] root.wm_iconphoto(True, *icons)
# start editor and/or shell windows: fixwordbreaks(root) fix_x11_paste(root) flist = PyShellFileList(root) macosx.setupApp(root, flist)
if enable_edit: if not (cmd or script): for filename in args[:]: if flist.open(filename) is None: # filename is a directory actually, disconsider it args.remove(filename) if not args: flist.new()
if enable_shell: shell = flist.open_shell() if not shell: return # couldn't open shell if macosx.isAquaTk() and flist.dict: # On OSX: when the user has double-clicked on a file that causes # IDLE to be launched the shell window will open just in front of # the file she wants to see. Lower the interpreter window when # there are open files. shell.top.lower() else: shell = flist.pyshell
# Handle remaining options. If any of these are set, enable_shell # was set also, so shell must be true to reach here. if debug: shell.open_debugger() if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): shell.interp.execfile(filename) if cmd or script: shell.interp.runcommand("""if 1: import sys as _sys _sys.argv = %r del _sys \n""" % (sys.argv,)) if cmd: shell.interp.execsource(cmd) elif script: shell.interp.prepend_syspath(script) shell.interp.execfile(script) elif shell: # If there is a shell window and no cmd or script in progress, # check for problematic issues and print warning message(s) in # the IDLE shell window; this is less intrusive than always # opening a separate window.
# Warn if using a problematic OS X Tk version. tkversionwarning = macosx.tkVersionWarning(root) if tkversionwarning: shell.show_warning(tkversionwarning)
# Warn if the "Prefer tabs when opening documents" system # preference is set to "Always". prefer_tabs_preference_warning = macosx.preferTabsPreferenceWarning() if prefer_tabs_preference_warning: shell.show_warning(prefer_tabs_preference_warning)
while flist.inversedict: # keep IDLE running while files are open. root.mainloop() root.destroy() capture_warnings(False)
if __name__ == "__main__": main()
capture_warnings(False) # Make sure turned off; see issue 18081123456789101112131415161718192021222324===================================== Tests in example form - pure python=====================================
This file contains doctest examples embedded as code blocks, using normalPython prompts. See the accompanying file for similar examples using IPythonprompts (you can't mix both types within one file). The following will be runas a test::
>>> 1+1 2 >>> print ("hello") hello
More than one example works::
>>> s="Hello World"
>>> s.upper() 'HELLO WORLD'
but you should note that the *entire* test file is considered to be a singletest. Individual code blocks that fail are printed separately as ``examplefailures``, but the whole file is still counted and reported as one test.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>
#include <ATen/ops/_sparse_compressed_tensor_unsafe_ops.h>
namespace at {
// aten::_sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensorinline at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options={}) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options={}) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); }}
// aten::_sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensorinline at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, c10::fromIntArrayRefSlow(size), dtype, layout, device, pin_memory); }}
// aten::_sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensorinline at::Tensor _sparse_compressed_tensor_unsafe_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options={}) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, at::TensorOptions options={}) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); }}
// aten::_sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensorinline at::Tensor _sparse_compressed_tensor_unsafe_symint(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> at::Tensor _sparse_compressed_tensor_unsafe(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory) { return at::_ops::_sparse_compressed_tensor_unsafe::call(compressed_indices, plain_indices, values, size, dtype, layout, device, pin_memory); }}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366from sympy.core.function import Functionfrom sympy.core.mul import Mulfrom sympy.core.numbers import (E, I, Rational, oo, pi)from sympy.core.singleton import Sfrom sympy.core.symbol import (Dummy, Symbol, symbols)from sympy.functions.elementary.exponential import (exp, log)from sympy.functions.elementary.miscellaneous import (root, sqrt)from sympy.functions.elementary.trigonometric import sinfrom sympy.functions.special.gamma_functions import gammafrom sympy.functions.special.hyper import hyperfrom sympy.matrices.expressions.matexpr import MatrixSymbolfrom sympy.simplify.powsimp import (powdenest, powsimp)from sympy.simplify.simplify import (signsimp, simplify)from sympy.core.symbol import Str
from sympy.abc import x, y, z, a, b
def test_powsimp(): x, y, z, n = symbols('x,y,z,n') f = Function('f') assert powsimp( 4**x * 2**(-x) * 2**(-x) ) == 1 assert powsimp( (-4)**x * (-2)**(-x) * 2**(-x) ) == 1
assert powsimp( f(4**x * 2**(-x) * 2**(-x)) ) == f(4**x * 2**(-x) * 2**(-x)) assert powsimp( f(4**x * 2**(-x) * 2**(-x)), deep=True ) == f(1) assert exp(x)*exp(y) == exp(x)*exp(y) assert powsimp(exp(x)*exp(y)) == exp(x + y) assert powsimp(exp(x)*exp(y)*2**x*2**y) == (2*E)**(x + y) assert powsimp(exp(x)*exp(y)*2**x*2**y, combine='exp') == \ exp(x + y)*2**(x + y) assert powsimp(exp(x)*exp(y)*exp(2)*sin(x) + sin(y) + 2**x*2**y) == \ exp(2 + x + y)*sin(x) + sin(y) + 2**(x + y) assert powsimp(sin(exp(x)*exp(y))) == sin(exp(x)*exp(y)) assert powsimp(sin(exp(x)*exp(y)), deep=True) == sin(exp(x + y)) assert powsimp(x**2*x**y) == x**(2 + y) # This should remain factored, because 'exp' with deep=True is supposed # to act like old automatic exponent combining. assert powsimp((1 + E*exp(E))*exp(-E), combine='exp', deep=True) == \ (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E), deep=True) == \ (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E)) == (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E), combine='exp') == \ (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E), combine='base') == \ (1 + E*exp(E))*exp(-E) x, y = symbols('x,y', nonnegative=True) n = Symbol('n', real=True) assert powsimp(y**n * (y/x)**(-n)) == x**n assert powsimp(x**(x**(x*y)*y**(x*y))*y**(x**(x*y)*y**(x*y)), deep=True) \ == (x*y)**(x*y)**(x*y) assert powsimp(2**(2**(2*x)*x), deep=False) == 2**(2**(2*x)*x) assert powsimp(2**(2**(2*x)*x), deep=True) == 2**(x*4**x) assert powsimp( exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \ exp(-x + exp(-x)*exp(-x*log(x))) assert powsimp( exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \ exp(-x + exp(-x)*exp(-x*log(x))) assert powsimp((x + y)/(3*z), deep=False, combine='exp') == (x + y)/(3*z) assert powsimp((x/3 + y/3)/z, deep=True, combine='exp') == (x/3 + y/3)/z assert powsimp(exp(x)/(1 + exp(x)*exp(y)), deep=True) == \ exp(x)/(1 + exp(x + y)) assert powsimp(x*y**(z**x*z**y), deep=True) == x*y**(z**(x + y)) assert powsimp((z**x*z**y)**x, deep=True) == (z**(x + y))**x assert powsimp(x*(z**x*z**y)**x, deep=True) == x*(z**(x + y))**x p = symbols('p', positive=True) assert powsimp((1/x)**log(2)/x) == (1/x)**(1 + log(2)) assert powsimp((1/p)**log(2)/p) == p**(-1 - log(2))
# coefficient of exponent can only be simplified for positive bases assert powsimp(2**(2*x)) == 4**x assert powsimp((-1)**(2*x)) == (-1)**(2*x) i = symbols('i', integer=True) assert powsimp((-1)**(2*i)) == 1 assert powsimp((-1)**(-x)) != (-1)**x # could be 1/((-1)**x), but is not # force=True overrides assumptions assert powsimp((-1)**(2*x), force=True) == 1
# rational exponents allow combining of negative terms w, n, m = symbols('w n m', negative=True) e = i/a # not a rational exponent if `a` is unknown ex = w**e*n**e*m**e assert powsimp(ex) == m**(i/a)*n**(i/a)*w**(i/a) e = i/3 ex = w**e*n**e*m**e assert powsimp(ex) == (-1)**i*(-m*n*w)**(i/3) e = (3 + i)/i ex = w**e*n**e*m**e assert powsimp(ex) == (-1)**(3*e)*(-m*n*w)**e
eq = x**(a*Rational(2, 3)) # eq != (x**a)**(2/3) (try x = -1 and a = 3 to see) assert powsimp(eq).exp == eq.exp == a*Rational(2, 3) # powdenest goes the other direction assert powsimp(2**(2*x)) == 4**x
assert powsimp(exp(p/2)) == exp(p/2)
# issue 6368 eq = Mul(*[sqrt(Dummy(imaginary=True)) for i in range(3)]) assert powsimp(eq) == eq and eq.is_Mul
assert all(powsimp(e) == e for e in (sqrt(x**a), sqrt(x**2)))
# issue 8836 assert str( powsimp(exp(I*pi/3)*root(-1,3)) ) == '(-1)**(2/3)'
# issue 9183 assert powsimp(-0.1**x) == -0.1**x
# issue 10095 assert powsimp((1/(2*E))**oo) == (exp(-1)/2)**oo
# PR 13131 eq = sin(2*x)**2*sin(2.0*x)**2 assert powsimp(eq) == eq
# issue 14615 assert powsimp(x**2*y**3*(x*y**2)**Rational(3, 2) ) == x*y*(x*y**2)**Rational(5, 2)
def test_powsimp_negated_base(): assert powsimp((-x + y)/sqrt(x - y)) == -sqrt(x - y) assert powsimp((-x + y)*(-z + y)/sqrt(x - y)/sqrt(z - y)) == sqrt(x - y)*sqrt(z - y) p = symbols('p', positive=True) reps = {p: 2, a: S.Half} assert powsimp((-p)**a/p**a).subs(reps) == ((-1)**a).subs(reps) assert powsimp((-p)**a*p**a).subs(reps) == ((-p**2)**a).subs(reps) n = symbols('n', negative=True) reps = {p: -2, a: S.Half} assert powsimp((-n)**a/n**a).subs(reps) == (-1)**(-a).subs(a, S.Half) assert powsimp((-n)**a*n**a).subs(reps) == ((-n**2)**a).subs(reps) # if x is 0 then the lhs is 0**a*oo**a which is not (-1)**a eq = (-x)**a/x**a assert powsimp(eq) == eq
def test_powsimp_nc(): x, y, z = symbols('x,y,z') A, B, C = symbols('A B C', commutative=False)
assert powsimp(A**x*A**y, combine='all') == A**(x + y) assert powsimp(A**x*A**y, combine='base') == A**x*A**y assert powsimp(A**x*A**y, combine='exp') == A**(x + y)
assert powsimp(A**x*B**x, combine='all') == A**x*B**x assert powsimp(A**x*B**x, combine='base') == A**x*B**x assert powsimp(A**x*B**x, combine='exp') == A**x*B**x
assert powsimp(B**x*A**x, combine='all') == B**x*A**x assert powsimp(B**x*A**x, combine='base') == B**x*A**x assert powsimp(B**x*A**x, combine='exp') == B**x*A**x
assert powsimp(A**x*A**y*A**z, combine='all') == A**(x + y + z) assert powsimp(A**x*A**y*A**z, combine='base') == A**x*A**y*A**z assert powsimp(A**x*A**y*A**z, combine='exp') == A**(x + y + z)
assert powsimp(A**x*B**x*C**x, combine='all') == A**x*B**x*C**x assert powsimp(A**x*B**x*C**x, combine='base') == A**x*B**x*C**x assert powsimp(A**x*B**x*C**x, combine='exp') == A**x*B**x*C**x
assert powsimp(B**x*A**x*C**x, combine='all') == B**x*A**x*C**x assert powsimp(B**x*A**x*C**x, combine='base') == B**x*A**x*C**x assert powsimp(B**x*A**x*C**x, combine='exp') == B**x*A**x*C**x
def test_issue_6440(): assert powsimp(16*2**a*8**b) == 2**(a + 3*b + 4)
def test_powdenest(): x, y = symbols('x,y') p, q = symbols('p q', positive=True) i, j = symbols('i,j', integer=True)
assert powdenest(x) == x assert powdenest(x + 2*(x**(a*Rational(2, 3)))**(3*x)) == (x + 2*(x**(a*Rational(2, 3)))**(3*x)) assert powdenest((exp(a*Rational(2, 3)))**(3*x)) # -X-> (exp(a/3))**(6*x) assert powdenest((x**(a*Rational(2, 3)))**(3*x)) == ((x**(a*Rational(2, 3)))**(3*x)) assert powdenest(exp(3*x*log(2))) == 2**(3*x) assert powdenest(sqrt(p**2)) == p eq = p**(2*i)*q**(4*i) assert powdenest(eq) == (p*q**2)**(2*i) # -X-> (x**x)**i*(x**x)**j == x**(x*(i + j)) assert powdenest((x**x)**(i + j)) assert powdenest(exp(3*y*log(x))) == x**(3*y) assert powdenest(exp(y*(log(a) + log(b)))) == (a*b)**y assert powdenest(exp(3*(log(a) + log(b)))) == a**3*b**3 assert powdenest(((x**(2*i))**(3*y))**x) == ((x**(2*i))**(3*y))**x assert powdenest(((x**(2*i))**(3*y))**x, force=True) == x**(6*i*x*y) assert powdenest(((x**(a*Rational(2, 3)))**(3*y/i))**x) == \ (((x**(a*Rational(2, 3)))**(3*y/i))**x) assert powdenest((x**(2*i)*y**(4*i))**z, force=True) == (x*y**2)**(2*i*z) assert powdenest((p**(2*i)*q**(4*i))**j) == (p*q**2)**(2*i*j) e = ((p**(2*a))**(3*y))**x assert powdenest(e) == e e = ((x**2*y**4)**a)**(x*y) assert powdenest(e) == e e = (((x**2*y**4)**a)**(x*y))**3 assert powdenest(e) == ((x**2*y**4)**a)**(3*x*y) assert powdenest((((x**2*y**4)**a)**(x*y)), force=True) == \ (x*y**2)**(2*a*x*y) assert powdenest((((x**2*y**4)**a)**(x*y))**3, force=True) == \ (x*y**2)**(6*a*x*y) assert powdenest((x**2*y**6)**i) != (x*y**3)**(2*i) x, y = symbols('x,y', positive=True) assert powdenest((x**2*y**6)**i) == (x*y**3)**(2*i)
assert powdenest((x**(i*Rational(2, 3))*y**(i/2))**(2*i)) == (x**Rational(4, 3)*y)**(i**2) assert powdenest(sqrt(x**(2*i)*y**(6*i))) == (x*y**3)**i
assert powdenest(4**x) == 2**(2*x) assert powdenest((4**x)**y) == 2**(2*x*y) assert powdenest(4**x*y) == 2**(2*x)*y
def test_powdenest_polar(): x, y, z = symbols('x y z', polar=True) a, b, c = symbols('a b c') assert powdenest((x*y*z)**a) == x**a*y**a*z**a assert powdenest((x**a*y**b)**c) == x**(a*c)*y**(b*c) assert powdenest(((x**a)**b*y**c)**c) == x**(a*b*c)*y**(c**2)
def test_issue_5805(): arg = ((gamma(x)*hyper((), (), x))*pi)**2 assert powdenest(arg) == (pi*gamma(x)*hyper((), (), x))**2 assert arg.is_positive is None
def test_issue_9324_powsimp_on_matrix_symbol(): M = MatrixSymbol('M', 10, 10) expr = powsimp(M, deep=True) assert expr == M assert expr.args[0] == Str('M')
def test_issue_6367(): z = -5*sqrt(2)/(2*sqrt(2*sqrt(29) + 29)) + sqrt(-sqrt(29)/29 + S.Half) assert Mul(*[powsimp(a) for a in Mul.make_args(z.normal())]) == 0 assert powsimp(z.normal()) == 0 assert simplify(z) == 0 assert powsimp(sqrt(2 + sqrt(3))*sqrt(2 - sqrt(3)) + 1) == 2 assert powsimp(z) != 0
def test_powsimp_polar(): from sympy.functions.elementary.complexes import polar_lift from sympy.functions.elementary.exponential import exp_polar x, y, z = symbols('x y z') p, q, r = symbols('p q r', polar=True)
assert (polar_lift(-1))**(2*x) == exp_polar(2*pi*I*x) assert powsimp(p**x * q**x) == (p*q)**x assert p**x * (1/p)**x == 1 assert (1/p)**x == p**(-x)
assert exp_polar(x)*exp_polar(y) == exp_polar(x)*exp_polar(y) assert powsimp(exp_polar(x)*exp_polar(y)) == exp_polar(x + y) assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y) == \ (p*exp_polar(1))**(x + y) assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y, combine='exp') == \ exp_polar(x + y)*p**(x + y) assert powsimp( exp_polar(x)*exp_polar(y)*exp_polar(2)*sin(x) + sin(y) + p**x*p**y) \ == p**(x + y) + sin(x)*exp_polar(2 + x + y) + sin(y) assert powsimp(sin(exp_polar(x)*exp_polar(y))) == \ sin(exp_polar(x)*exp_polar(y)) assert powsimp(sin(exp_polar(x)*exp_polar(y)), deep=True) == \ sin(exp_polar(x + y))
def test_issue_5728(): b = x*sqrt(y) a = sqrt(b) c = sqrt(sqrt(x)*y) assert powsimp(a*b) == sqrt(b)**3 assert powsimp(a*b**2*sqrt(y)) == sqrt(y)*a**5 assert powsimp(a*x**2*c**3*y) == c**3*a**5 assert powsimp(a*x*c**3*y**2) == c**7*a assert powsimp(x*c**3*y**2) == c**7 assert powsimp(x*c**3*y) == x*y*c**3 assert powsimp(sqrt(x)*c**3*y) == c**5 assert powsimp(sqrt(x)*a**3*sqrt(y)) == sqrt(x)*sqrt(y)*a**3 assert powsimp(Mul(sqrt(x)*c**3*sqrt(y), y, evaluate=False)) == \ sqrt(x)*sqrt(y)**3*c**3 assert powsimp(a**2*a*x**2*y) == a**7
# symbolic powers work, too b = x**y*y a = b*sqrt(b) assert a.is_Mul is True assert powsimp(a) == sqrt(b)**3
# as does exp a = x*exp(y*Rational(2, 3)) assert powsimp(a*sqrt(a)) == sqrt(a)**3 assert powsimp(a**2*sqrt(a)) == sqrt(a)**5 assert powsimp(a**2*sqrt(sqrt(a))) == sqrt(sqrt(a))**9
def test_issue_from_PR1599(): n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) assert (powsimp(sqrt(n1)*sqrt(n2)*sqrt(n3)) == -I*sqrt(-n1)*sqrt(-n2)*sqrt(-n3)) assert (powsimp(root(n1, 3)*root(n2, 3)*root(n3, 3)*root(n4, 3)) == -(-1)**Rational(1, 3)* (-n1)**Rational(1, 3)*(-n2)**Rational(1, 3)*(-n3)**Rational(1, 3)*(-n4)**Rational(1, 3))
def test_issue_10195(): a = Symbol('a', integer=True) l = Symbol('l', even=True, nonzero=True) n = Symbol('n', odd=True) e_x = (-1)**(n/2 - S.Half) - (-1)**(n*Rational(3, 2) - S.Half) assert powsimp((-1)**(l/2)) == I**l assert powsimp((-1)**(n/2)) == I**n assert powsimp((-1)**(n*Rational(3, 2))) == -I**n assert powsimp(e_x) == (-1)**(n/2 - S.Half) + (-1)**(n*Rational(3, 2) + S.Half) assert powsimp((-1)**(a*Rational(3, 2))) == (-I)**a
def test_issue_15709(): assert powsimp(3**x*Rational(2, 3)) == 2*3**(x-1) assert powsimp(2*3**x/3) == 2*3**(x-1)
def test_issue_11981(): x, y = symbols('x y', commutative=False) assert powsimp((x*y)**2 * (y*x)**2) == (x*y)**2 * (y*x)**2
def test_issue_17524(): a = symbols("a", real=True) e = (-1 - a**2)*sqrt(1 + a**2) assert signsimp(powsimp(e)) == signsimp(e) == -(a**2 + 1)**(S(3)/2)
def test_issue_19627(): # if you use force the user must verify assert powdenest(sqrt(sin(x)**2), force=True) == sin(x) assert powdenest((x**(S.Half/y))**(2*y), force=True) == x from sympy.core.function import expand_power_base e = 1 - a expr = (exp(z/e)*x**(b/e)*y**((1 - b)/e))**e assert powdenest(expand_power_base(expr, force=True), force=True ) == x**b*y**(1 - b)*exp(z)
def test_issue_22546(): p1, p2 = symbols('p1, p2', positive=True) ref = powsimp(p1**z/p2**z) e = z + 1 ans = ref.subs(z, e) assert ans.is_Pow assert powsimp(p1**e/p2**e) == ans i = symbols('i', integer=True) ref = powsimp(x**i/y**i) e = i + 1 ans = ref.subs(i, e) assert ans.is_Pow assert powsimp(x**e/y**e) == ans123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218# mypy: ignore-errors
# noqa: F401, E501# This is an auto-generated file. Please do not modify it by hand.# To re-generate, run:# cd ~/pytorch && python# torchgen/fuse_attention_patterns/gen_attention_patterns.py
import torchimport torch._inductor
aten = torch.ops.atenprims = torch.ops.prims
from torch._inductor.pattern_matcher import ( Arg, CallFunction, CallFunctionVarArgs, CallMethod, CallMethodVarArgs, CallModule, CallModuleVarArgs, ExclusiveKeywordArg, Ignored, KeywordArg, ListOf, MultiOutputPattern, PatternExpr, RepeatedExpr, _TargetArgsExpr, _TargetExpr, _TargetExprVarArgs,)permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())expand_default = CallFunction(aten.expand.default, permute_default, Ignored())clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=2)expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())alias_default = CallFunction(aten.alias.default, div_Tensor_1)alias_default_1 = CallFunction(aten.alias.default, alias_default)alias_default_2 = CallFunction(aten.alias.default, alias_default_1)alias_default_3 = CallFunction(aten.alias.default, alias_default_2, _users=2)mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, alias_default_3, _users=2)sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)mul_Tensor_1 = CallFunction(aten.mul.Tensor, alias_default_3, sum_dim_IntList_1)sub_Tensor_1 = CallFunction(aten.sub.Tensor, mul_Tensor, mul_Tensor_1)div_Tensor_2 = CallFunction(aten.div.Tensor, sub_Tensor_1, KeywordArg('inv_scale'))view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())_sfdp_pattern_14_training = MultiOutputPattern([view_default_5, permute_default_6, permute_default_9, permute_default_11, None, None])
permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())expand_default = CallFunction(aten.expand.default, permute_default, Ignored())clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)view_default = CallFunction(aten.view.default, clone_default, Ignored())permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)_sfdp_pattern_14_inference = CallFunction(aten.view.default, bmm_default_1, Ignored())
permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())expand_default = CallFunction(aten.expand.default, permute_default, Ignored())clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())alias_default = CallFunction(aten.alias.default, convert_element_type_default_1)alias_default_1 = CallFunction(aten.alias.default, alias_default)alias_default_2 = CallFunction(aten.alias.default, alias_default_1)alias_default_3 = CallFunction(aten.alias.default, alias_default_2)convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, alias_default_3, Ignored(), _users=2)mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, convert_element_type_default_3, _users=2)sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)mul_Tensor_1 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, sum_dim_IntList_1)sub_Tensor_1 = CallFunction(aten.sub.Tensor, mul_Tensor, mul_Tensor_1)convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, sub_Tensor_1, Ignored())div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale'))view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())_sfdp_pattern_14_half_training = MultiOutputPattern([view_default_5, permute_default_6, permute_default_9, permute_default_11, None, None])
permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())expand_default = CallFunction(aten.expand.default, permute_default, Ignored())clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)view_default = CallFunction(aten.view.default, clone_default, Ignored())permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)_sfdp_pattern_14_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored())12345678910111213141516171819202122#pragma once
// @generated by torchgen/gen.py from NativeFunction.h
#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>#include <c10/core/QScheme.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <tuple>#include <vector>
namespace at {namespace native {TORCH_API at::Tensor linalg_eigvalsh(const at::Tensor & self, c10::string_view UPLO="L");TORCH_API at::Tensor & linalg_eigvalsh_out(const at::Tensor & self, c10::string_view UPLO, at::Tensor & out);} // namespace native} // namespace at1234567891011121314151617181920212223#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cuda {
TORCH_API at::Tensor _to_sparse_csc(const at::Tensor & self, c10::optional<int64_t> dense_dim=c10::nullopt);
} // namespace cuda} // namespace at1234567891011121314151617181920212223242526#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace meta {
TORCH_API at::Tensor erfc(const at::Tensor & self);TORCH_API at::Tensor & erfc_out(at::Tensor & out, const at::Tensor & self);TORCH_API at::Tensor & erfc_outf(const at::Tensor & self, at::Tensor & out);TORCH_API at::Tensor & erfc_(at::Tensor & self);
} // namespace meta} // namespace at12345678910111213141516171819202122232425262728#pragma once
// @generated by torchgen/gen.py from Operator.h
#include <tuple>#include <vector>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {namespace _ops {
struct TORCH_API _cufft_get_plan_cache_size { using schema = int64_t (at::DeviceIndex); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cufft_get_plan_cache_size") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cufft_get_plan_cache_size(DeviceIndex device_index) -> int") static int64_t call(at::DeviceIndex device_index); static int64_t redispatch(c10::DispatchKeySet dispatchKeySet, at::DeviceIndex device_index);};
}} // namespace at::_ops123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import mathfrom numbers import Number
import torchfrom torch import inf, nanfrom torch.distributions import constraintsfrom torch.distributions.distribution import Distributionfrom torch.distributions.utils import broadcast_all
__all__ = ["Cauchy"]
class Cauchy(Distribution): r""" Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of independent normally distributed random variables with means `0` follows a Cauchy distribution.
Example::
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Cauchy distribution with loc=0 and scale=1 tensor([ 2.3214])
Args: loc (float or Tensor): mode or median of the distribution. scale (float or Tensor): half width at half maximum. """ arg_constraints = {"loc": constraints.real, "scale": constraints.positive} support = constraints.real has_rsample = True
def __init__(self, loc, scale, validate_args=None): self.loc, self.scale = broadcast_all(loc, scale) if isinstance(loc, Number) and isinstance(scale, Number): batch_shape = torch.Size() else: batch_shape = self.loc.size() super().__init__(batch_shape, validate_args=validate_args)
def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(Cauchy, _instance) batch_shape = torch.Size(batch_shape) new.loc = self.loc.expand(batch_shape) new.scale = self.scale.expand(batch_shape) super(Cauchy, new).__init__(batch_shape, validate_args=False) new._validate_args = self._validate_args return new
@property def mean(self): return torch.full( self._extended_shape(), nan, dtype=self.loc.dtype, device=self.loc.device )
@property def mode(self): return self.loc
@property def variance(self): return torch.full( self._extended_shape(), inf, dtype=self.loc.dtype, device=self.loc.device )
def rsample(self, sample_shape=torch.Size()): shape = self._extended_shape(sample_shape) eps = self.loc.new(shape).cauchy_() return self.loc + eps * self.scale
def log_prob(self, value): if self._validate_args: self._validate_sample(value) return ( -math.log(math.pi) - self.scale.log() - (((value - self.loc) / self.scale) ** 2).log1p() )
def cdf(self, value): if self._validate_args: self._validate_sample(value) return torch.atan((value - self.loc) / self.scale) / math.pi + 0.5
def icdf(self, value): return torch.tan(math.pi * (value - 0.5)) * self.scale + self.loc
def entropy(self): return math.log(4 * math.pi) + self.scale.log()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169from abc import ABC, abstractmethodfrom numba.core.registry import DelayedRegistry, CPUDispatcherfrom numba.core.decorators import jitfrom numba.core.errors import (InternalTargetMismatchError, NonexistentTargetError)from threading import local as tls
_active_context = tls()_active_context_default = 'cpu'
class _TargetRegistry(DelayedRegistry):
def __getitem__(self, item): try: return super().__getitem__(item) except KeyError: msg = "No target is registered against '{}', known targets:\n{}" known = '\n'.join([f"{k: <{10}} -> {v}" for k, v in target_registry.items()]) raise NonexistentTargetError(msg.format(item, known)) from None
# Registry mapping target name strings to Target classestarget_registry = _TargetRegistry()
# Registry mapping Target classes the @jit decorator for that targetjit_registry = DelayedRegistry()
class target_override(object): """Context manager to temporarily override the current target with that prescribed.""" def __init__(self, name): self._orig_target = getattr(_active_context, 'target', _active_context_default) self.target = name
def __enter__(self): _active_context.target = self.target
def __exit__(self, ty, val, tb): _active_context.target = self._orig_target
def current_target(): """Returns the current target """ return getattr(_active_context, 'target', _active_context_default)
def get_local_target(context): """ Gets the local target from the call stack if available and the TLS override if not. """ # TODO: Should this logic be reversed to prefer TLS override? if len(context.callstack._stack) > 0: target = context.callstack[0].target else: target = target_registry.get(current_target(), None) if target is None: msg = ("The target found is not registered." "Given target was {}.") raise ValueError(msg.format(target)) else: return target
def resolve_target_str(target_str): """Resolves a target specified as a string to its Target class.""" return target_registry[target_str]
def resolve_dispatcher_from_str(target_str): """Returns the dispatcher associated with a target string""" target_hw = resolve_target_str(target_str) return dispatcher_registry[target_hw]
def _get_local_target_checked(tyctx, hwstr, reason): """Returns the local target if it is compatible with the given target name during a type resolution; otherwise, raises an exception.
Parameters ---------- tyctx: typing context hwstr: str target name to check against reason: str Reason for the resolution. Expects a noun. Returns ------- target_hw : Target
Raises ------ InternalTargetMismatchError """ # Get the class for the target declared by the function hw_clazz = resolve_target_str(hwstr) # get the local target target_hw = get_local_target(tyctx) # make sure the target_hw is in the MRO for hw_clazz else bail if not target_hw.inherits_from(hw_clazz): raise InternalTargetMismatchError(reason, target_hw, hw_clazz) return target_hw
class JitDecorator(ABC):
@abstractmethod def __call__(self): return NotImplemented
class Target(ABC): """ Implements a target """
@classmethod def inherits_from(cls, other): """Returns True if this target inherits from 'other' False otherwise""" return issubclass(cls, other)
class Generic(Target): """Mark the target as generic, i.e. suitable for compilation on any target. All must inherit from this. """
class CPU(Generic): """Mark the target as CPU. """
class GPU(Generic): """Mark the target as GPU, i.e. suitable for compilation on a GPU target. """
class CUDA(GPU): """Mark the target as CUDA. """
class NPyUfunc(Target): """Mark the target as a ufunc """
target_registry['generic'] = Generictarget_registry['CPU'] = CPUtarget_registry['cpu'] = CPUtarget_registry['GPU'] = GPUtarget_registry['gpu'] = GPUtarget_registry['CUDA'] = CUDAtarget_registry['cuda'] = CUDAtarget_registry['npyufunc'] = NPyUfunc
dispatcher_registry = DelayedRegistry(key_type=Target)
# Register the cpu target token with its dispatcher and jitcpu_target = target_registry['cpu']dispatcher_registry[cpu_target] = CPUDispatcherjit_registry[cpu_target] = jit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334# mypy: ignore-errors
from __future__ import annotations
from typing import Optional
import torch
from . import _binary_ufuncs_impl, _dtypes_impl, _unary_ufuncs_impl, _utilfrom ._normalizations import ( ArrayLike, ArrayLikeOrScalar, CastingModes, DTypeLike, normalizer, NotImplementedType, OutArray,)
def _ufunc_postprocess(result, out, casting): if out is not None: result = _util.typecast_tensor(result, out.dtype.torch_dtype, casting) result = torch.broadcast_to(result, out.shape) return result
# ############# Binary ufuncs ######################
_binary = [ name for name in dir(_binary_ufuncs_impl) if not name.startswith("_") and name not in ["torch", "matmul", "divmod", "ldexp"]]
NEP50_FUNCS = ( "add", "subtract", "multiply", "floor_divide", "true_divide", "divide", "remainder", "bitwise_and", "bitwise_or", "bitwise_xor", "bitwise_left_shift", "bitwise_right_shift", "hypot", "arctan2", "logaddexp", "logaddexp2", "heaviside", "copysign", "fmax", "minimum", "fmin", "maximum", "fmod", "gcd", "lcm", "pow",)
def deco_binary_ufunc(torch_func): """Common infra for binary ufuncs.
Normalize arguments, sort out type casting, broadcasting and delegate to the pytorch functions for the actual work. """
@normalizer def wrapped( x1: ArrayLikeOrScalar, x2: ArrayLikeOrScalar, /, out: Optional[OutArray] = None, *, where: NotImplementedType = True, casting: Optional[CastingModes] = "same_kind", order: NotImplementedType = "K", dtype: Optional[DTypeLike] = None, subok: NotImplementedType = False, signature: NotImplementedType = None, extobj: NotImplementedType = None, ): if dtype is not None:
def cast(x, dtype): if isinstance(x, torch.Tensor): return _util.typecast_tensor(x, dtype, casting) else: return torch.as_tensor(x, dtype=dtype)
x1 = cast(x1, dtype) x2 = cast(x2, dtype) elif isinstance(x1, torch.Tensor) and isinstance(x2, torch.Tensor): dtype = _dtypes_impl.result_type_impl(x1, x2) x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting) else: x1, x2 = _dtypes_impl.nep50_to_tensors( x1, x2, torch_func.__name__ in NEP50_FUNCS, torch_func.__name__ )
result = torch_func(x1, x2)
return _ufunc_postprocess(result, out, casting)
wrapped.__qualname__ = torch_func.__name__ wrapped.__name__ = torch_func.__name__
return wrapped
# matmul's signature is _slightly_ different from other ufuncs:# - no where=...# - additional axis=..., axes=...# - no NEP50 scalars in or out@normalizerdef matmul( x1: ArrayLike, x2: ArrayLike, /, out: Optional[OutArray] = None, *, casting: Optional[CastingModes] = "same_kind", order: NotImplementedType = "K", dtype: Optional[DTypeLike] = None, subok: NotImplementedType = False, signature: NotImplementedType = None, extobj: NotImplementedType = None, axes: NotImplementedType = None, axis: NotImplementedType = None,): if dtype is None: dtype = _dtypes_impl.result_type_impl(x1, x2) x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting)
result = _binary_ufuncs_impl.matmul(x1, x2)
result = _ufunc_postprocess(result, out, casting) return result
# ldexp casting is special : the dtype of the result == dtype of the 1st arg@normalizerdef ldexp( x1: ArrayLikeOrScalar, x2: ArrayLikeOrScalar, /, out: Optional[OutArray] = None, *, where: NotImplementedType = True, casting: Optional[CastingModes] = "same_kind", order: NotImplementedType = "K", dtype: Optional[DTypeLike] = None, subok: NotImplementedType = False, signature: NotImplementedType = None, extobj: NotImplementedType = None,): if dtype is not None: if isinstance(x1, torch.Tensor): x1 = _util.typecast_tensor(x1, dtype, casting) else: x1 = torch.as_tensor(x1, dtype=dtype) else: if not isinstance(x1, torch.Tensor): x1 = torch.as_tensor(x1) x1 = _util.cast_int_to_float(x1)
x2 = torch.as_tensor(x2) # the second arg must be integer if _dtypes_impl._category(x2.dtype) != 1: raise ValueError("ldexp 2nd arg must be integer")
result = _binary_ufuncs_impl.ldexp(x1, x2)
if x1.dtype == torch.float16: # torch.ldexp(f16, int) -> f32, undo it result = result.to(torch.float16)
return _ufunc_postprocess(result, out, casting)
# nin=2, nout=2@normalizerdef divmod( x1: ArrayLike, x2: ArrayLike, out1: Optional[OutArray] = None, out2: Optional[OutArray] = None, /, out: tuple[Optional[OutArray], Optional[OutArray]] = (None, None), *, where: NotImplementedType = True, casting: Optional[CastingModes] = "same_kind", order: NotImplementedType = "K", dtype: Optional[DTypeLike] = None, subok: NotImplementedType = False, signature: NotImplementedType = None, extobj: NotImplementedType = None,): # make sure we either have no out arrays at all, or there is either # out1, out2, or out=tuple, but not both num_outs = sum(x is not None for x in [out1, out2]) if num_outs == 1: raise ValueError("both out1 and out2 need to be provided") elif num_outs == 2: o1, o2 = out if o1 is not None or o2 is not None: raise TypeError( "cannot specify 'out' as both a positional and keyword argument" ) else: out1, out2 = out
if dtype is None: dtype = _dtypes_impl.result_type_impl(x1, x2) x1, x2 = _util.typecast_tensors((x1, x2), dtype, casting)
quot, rem = _binary_ufuncs_impl.divmod(x1, x2)
quot = _ufunc_postprocess(quot, out1, casting) rem = _ufunc_postprocess(rem, out2, casting) return quot, rem
## Attach ufuncs to this module, for a further export to the public namespace in __init__.py#for name in _binary: ufunc = getattr(_binary_ufuncs_impl, name) vars()[name] = deco_binary_ufunc(ufunc)
def modf(x, /, *args, **kwds): quot, rem = divmod(x, 1, *args, **kwds) return rem, quot
_binary = _binary + ["divmod", "modf", "matmul", "ldexp"]
# ############# Unary ufuncs ######################
_unary = [ name for name in dir(_unary_ufuncs_impl) if not name.startswith("_") and name != "torch"]
# these are ufunc(int) -> float_fp_unary = [ "arccos", "arccosh", "arcsin", "arcsinh", "arctan", "arctanh", "cbrt", "cos", "cosh", "deg2rad", "degrees", "exp", "exp2", "expm1", "log", "log10", "log1p", "log2", "rad2deg", "radians", "reciprocal", "sin", "sinh", "sqrt", "square", "tan", "tanh", "trunc",]
def deco_unary_ufunc(torch_func): """Common infra for unary ufuncs.
Normalize arguments, sort out type casting, broadcasting and delegate to the pytorch functions for the actual work. """
@normalizer def wrapped( x: ArrayLike, /, out: Optional[OutArray] = None, *, where=True, casting: Optional[CastingModes] = "same_kind", order="K", dtype: Optional[DTypeLike] = None, subok: NotImplementedType = False, signature=None, extobj=None, ): if dtype is not None: x = _util.typecast_tensor(x, dtype, casting)
if torch_func.__name__ in _fp_unary: x = _util.cast_int_to_float(x)
result = torch_func(x) result = _ufunc_postprocess(result, out, casting) return result
wrapped.__qualname__ = torch_func.__name__ wrapped.__name__ = torch_func.__name__
return wrapped
## Attach ufuncs to this module, for a further export to the public namespace in __init__.py#for name in _unary: ufunc = getattr(_unary_ufuncs_impl, name) vars()[name] = deco_unary_ufunc(ufunc)
__all__ = _binary + _unary # noqa: PLE060512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>
#include <ATen/ops/split_with_sizes_copy_ops.h>
namespace at {
// aten::split_with_sizes_copy(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]inline ::std::vector<at::Tensor> split_with_sizes_copy(const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy::call(self, c10::fromIntArrayRefSlow(split_sizes), dim);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> ::std::vector<at::Tensor> split_with_sizes_copy(const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy::call(self, c10::fromIntArrayRefSlow(split_sizes), dim); }}
// aten::split_with_sizes_copy(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]inline ::std::vector<at::Tensor> split_with_sizes_copy_symint(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy::call(self, split_sizes, dim);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> ::std::vector<at::Tensor> split_with_sizes_copy(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy::call(self, split_sizes, dim); }}
// aten::split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()inline void split_with_sizes_copy_out(at::TensorList out, const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy_out::call(self, c10::fromIntArrayRefSlow(split_sizes), dim, out);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> void split_with_sizes_copy_out(at::TensorList out, const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy_out::call(self, c10::fromIntArrayRefSlow(split_sizes), dim, out); }}
// aten::split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()inline void split_with_sizes_copy_outf(const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim, at::TensorList out) { return at::_ops::split_with_sizes_copy_out::call(self, c10::fromIntArrayRefSlow(split_sizes), dim, out);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> void split_with_sizes_copy_outf(const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim, at::TensorList out) { return at::_ops::split_with_sizes_copy_out::call(self, c10::fromIntArrayRefSlow(split_sizes), dim, out); }}
// aten::split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()inline void split_with_sizes_copy_symint_out(at::TensorList out, const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy_out::call(self, split_sizes, dim, out);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> void split_with_sizes_copy_out(at::TensorList out, const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim=0) { return at::_ops::split_with_sizes_copy_out::call(self, split_sizes, dim, out); }}
// aten::split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()inline void split_with_sizes_copy_symint_outf(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim, at::TensorList out) { return at::_ops::split_with_sizes_copy_out::call(self, split_sizes, dim, out);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> void split_with_sizes_copy_outf(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim, at::TensorList out) { return at::_ops::split_with_sizes_copy_out::call(self, split_sizes, dim, out); }}
}1234567891011121314151617181920212223242526272829303132333435363738"""Tests for PeriodIndex behaving like a vectorized Period scalar"""
import pytest
from pandas import ( Timedelta, date_range, period_range,)import pandas._testing as tm
class TestPeriodIndexOps: def test_start_time(self): # GH#17157 index = period_range(freq="M", start="2016-01-01", end="2016-05-31") expected_index = date_range("2016-01-01", end="2016-05-31", freq="MS") tm.assert_index_equal(index.start_time, expected_index)
def test_end_time(self): # GH#17157 index = period_range(freq="M", start="2016-01-01", end="2016-05-31") expected_index = date_range("2016-01-01", end="2016-05-31", freq="ME") expected_index += Timedelta(1, "D") - Timedelta(1, "ns") tm.assert_index_equal(index.end_time, expected_index)
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") @pytest.mark.filterwarnings( "ignore:Period with BDay freq is deprecated:FutureWarning" ) def test_end_time_business_friday(self): # GH#34449 pi = period_range("1990-01-05", freq="B", periods=1) result = pi.end_time
dti = date_range("1990-01-05", freq="D", periods=1)._with_freq(None) expected = dti + Timedelta(days=1, nanoseconds=-1) tm.assert_index_equal(result, expected)123456789101112131415161718192021222324252627282930import collections
# from jaraco.collections 3.3class FreezableDefaultDict(collections.defaultdict): """ Often it is desirable to prevent the mutation of a default dict after its initial construction, such as to prevent mutation during iteration.
>>> dd = FreezableDefaultDict(list) >>> dd[0].append('1') >>> dd.freeze() >>> dd[1] [] >>> len(dd) 1 """
def __missing__(self, key): return getattr(self, '_frozen', super().__missing__)(key)
def freeze(self): self._frozen = lambda key: self.default_factory()
class Pair(collections.namedtuple('Pair', 'name value')): @classmethod def parse(cls, text): return cls(*map(str.strip, text.split("=", 1)))1234567from typing import Any, List, Optional, Type, TypeVar
_T = TypeVar("_T")
def none_throws(optional: Optional[_T], message: str = ...) -> _T: ...def safe_cast(new_type: Type[_T], value: Any) -> _T: ...def ParameterSpecification(__name: str) -> List[Type[Any]]: ...123456789101112131415161718192021222324#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace compositeexplicitautograd {
TORCH_API at::Tensor & _dirichlet_grad_out(at::Tensor & out, const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total);TORCH_API at::Tensor & _dirichlet_grad_outf(const at::Tensor & x, const at::Tensor & alpha, const at::Tensor & total, at::Tensor & out);
} // namespace compositeexplicitautograd} // namespace at12345678910111213141516171819202122from numpy.testing import assert_import numpy.distutils.fcompiler
nag_version_strings = [('nagfor', 'NAG Fortran Compiler Release ' '6.2(Chiyoda) Build 6200', '6.2'), ('nagfor', 'NAG Fortran Compiler Release ' '6.1(Tozai) Build 6136', '6.1'), ('nagfor', 'NAG Fortran Compiler Release ' '6.0(Hibiya) Build 1021', '6.0'), ('nagfor', 'NAG Fortran Compiler Release ' '5.3.2(971)', '5.3.2'), ('nag', 'NAGWare Fortran 95 compiler Release 5.1' '(347,355-367,375,380-383,389,394,399,401-402,407,' '431,435,437,446,459-460,463,472,494,496,503,508,' '511,517,529,555,557,565)', '5.1')]
class TestNagFCompilerVersions: def test_version_match(self): for comp, vs, version in nag_version_strings: fc = numpy.distutils.fcompiler.new_fcompiler(compiler=comp) v = fc.version_match(vs) assert_(v == version)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960class State: ''' A representation of a state managed by a ``StateMachine``.
Attributes: name (instance of FreeGroupElement or string) -- State name which is also assigned to the Machine. transisitons (OrderedDict) -- Represents all the transitions of the state object. state_type (string) -- Denotes the type (accept/start/dead) of the state. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state. state_machine (instance of StateMachine object) -- The finite state machine that the state belongs to. '''
def __init__(self, name, state_machine, state_type=None, rh_rule=None): self.name = name self.transitions = {} self.state_machine = state_machine self.state_type = state_type[0] self.rh_rule = rh_rule
def add_transition(self, letter, state): ''' Add a transition from the current state to a new state.
Keyword Arguments: letter -- The alphabet element the current state reads to make the state transition. state -- This will be an instance of the State object which represents a new state after in the transition after the alphabet is read.
''' self.transitions[letter] = state
class StateMachine: ''' Representation of a finite state machine the manages the states and the transitions of the automaton.
Attributes: states (dictionary) -- Collection of all registered `State` objects. name (str) -- Name of the state machine. '''
def __init__(self, name, automaton_alphabet): self.name = name self.automaton_alphabet = automaton_alphabet self.states = {} # Contains all the states in the machine. self.add_state('start', state_type='s')
def add_state(self, state_name, state_type=None, rh_rule=None): ''' Instantiate a state object and stores it in the 'states' dictionary.
Arguments: state_name (instance of FreeGroupElement or string) -- name of the new states. state_type (string) -- Denotes the type (accept/start/dead) of the state added. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
''' new_state = State(state_name, self, state_type, rh_rule) self.states[state_name] = new_state
def __repr__(self): return "%s" % (self.name)123456789101112131415161718192021222324252627282930#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <c10/util/Optional.h>
#include <ATen/ops/_use_cudnn_rnn_flatten_weight_ops.h>
namespace at {
// aten::_use_cudnn_rnn_flatten_weight() -> boolinline bool _use_cudnn_rnn_flatten_weight() { return at::_ops::_use_cudnn_rnn_flatten_weight::call();}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# - Config file for the Caffe2 package# It defines the following variable(s)# CAFFE2_INCLUDE_DIRS - include directories for FooBar# as well as Caffe2 targets for other cmake libraries to use.
# library version information
# Utils functions.include("${CMAKE_CURRENT_LIST_DIR}/public/utils.cmake")
# Depending on whether Caffe2 uses gflags during compile time or# not, invoke gflags.if(OFF) include("${CMAKE_CURRENT_LIST_DIR}/public/gflags.cmake") if(NOT TARGET gflags) message(FATAL_ERROR "Your installed Caffe2 version uses gflags but the gflags library " "cannot be found. Did you accidentally remove it, or have you set " "the right CMAKE_PREFIX_PATH and/or GFLAGS_ROOT_DIR? If you do not " "have gflags, you will need to install gflags and set the library " "path accordingly.") endif()endif()
# Depending on whether Caffe2 uses glog during compile time or# not, invoke glog.if(OFF) include("${CMAKE_CURRENT_LIST_DIR}/public/glog.cmake") if(NOT TARGET glog::glog) message(FATAL_ERROR "Your installed Caffe2 version uses glog but the glog library " "cannot be found. Did you accidentally remove it, or have you set " "the right CMAKE_PREFIX_PATH and/or GFLAGS_ROOT_DIR? If you do not " "have glog, you will need to install glog and set the library " "path accordingly.") endif()endif()
# Protobufif(ON) if(NOT TARGET protobuf::libprotobuf) # Define protobuf::libprotobuf as a dummy target to resolve references to # protobuf::libprotobuf in Caffe2Targets.cmake. add_library(dummy INTERFACE) add_library(protobuf::libprotobuf ALIAS dummy) endif()else() include("${CMAKE_CURRENT_LIST_DIR}/public/protobuf.cmake") if(NOT TARGET protobuf::libprotobuf) message(FATAL_ERROR "Your installed Caffe2 version uses protobuf but the protobuf library " "cannot be found. Did you accidentally remove it, or have you set " "the right CMAKE_PREFIX_PATH? If you do not have protobuf, you will " "need to install protobuf and set the library path accordingly.") endif() message(STATUS "Caffe2: Protobuf version " ${Protobuf_VERSION}) # If during build time we know the protobuf version, we will also do a sanity # check to ensure that the protobuf library that Caffe2 found is consistent # with the compiled version. if(FALSE) if(NOT (${Protobuf_VERSION} VERSION_EQUAL Protobuf_VERSION_NOTFOUND)) message(FATAL_ERROR "Your installed Caffe2 is built with protobuf " "Protobuf_VERSION_NOTFOUND" ", while your current cmake setting discovers protobuf version " ${Protobuf_VERSION} ". Please specify a protobuf version that is the same as the built " "version.") endif() endif()endif()
if (OFF) include("${CMAKE_CURRENT_LIST_DIR}/public/LoadHIP.cmake")endif()
if(ON) # The file public/cuda.cmake exclusively uses CAFFE2_USE_*. # If Caffe2 was compiled with the libraries below, they must # be found again when including the Caffe2 target. set(CAFFE2_USE_CUDA ON) set(CAFFE2_USE_TENSORRT OFF)
# Add current directory to module path so we pick up FindCUDAToolkit.cmake set(old_CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}") include("${CMAKE_CURRENT_LIST_DIR}/public/cuda.cmake") set(CMAKE_MODULE_PATH "${old_CMAKE_MODULE_PATH}")
if(ON AND NOT CAFFE2_USE_CUDA) message(FATAL_ERROR "Your installed Caffe2 version uses CUDA but I cannot find the CUDA " "libraries. Please set the proper CUDA prefixes and / or install " "CUDA.") endif() if(OFF AND NOT CAFFE2_USE_TENSORRT) message(FATAL_ERROR "Your installed Caffe2 version uses TensorRT but I cannot find the TensorRT " "libraries. Please set the proper TensorRT prefixes and / or install " "TensorRT.") endif()endif()
if(OFF) # Add current directory to module path so we pick up FindSYCLToolkit.cmake set(old_CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}") include("${CMAKE_CURRENT_LIST_DIR}/public/xpu.cmake") set(CMAKE_MODULE_PATH "${old_CMAKE_MODULE_PATH}")endif()
if(ON) include("${CMAKE_CURRENT_LIST_DIR}/public/mkl.cmake")endif()
if(ON) include("${CMAKE_CURRENT_LIST_DIR}/public/mkldnn.cmake")endif()
# import targetsinclude ("${CMAKE_CURRENT_LIST_DIR}/Caffe2Targets.cmake")
# Interface libraries, that allows one to build proper link flags.# We will also define a helper variable, Caffe2_MAIN_LIBS, that resolves to# the main caffe2 libraries in cases of cuda presence / absence.set(Caffe2_MAIN_LIBS torch_library)
# include directory.## Newer versions of CMake set the INTERFACE_INCLUDE_DIRECTORIES property# of the imported targets. It is hence not necessary to add this path# manually to the include search path for targets which link to gflags.# The following lines are here for backward compatibility, in case one# would like to use the old-style include path.get_filename_component( CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)# Note: the current list dir is _INSTALL_PREFIX/share/cmake/Gloo.get_filename_component( _INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)set(CAFFE2_INCLUDE_DIRS "${_INSTALL_PREFIX}/include")shared/package-files/08/0802392a2a1c49abdd877f290daf0f0f7ed8670051c793672ff8e3dd167c860d/_sparse_softmax_compositeexplicitautograd_dispatch.hAdded+24
shared/package-files/08/080568ed7a3da54d12410ffe081a28a8b6cc6948e0aae82daaf4145c07262eb3/models.pyiAdded+21
shared/package-files/08/0806ef3662b840225106c5f6e7fca2d887bd241dfbc600ec6219a67b2dfe11ff/quantize_per_tensor_native.hAdded+26
shared/package-files/08/08199dfe00ed822a87d9276841094e05bb4e11ea6b5ad33af18ddfd6c4aa3df2/fontchooser.tclAdded+456
shared/package-files/08/081ee3b785d24720ac3ab9bbaf7ef597fcb7c9af7e00ddb017b048b575d06825/code.pyAdded+755
shared/package-files/08/081ef817a8a64aebd16fb7dfceda03dd5a0884c67a72e8add1416bf9da318a69/grammar_analysis.pyAdded+203
shared/package-files/08/0824daa4f11e187f7b88ab15b0f4855f441195175d4e353f4b9f31ac72f5f5b4/executionengine.pyAdded+330
shared/package-files/08/0824e40a2e60f1757e0c94f1f125c26a2111d250d97d98e672afac7da09a27ec/add_cuda_dispatch.hAdded+26
shared/package-files/08/0827b1cd3d6592c4c6fd6bc6bc79faf82b9677f657a05be23469c165dfe113b6/test_mstats_extras.pyAdded+172
shared/package-files/08/08291913035c258ae6872b8156bf782b03058c7b1b2fa98e259d9fe5a19c0115/diffgeom.pyAdded+2273
shared/package-files/08/0831778a6e88c5d63732ee9fc114269121019974b79105489d0e29957b285fd7/_datasource.pyAdded+704
shared/package-files/08/08343747764e4a5814262793cf4d652057a7913863c5950d43297e8e1fdac5b6/contentAdded+17
shared/package-files/08/08356ef929f04501b2ccaa77effb8f1f36c200703c6a68952f2b86813558c723/__init__.pyAdded+4
shared/package-files/08/08358a652ec2a49cb967f8a7aaee8b2cf0d5a67856a2e216864ef0e3e335c0c3/test_numpy_generators.pyAdded+38
shared/package-files/08/083853b6609e1e609b4a6ed178271ec92f73d841a2bdf6ecfe905b34be04ebb2/istft.hAdded+30
shared/package-files/08/083afd847ede83d6e66eb74533613f08ea57e1e3fc22418ea5a41e38d025c9bb/__init__.pyAdded+7
shared/package-files/08/083e8c7f3213c8279ab0b5010c25f3265c911ca7489c234cd04ed01a6017fc56/topk_cuda_dispatch.hAdded+28
shared/package-files/08/0841783816f8f9bc8425953ff5e25b67b58d59231b24eedda06037c95c0d0eee/torchbind.pyAdded+94
shared/package-files/08/0847db444a04894a6cb0c849c235498b49c8eb1ec6647e28c51abc1ff26e42bd/_kalman_smoother.pxdAdded+491
shared/package-files/08/084a5c8a445afd8f9267fa05b12695aef9c74b5cfdf58482fed17b56e8ac2d59/registry.pyAdded+141
shared/package-files/08/084af1309d3205fbbf72f0a828932ef568ea51aa212c8aaa7f6dbc1a6f575892/__init__.pyAdded+131
shared/package-files/08/084bc0c7c2c9f3dd30b251dddfcccdd19971b76cbe369689f4245ecadb510eaf/RECORDAdded+42
shared/package-files/08/0852d8ea2cf5f5d00d3e56060c05a8c5ca0d03060290e1a0e4c83b02d7a93615/nord.pyAdded+150
shared/package-files/08/0855dea48aac25c054c60c36c9f871d630aee355cf8269f977ffba3ade02e35e/minitel12-80Added
shared/package-files/08/085adcca077cb9d7b9c7a384b5f33f0f0d0a607a31a4f3f3ab8e8aa075718e37/FamagustaAdded
shared/package-files/08/085b2fe38a29f41c6927adb16d3be8763153f9822fe5980b0fe8db83c1b20a1c/jit_exception.hAdded+38
shared/package-files/08/085bbee935f102d83dec053bfb5ebc6b6982e5d5fbe91e8fd8605124d1c71e39/empty_like.hAdded+43
shared/package-files/08/085de63724bef7a53ede2061593f9693dd992eb92f5b1b51bcb6d7cd77f8b613/mach-gnu-colorAdded
shared/package-files/08/08630ec45901fcdf4d9a6e97dacf70c57a4c4be5c6e81c738d226588b7c71fdf/pyshell.pyAdded+1713
shared/package-files/08/08633c6992181e578f0dd027475c97dcc7c31aed0e71e66952223f638b5919a5/test_example.txtAdded+24
shared/package-files/08/086bf2e7d296995f7cc7b486a62ae430fc9949314867e01d65ccf960e0056a4c/_sparse_compressed_tensor_unsafe.hAdded+69
shared/package-files/08/086e47ff149bb7065a9232f32fe10483e4fd8f618e5329425396202ec6c79b60/test_powsimp.pyAdded+366
shared/package-files/08/08811d886039522efb63296f01f62f90614d6a0a92a8060e8a5747724f16a3cd/_sfdp_pattern_14.pyAdded+218
shared/package-files/08/088221112d40daa0dc7aefcd59b4379d2a45816d1f91c1a7c930265b219b1f18/linalg_eigvalsh_native.hAdded+22
shared/package-files/08/08879f4a4a4dd1d76913bbea6e59db37e743f9236c94f665b851b4030e42620c/_to_sparse_csc_cuda_dispatch.hAdded+23
shared/package-files/08/0896100ee277cb6b6f25c5ed03b32246387133fdd354f9a756e030738b30bad5/erfc_meta_dispatch.hAdded+26
shared/package-files/08/0896c48a43618468c73effc245d088849cd6651819167bd75a89f6ad237337f3/guru+rvAdded
shared/package-files/08/0897b0a6c7147a1b7aa79ed5cc0cdfe026c9623cfa00dafac0f86386b19c3ed8/_cufft_get_plan_cache_size_ops.hAdded+28
shared/package-files/08/0899037850bf916ff6a2d07c638822698d6140674e8f73f8c4643d6999deb041/cauchy.pyAdded+90
shared/package-files/08/089949de76f7625218c9bba31312d31054f670ee6422da886b2e5081ce929b7b/target_extension.pyAdded+169
shared/package-files/08/089a161bb4d6291676b4cec9577aac657a40625076891cdfa20b3bef6d711a5d/_ufuncs.pyAdded+334
shared/package-files/08/089a4fea064faa4a714c1353f230cf17d7dc49fa1c4ba20023ae61989661efdc/split_with_sizes_copy.hAdded+91
shared/package-files/08/089b96d30e927700cfb659360e5d788347b0b8272c20a3f0b6798830149812e7/test_scalar_compat.pyAdded+38
shared/package-files/08/089d0e4c21c88d6034648552e2fa0e440b27d91e11d9c40112d3ec6442690126/_collections.pyAdded+30
shared/package-files/08/089d2351ad72aee4786bf715a9c151a4e441a5819e6bd0b9bd0e65c067d65192/pyre_extensions.pyiAdded+7
shared/package-files/08/089dabe5ceebc1d17ea056c605db3f6e4a63e9c91a3d37b1a7eabd8897147aa8/_dirichlet_grad_compositeexplicitautograd_dispatch.hAdded+24
shared/package-files/08/08a1238a4ed855f48918be1a6ee72d92696421484086ffb1d9a51c5e24d1f5bd/test_fcompiler_nagfor.pyAdded+22
shared/package-files/08/08a1a12eacafc58d26966cbcfc76f85b391275660f51a536c99621cfed22679c/rewritingsystem_fsm.pyAdded+60
shared/package-files/08/08a22cd6886ea1ae62ab72dbd00f8510cc2a92eb8e122c3a4c8a04c0cffafc10/_use_cudnn_rnn_flatten_weight.hAdded+30
shared/package-files/08/08b8092063fe3c24ed22c342ce4a83171d76028507d2b36a2619f6fe90b076fd/Caffe2Config.cmakeAdded+140