idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
62,800
def terms ( self ) : from qnet . algebra . core . scalar_algebra import ScalarValue for mapping in yield_from_ranges ( self . ranges ) : term = self . term . substitute ( mapping ) if isinstance ( term , ScalarValue . _val_types ) : term = ScalarValue . create ( term ) assert isinstance ( term , Expression ) yield term
Iterator over the terms of the sum
62,801
def doit ( self , classes = None , recursive = True , indices = None , max_terms = None , ** kwargs ) : return super ( ) . doit ( classes , recursive , indices = indices , max_terms = max_terms , ** kwargs )
Write out the indexed sum explicitly
62,802
def make_disjunct_indices ( self , * others ) : new = self other_index_symbols = set ( ) for other in others : try : if isinstance ( other , IdxSym ) : other_index_symbols . add ( other ) elif isinstance ( other , IndexRangeBase ) : other_index_symbols . add ( other . index_symbol ) elif hasattr ( other , 'ranges' ) : ...
Return a copy with modified indices to ensure disjunct indices with others .
62,803
def codemirror_field_js_assets ( * args ) : manifesto = CodemirrorAssetTagRender ( ) manifesto . register_from_fields ( * args ) return mark_safe ( manifesto . js_html ( ) )
Tag to render CodeMirror Javascript assets needed for all given fields .
62,804
def codemirror_field_css_assets ( * args ) : manifesto = CodemirrorAssetTagRender ( ) manifesto . register_from_fields ( * args ) return mark_safe ( manifesto . css_html ( ) )
Tag to render CodeMirror CSS assets needed for all given fields .
62,805
def codemirror_field_js_bundle ( field ) : manifesto = CodemirrorAssetTagRender ( ) manifesto . register_from_fields ( field ) try : bundle_name = manifesto . js_bundle_names ( ) [ 0 ] except IndexError : msg = ( "Given field with configuration name '{}' does not have a " "Javascript bundle name" ) raise CodeMirrorFiel...
Filter to get CodeMirror Javascript bundle name needed for a single field .
62,806
def codemirror_field_css_bundle ( field ) : manifesto = CodemirrorAssetTagRender ( ) manifesto . register_from_fields ( field ) try : bundle_name = manifesto . css_bundle_names ( ) [ 0 ] except IndexError : msg = ( "Given field with configuration name '{}' does not have a " "Javascript bundle name" ) raise CodeMirrorFi...
Filter to get CodeMirror CSS bundle name needed for a single field .
62,807
def codemirror_parameters ( field ) : manifesto = CodemirrorAssetTagRender ( ) names = manifesto . register_from_fields ( field ) config = manifesto . get_codemirror_parameters ( names [ 0 ] ) return mark_safe ( json . dumps ( config ) )
Filter to include CodeMirror parameters as a JSON string for a single field .
62,808
def codemirror_instance ( config_name , varname , element_id , assets = True ) : output = io . StringIO ( ) manifesto = CodemirrorAssetTagRender ( ) manifesto . register ( config_name ) if assets : output . write ( manifesto . css_html ( ) ) output . write ( manifesto . js_html ( ) ) html = manifesto . codemirror_html ...
Return HTML to init a CodeMirror instance for an element .
62,809
def resolve_widget ( self , field ) : if hasattr ( field , 'field' ) : widget = field . field . widget else : widget = field . widget return widget
Given a Field or BoundField return widget instance .
62,810
def register_from_fields ( self , * args ) : names = [ ] for field in args : widget = self . resolve_widget ( field ) self . register ( widget . config_name ) if widget . config_name not in names : names . append ( widget . config_name ) return names
Register config name from field widgets
62,811
def render_asset_html ( self , path , tag_template ) : url = os . path . join ( settings . STATIC_URL , path ) return tag_template . format ( url = url )
Render HTML tag for a given path .
62,812
def codemirror_html ( self , config_name , varname , element_id ) : parameters = json . dumps ( self . get_codemirror_parameters ( config_name ) , sort_keys = True ) return settings . CODEMIRROR_FIELD_INIT_JS . format ( varname = varname , inputid = element_id , settings = parameters , )
Render HTML for a CodeMirror instance .
62,813
def run_apidoc ( _ ) : import better_apidoc better_apidoc . main ( [ 'better-apidoc' , '-t' , os . path . join ( '.' , '_templates' ) , '--force' , '--no-toc' , '--separate' , '-o' , os . path . join ( '.' , 'API' ) , os . path . join ( '..' , 'src' , 'qnet' ) , ] )
Generage API documentation
62,814
def _shorten_render ( renderer , max_len ) : def short_renderer ( expr ) : res = renderer ( expr ) if len ( res ) > max_len : return '...' else : return res return short_renderer
Return a modified that returns the representation of expr or ... if that representation is longer than max_len
62,815
def init_algebra ( * , default_hs_cls = 'LocalSpace' ) : from qnet . algebra . core . hilbert_space_algebra import LocalSpace from qnet . algebra . core . abstract_quantum_algebra import QuantumExpression default_hs_cls = getattr ( importlib . import_module ( 'qnet' ) , default_hs_cls ) if issubclass ( default_hs_cls ,...
Initialize the algebra system
62,816
def register ( self , name ) : if name not in settings . CODEMIRROR_SETTINGS : msg = ( "Given config name '{}' does not exists in " "'settings.CODEMIRROR_SETTINGS'." ) raise UnknowConfigError ( msg . format ( name ) ) parameters = copy . deepcopy ( self . default_internal_config ) parameters . update ( copy . deepcopy ...
Register configuration for an editor instance .
62,817
def register_many ( self , * args ) : params = [ ] for name in args : params . append ( self . register ( name ) ) return params
Register many configuration names .
62,818
def resolve_mode ( self , name ) : if name not in settings . CODEMIRROR_MODES : msg = ( "Given config name '{}' does not exists in " "'settings.CODEMIRROR_MODES'." ) raise UnknowModeError ( msg . format ( name ) ) return settings . CODEMIRROR_MODES . get ( name )
From given mode name return mode file path from settings . CODEMIRROR_MODES map .
62,819
def resolve_theme ( self , name ) : if name not in settings . CODEMIRROR_THEMES : msg = ( "Given theme name '{}' does not exists in " "'settings.CODEMIRROR_THEMES'." ) raise UnknowThemeError ( msg . format ( name ) ) return settings . CODEMIRROR_THEMES . get ( name )
From given theme name return theme file path from settings . CODEMIRROR_THEMES map .
62,820
def get_configs ( self , name = None ) : if name : if name not in self . registry : msg = "Given config name '{}' is not registered." raise NotRegisteredError ( msg . format ( name ) ) return { name : self . registry [ name ] } return self . registry
Returns registred configurations .
62,821
def get_config ( self , name ) : if name not in self . registry : msg = "Given config name '{}' is not registered." raise NotRegisteredError ( msg . format ( name ) ) return copy . deepcopy ( self . registry [ name ] )
Return a registred configuration for given config name .
62,822
def get_codemirror_parameters ( self , name ) : config = self . get_config ( name ) return { k : config [ k ] for k in config if k not in self . _internal_only }
Return CodeMirror parameters for given configuration name .
62,823
def commutator ( A , B = None ) : if B : return A * B - B * A return SPre ( A ) - SPost ( A )
Commutator of A and B
62,824
def liouvillian ( H , Ls = None ) : r if Ls is None : Ls = [ ] elif isinstance ( Ls , Matrix ) : Ls = Ls . matrix . ravel ( ) . tolist ( ) summands = [ - I * commutator ( H ) , ] summands . extend ( [ lindblad ( L ) for L in Ls ] ) return SuperOperatorPlus . create ( * summands )
r Return the Liouvillian super - operator associated with H and Ls
62,825
def block_matrix ( A , B , C , D ) : r return vstackm ( ( hstackm ( ( A , B ) ) , hstackm ( ( C , D ) ) ) )
r Generate the operator matrix with quadrants
62,826
def permutation_matrix ( permutation ) : r assert check_permutation ( permutation ) n = len ( permutation ) op_matrix = np_zeros ( ( n , n ) , dtype = int ) for i , j in enumerate ( permutation ) : op_matrix [ j , i ] = 1 return Matrix ( op_matrix )
r Return orthogonal permutation matrix for permutation tuple
62,827
def is_zero ( self ) : for o in self . matrix . ravel ( ) : try : if not o . is_zero : return False except AttributeError : if not o == 0 : return False return True
Are all elements of the matrix zero?
62,828
def conjugate ( self ) : try : return Matrix ( np_conjugate ( self . matrix ) ) except AttributeError : raise NoConjugateMatrix ( "Matrix %s contains entries that have no defined " "conjugate" % str ( self ) )
The element - wise conjugate matrix
62,829
def real ( self ) : def re ( val ) : if hasattr ( val , 'real' ) : return val . real elif hasattr ( val , 'as_real_imag' ) : return val . as_real_imag ( ) [ 0 ] elif hasattr ( val , 'conjugate' ) : return ( val . conjugate ( ) + val ) / 2 else : raise NoConjugateMatrix ( "Matrix entry %s contains has no defined " "conj...
Element - wise real part
62,830
def imag ( self ) : def im ( val ) : if hasattr ( val , 'imag' ) : return val . imag elif hasattr ( val , 'as_real_imag' ) : return val . as_real_imag ( ) [ 1 ] elif hasattr ( val , 'conjugate' ) : return ( val . conjugate ( ) - val ) / ( 2 * I ) else : raise NoConjugateMatrix ( "Matrix entry %s contains has no defined...
Element - wise imaginary part
62,831
def element_wise ( self , func , * args , ** kwargs ) : s = self . shape emat = [ func ( o , * args , ** kwargs ) for o in self . matrix . ravel ( ) ] return Matrix ( np_array ( emat ) . reshape ( s ) )
Apply a function to each matrix element and return the result in a new operator matrix of the same shape .
62,832
def series_expand ( self , param : Symbol , about , order : int ) : s = self . shape emats = zip ( * [ o . series_expand ( param , about , order ) for o in self . matrix . ravel ( ) ] ) return tuple ( ( Matrix ( np_array ( em ) . reshape ( s ) ) for em in emats ) )
Expand the matrix expression as a truncated power series in a scalar parameter .
62,833
def expand ( self ) : return self . element_wise ( lambda o : o . expand ( ) if isinstance ( o , QuantumExpression ) else o )
Expand each matrix element distributively .
62,834
def space ( self ) : arg_spaces = [ o . space for o in self . matrix . ravel ( ) if hasattr ( o , 'space' ) ] if len ( arg_spaces ) == 0 : return TrivialSpace else : return ProductSpace . create ( * arg_spaces )
Combined Hilbert space of all matrix elements .
62,835
def simplify_scalar ( self , func = sympy . simplify ) : def element_simplify ( v ) : if isinstance ( v , sympy . Basic ) : return func ( v ) elif isinstance ( v , QuantumExpression ) : return v . simplify_scalar ( func = func ) else : return v return self . element_wise ( element_simplify )
Simplify all scalar expressions appearing in the Matrix .
62,836
def get_initial ( self ) : initial = { } if self . kwargs . get ( 'mode' , None ) : filename = "{}.txt" . format ( self . kwargs [ 'mode' ] ) filepath = os . path . join ( settings . BASE_DIR , 'demo_datas' , filename ) if os . path . exists ( filepath ) : with io . open ( filepath , 'r' , encoding = 'utf-8' ) as fp : ...
Try to find a demo source for given mode if any if finded use it to fill the demo textarea .
62,837
def _get_order_by ( order , orderby , order_by_fields ) : try : db_fieldnames = order_by_fields [ orderby ] except KeyError : raise ValueError ( "Invalid value for 'orderby': '{0}', supported values are: {1}" . format ( orderby , ', ' . join ( sorted ( order_by_fields . keys ( ) ) ) ) ) is_desc = ( not order and orderb...
Return the order by syntax for a model . Checks whether use ascending or descending order and maps the fieldnames .
62,838
def query_entries ( queryset = None , year = None , month = None , day = None , category = None , category_slug = None , tag = None , tag_slug = None , author = None , author_slug = None , future = False , order = None , orderby = None , limit = None , ) : if queryset is None : queryset = get_entry_model ( ) . objects ...
Query the entries using a set of predefined filters . This interface is mainly used by the get_entries template tag .
62,839
def query_tags ( order = None , orderby = None , limit = None ) : from taggit . models import Tag , TaggedItem EntryModel = get_entry_model ( ) ct = ContentType . objects . get_for_model ( EntryModel ) entry_filter = { 'status' : EntryModel . PUBLISHED } if appsettings . FLUENT_BLOGS_FILTER_SITE_ID : entry_filter [ 'pa...
Query the tags with usage count included . This interface is mainly used by the get_tags template tag .
62,840
def get_category_for_slug ( slug , language_code = None ) : Category = get_category_model ( ) if issubclass ( Category , TranslatableModel ) : return Category . objects . active_translations ( language_code , slug = slug ) . get ( ) else : return Category . objects . get ( slug = slug )
Find the category for a given slug
62,841
def get_date_range ( year = None , month = None , day = None ) : if year is None : return None if month is None : start = datetime ( year , 1 , 1 , 0 , 0 , 0 , tzinfo = utc ) end = datetime ( year , 12 , 31 , 23 , 59 , 59 , 999 , tzinfo = utc ) return ( start , end ) if day is None : start = datetime ( year , month , 1...
Return a start .. end range to query for a specific month day or year .
62,842
def pattern ( head , * args , mode = 1 , wc_name = None , conditions = None , ** kwargs ) -> Pattern : if len ( args ) == 0 : args = None if len ( kwargs ) == 0 : kwargs = None return Pattern ( head , args , kwargs , mode = mode , wc_name = wc_name , conditions = conditions )
Flat constructor for the Pattern class
62,843
def match_pattern ( expr_or_pattern : object , expr : object ) -> MatchDict : try : return expr_or_pattern . match ( expr ) except AttributeError : if expr_or_pattern == expr : return MatchDict ( ) else : res = MatchDict ( ) res . success = False res . reason = "Expressions '%s' and '%s' are not the same" % ( repr ( ex...
Recursively match expr with the given expr_or_pattern
62,844
def update ( self , * others ) : for other in others : for key , val in other . items ( ) : self [ key ] = val try : if not other . success : self . success = False self . reason = other . reason except AttributeError : pass
Update dict with entries from other
62,845
def extended_arg_patterns ( self ) : for arg in self . _arg_iterator ( self . args ) : if isinstance ( arg , Pattern ) : if arg . mode > self . single : while True : yield arg else : yield arg else : yield arg
Iterator over patterns for positional arguments to be matched
62,846
def finditer ( self , expr ) : try : for arg in expr . args : for m in self . finditer ( arg ) : yield m for arg in expr . kwargs . values ( ) : for m in self . finditer ( arg ) : yield m except AttributeError : pass m = self . match ( expr ) if m : yield m
Return an iterator over all matches in expr
62,847
def wc_names ( self ) : if self . wc_name is None : res = set ( ) else : res = set ( [ self . wc_name ] ) if self . args is not None : for arg in self . args : if isinstance ( arg , Pattern ) : res . update ( arg . wc_names ) if self . kwargs is not None : for val in self . kwargs . values ( ) : if isinstance ( val , P...
Set of all wildcard names occurring in the pattern
62,848
def from_expr ( cls , expr ) : return cls ( expr . args , expr . kwargs , cls = expr . __class__ )
Instantiate proto - expression from the given Expression
62,849
def get_entry_model ( ) : global _EntryModel if _EntryModel is None : if not appsettings . FLUENT_BLOGS_ENTRY_MODEL : _EntryModel = Entry else : app_label , model_name = appsettings . FLUENT_BLOGS_ENTRY_MODEL . rsplit ( '.' , 1 ) _EntryModel = apps . get_model ( app_label , model_name ) if _EntryModel is None : raise I...
Return the actual entry model that is in use .
62,850
def get_category_model ( ) : app_label , model_name = appsettings . FLUENT_BLOGS_CATEGORY_MODEL . rsplit ( '.' , 1 ) try : return apps . get_model ( app_label , model_name ) except Exception as e : raise ImproperlyConfigured ( "Failed to import FLUENT_BLOGS_CATEGORY_MODEL '{0}': {1}" . format ( appsettings . FLUENT_BLO...
Return the category model to use .
62,851
def blog_reverse ( viewname , args = None , kwargs = None , current_app = 'fluent_blogs' , ** page_kwargs ) : return mixed_reverse ( viewname , args = args , kwargs = kwargs , current_app = current_app , ** page_kwargs )
Reverse a URL to the blog taking various configuration options into account .
62,852
def expand_commutators_leibniz ( expr , expand_expr = True ) : recurse = partial ( expand_commutators_leibniz , expand_expr = expand_expr ) A = wc ( 'A' , head = Operator ) C = wc ( 'C' , head = Operator ) AB = wc ( 'AB' , head = OperatorTimes ) BC = wc ( 'BC' , head = OperatorTimes ) def leibniz_right ( A , BC ) : B =...
Recursively expand commutators in expr according to the Leibniz rule .
62,853
def init_printing ( * , reset = False , init_sympy = True , ** kwargs ) : logger = logging . getLogger ( __name__ ) if reset : SympyPrinter . _global_settings = { } if init_sympy : if kwargs . get ( 'repr_format' , '' ) == 'unicode' : sympy_init_printing ( use_unicode = True ) if kwargs . get ( 'repr_format' , '' ) == ...
Initialize the printing system .
62,854
def configure_printing ( ** kwargs ) : freeze = init_printing ( _freeze = True , ** kwargs ) try : yield finally : for obj , attr_map in freeze . items ( ) : for attr , val in attr_map . items ( ) : setattr ( obj , attr , val )
Context manager for temporarily changing the printing system .
62,855
def convert_to_qutip ( expr , full_space = None , mapping = None ) : if full_space is None : full_space = expr . space if not expr . space . is_tensor_factor_of ( full_space ) : raise ValueError ( "expr '%s' must be in full_space %s" % ( expr , full_space ) ) if full_space == TrivialSpace : raise AlgebraError ( "Cannot...
Convert a QNET expression to a qutip object
62,856
def _convert_local_operator_to_qutip ( expr , full_space , mapping ) : n = full_space . dimension if full_space != expr . space : all_spaces = full_space . local_factors own_space_index = all_spaces . index ( expr . space ) return qutip . tensor ( * ( [ qutip . qeye ( s . dimension ) for s in all_spaces [ : own_space_i...
Convert a LocalOperator instance to qutip
62,857
def _time_dependent_to_qutip ( op , full_space = None , time_symbol = symbols ( "t" , real = True ) , convert_as = 'pyfunc' ) : if full_space is None : full_space = op . space if time_symbol in op . free_symbols : op = op . expand ( ) if isinstance ( op , OperatorPlus ) : result = [ ] for o in op . operands : if time_s...
Convert a possiblty time - dependent operator into the nested - list structure required by QuTiP
62,858
def ljust ( text , width , fillchar = ' ' ) : len_text = grapheme_len ( text ) return text + fillchar * ( width - len_text )
Left - justify text to a total of width
62,859
def rjust ( text , width , fillchar = ' ' ) : len_text = grapheme_len ( text ) return fillchar * ( width - len_text ) + text
Right - justify text for a total of width graphemes
62,860
def KroneckerDelta ( i , j , simplify = True ) : from qnet . algebra . core . scalar_algebra import ScalarValue , One if not isinstance ( i , ( int , sympy . Basic ) ) : raise TypeError ( "i is not an integer or sympy expression: %s" % type ( i ) ) if not isinstance ( j , ( int , sympy . Basic ) ) : raise TypeError ( "...
Kronecker delta symbol
62,861
def create ( cls , * operands , ** kwargs ) : converted_operands = [ ] for op in operands : if not isinstance ( op , Scalar ) : op = ScalarValue . create ( op ) converted_operands . append ( op ) return super ( ) . create ( * converted_operands , ** kwargs )
Instantiate the product while applying simplification rules
62,862
def conjugate ( self ) : return self . __class__ . create ( * [ arg . conjugate ( ) for arg in reversed ( self . args ) ] )
Complex conjugate of of the product
62,863
def create ( cls , term , * ranges ) : if not isinstance ( term , Scalar ) : term = ScalarValue . create ( term ) return super ( ) . create ( term , * ranges )
Instantiate the indexed sum while applying simplification rules
62,864
def conjugate ( self ) : return self . __class__ . create ( self . term . conjugate ( ) , * self . ranges )
Complex conjugate of of the indexed sum
62,865
def collect_summands ( cls , ops , kwargs ) : from qnet . algebra . core . abstract_quantum_algebra import ( ScalarTimesQuantumExpression ) coeff_map = OrderedDict ( ) for op in ops : if isinstance ( op , ScalarTimesQuantumExpression ) : coeff , term = op . coeff , op . term else : coeff , term = 1 , op if term in coef...
Collect summands that occur multiple times into a single summand
62,866
def _get_binary_replacement ( first , second , cls ) : expr = ProtoExpr ( [ first , second ] , { } ) if LOG : logger = logging . getLogger ( 'QNET.create' ) for key , rule in cls . _binary_rules . items ( ) : pat , replacement = rule match_dict = match_pattern ( pat , expr ) if match_dict : try : replaced = replacement...
Helper function for match_replace_binary
62,867
def _match_replace_binary ( cls , ops : list ) -> list : n = len ( ops ) if n <= 1 : return ops ops_left = ops [ : n // 2 ] ops_right = ops [ n // 2 : ] return _match_replace_binary_combine ( cls , _match_replace_binary ( cls , ops_left ) , _match_replace_binary ( cls , ops_right ) )
Reduce list of ops
62,868
def _match_replace_binary_combine ( cls , a : list , b : list ) -> list : if len ( a ) == 0 or len ( b ) == 0 : return a + b r = _get_binary_replacement ( a [ - 1 ] , b [ 0 ] , cls ) if r is None : return a + b if r == cls . _neutral_element : return _match_replace_binary_combine ( cls , a [ : - 1 ] , b [ 1 : ] ) if is...
combine two fully reduced lists a b
62,869
def empty_trivial ( cls , ops , kwargs ) : from qnet . algebra . core . hilbert_space_algebra import TrivialSpace if len ( ops ) == 0 : return TrivialSpace else : return ops , kwargs
A ProductSpace of zero Hilbert spaces should yield the TrivialSpace
62,870
def disjunct_hs_zero ( cls , ops , kwargs ) : from qnet . algebra . core . hilbert_space_algebra import TrivialSpace from qnet . algebra . core . operator_algebra import ZeroOperator hilbert_spaces = [ ] for op in ops : try : hs = op . space except AttributeError : hs = TrivialSpace for hs_prev in hilbert_spaces : if n...
Return ZeroOperator if all the operators in ops have a disjunct Hilbert space or an unchanged ops kwargs otherwise
62,871
def commutator_order ( cls , ops , kwargs ) : from qnet . algebra . core . operator_algebra import Commutator assert len ( ops ) == 2 if cls . order_key ( ops [ 1 ] ) < cls . order_key ( ops [ 0 ] ) : return - 1 * Commutator . create ( ops [ 1 ] , ops [ 0 ] ) else : return ops , kwargs
Apply anti - commutative property of the commutator to apply a standard ordering of the commutator arguments
62,872
def accept_bras ( cls , ops , kwargs ) : from qnet . algebra . core . state_algebra import Bra kets = [ ] for bra in ops : if isinstance ( bra , Bra ) : kets . append ( bra . ket ) else : return ops , kwargs return Bra . create ( cls . create ( * kets , ** kwargs ) )
Accept operands that are all bras and turn that into to bra of the operation applied to all corresponding kets
62,873
def _ranges_key ( r , delta_indices ) : idx = r . index_symbol if idx in delta_indices : return ( r . index_symbol . primed , r . index_symbol . name ) else : return ( 0 , ' ' )
Sorting key for ranges .
62,874
def _factors_for_expand_delta ( expr ) : from qnet . algebra . core . scalar_algebra import ScalarValue from qnet . algebra . core . abstract_quantum_algebra import ( ScalarTimesQuantumExpression ) if isinstance ( expr , ScalarTimesQuantumExpression ) : yield from _factors_for_expand_delta ( expr . coeff ) yield expr ....
Yield factors from expr mixing sympy and QNET
62,875
def _split_sympy_quantum_factor ( expr ) : from qnet . algebra . core . abstract_quantum_algebra import ( QuantumExpression , ScalarTimesQuantumExpression ) from qnet . algebra . core . scalar_algebra import ScalarValue , ScalarTimes , One if isinstance ( expr , ScalarTimesQuantumExpression ) : sympy_factor , quantum_f...
Split a product into sympy and qnet factors
62,876
def _extract_delta ( expr , idx ) : from qnet . algebra . core . abstract_quantum_algebra import QuantumExpression from qnet . algebra . core . scalar_algebra import ScalarValue sympy_factor , quantum_factor = _split_sympy_quantum_factor ( expr ) delta , new_expr = _sympy_extract_delta ( sympy_factor , idx ) if delta i...
Extract a simple Kronecker delta containing idx from expr .
62,877
def _deltasummation ( term , ranges , i_range ) : from qnet . algebra . core . abstract_quantum_algebra import QuantumExpression idx = ranges [ i_range ] . index_symbol summands = _expand_delta ( term , idx ) if len ( summands ) > 1 : return [ ( summand , ranges ) for summand in summands ] , 3 else : delta , expr = _ex...
Partially execute a summation for term with a Kronecker Delta for one of the summation indices .
62,878
def invert_permutation ( permutation ) : return tuple ( [ permutation . index ( p ) for p in range ( len ( permutation ) ) ] )
Compute the image tuple of the inverse permutation .
62,879
def permutation_to_block_permutations ( permutation ) : if len ( permutation ) == 0 or not check_permutation ( permutation ) : raise BadPermutationError ( ) cycles = permutation_to_disjoint_cycles ( permutation ) if len ( cycles ) == 1 : return ( permutation , ) current_block_start = cycles [ 0 ] [ 0 ] current_block_en...
If possible decompose a permutation into a sequence of permutations each acting on individual ranges of the full range of indices . E . g .
62,880
def block_perm_and_perms_within_blocks ( permutation , block_structure ) : nblocks = len ( block_structure ) offsets = [ sum ( block_structure [ : k ] ) for k in range ( nblocks ) ] images = [ permutation [ offset : offset + length ] for ( offset , length ) in zip ( offsets , block_structure ) ] images_mins = list ( ma...
Decompose a permutation into a block permutation and into permutations acting within each block .
62,881
def _check_kets ( * ops , same_space = False , disjunct_space = False ) : if not all ( [ ( isinstance ( o , State ) and o . isket ) for o in ops ] ) : raise TypeError ( "All operands must be Kets" ) if same_space : if not len ( { o . space for o in ops if o is not ZeroKet } ) == 1 : raise UnequalSpaces ( str ( ops ) ) ...
Check that all operands are Kets from the same Hilbert space .
62,882
def args ( self ) : if self . space . has_basis or isinstance ( self . label , SymbolicLabelBase ) : return ( self . label , ) else : return ( self . index , )
Tuple containing label_or_index as its only element .
62,883
def to_fock_representation ( self , index_symbol = 'n' , max_terms = None ) : phase_factor = sympy . exp ( sympy . Rational ( - 1 , 2 ) * self . ampl * self . ampl . conjugate ( ) ) if not isinstance ( index_symbol , IdxSym ) : index_symbol = IdxSym ( index_symbol ) n = index_symbol if max_terms is None : index_range =...
Return the coherent state written out as an indexed sum over Fock basis states
62,884
def codemirror_script ( self , inputid ) : varname = "{}_codemirror" . format ( inputid ) html = self . get_codemirror_field_js ( ) opts = self . codemirror_config ( ) return html . format ( varname = varname , inputid = inputid , settings = json . dumps ( opts , sort_keys = True ) )
Build CodeMirror HTML script tag which contains CodeMirror init .
62,885
def _algebraic_rules_scalar ( ) : a = wc ( "a" , head = SCALAR_VAL_TYPES ) b = wc ( "b" , head = SCALAR_VAL_TYPES ) x = wc ( "x" , head = SCALAR_TYPES ) y = wc ( "y" , head = SCALAR_TYPES ) z = wc ( "z" , head = SCALAR_TYPES ) indranges__ = wc ( "indranges__" , head = IndexRangeBase ) ScalarTimes . _binary_rules . upda...
Set the default algebraic rules for scalars
62,886
def _tensor_decompose_series ( lhs , rhs ) : if isinstance ( rhs , CPermutation ) : raise CannotSimplify ( ) lhs_structure = lhs . block_structure rhs_structure = rhs . block_structure res_struct = _get_common_block_structure ( lhs_structure , rhs_structure ) if len ( res_struct ) > 1 : blocks , oblocks = ( lhs . get_b...
Simplification method for lhs << rhs
62,887
def _factor_permutation_for_blocks ( cperm , rhs ) : rbs = rhs . block_structure if rhs == cid ( rhs . cdim ) : return cperm if len ( rbs ) > 1 : residual_lhs , transformed_rhs , carried_through_lhs = cperm . _factorize_for_rhs ( rhs ) if residual_lhs == cperm : raise CannotSimplify ( ) return SeriesProduct . create ( ...
Simplification method for cperm << rhs . Decompose a series product of a channel permutation and a reducible circuit with appropriate block structure by decomposing the permutation into a permutation within each block of rhs and a block permutation and a residual part . This allows for achieving something close to a no...
62,888
def _pull_out_perm_lhs ( lhs , rest , out_port , in_port ) : out_inv , lhs_red = lhs . _factor_lhs ( out_port ) return lhs_red << Feedback . create ( SeriesProduct . create ( * rest ) , out_port = out_inv , in_port = in_port )
Pull out a permutation from the Feedback of a SeriesProduct with itself .
62,889
def _pull_out_unaffected_blocks_lhs ( lhs , rest , out_port , in_port ) : _ , block_index = lhs . index_in_block ( out_port ) bs = lhs . block_structure nbefore , nblock , nafter = ( sum ( bs [ : block_index ] ) , bs [ block_index ] , sum ( bs [ block_index + 1 : ] ) ) before , block , after = lhs . get_blocks ( ( nbef...
In a self - Feedback of a series product where the left - most operand is reducible pull all non - trivial blocks outside of the feedback .
62,890
def _series_feedback ( series , out_port , in_port ) : series_s = series . series_inverse ( ) . series_inverse ( ) if series_s == series : raise CannotSimplify ( ) return series_s . feedback ( out_port = out_port , in_port = in_port )
Invert a series self - feedback twice to get rid of unnecessary permutations .
62,891
def properties_for_args ( cls , arg_names = '_arg_names' ) : from qnet . algebra . core . scalar_algebra import Scalar scalar_args = False if hasattr ( cls , '_scalar_args' ) : scalar_args = cls . _scalar_args for arg_name in getattr ( cls , arg_names ) : def get_arg ( self , name ) : val = getattr ( self , "_%s" % nam...
For a class with an attribute arg_names containing a list of names add a property for every name in that list .
62,892
def get_category ( self , slug ) : try : return get_category_for_slug ( slug ) except ObjectDoesNotExist as e : raise Http404 ( str ( e ) )
Get the category object
62,893
def validate_unique_slug ( self , cleaned_data ) : date_kwargs = { } error_msg = _ ( "The slug is not unique" ) pubdate = cleaned_data [ 'publication_date' ] or now ( ) if '{year}' in appsettings . FLUENT_BLOGS_ENTRY_LINK_STYLE : date_kwargs [ 'year' ] = pubdate . year error_msg = _ ( "The slug is not unique within it'...
Test whether the slug is unique within a given time period .
62,894
def _apply_rules_no_recurse ( expr , rules ) : try : items = rules . items ( ) except AttributeError : items = enumerate ( rules ) for key , ( pat , replacement ) in items : matched = pat . match ( expr ) if matched : try : return replacement ( ** matched ) except CannotSimplify : pass return expr
Non - recursively match expr again all rules
62,895
def create ( cls , * args , ** kwargs ) : global LEVEL if LOG : logger = logging . getLogger ( 'QNET.create' ) logger . debug ( "%s%s.create(*args, **kwargs); args = %s, kwargs = %s" , ( " " * LEVEL ) , cls . __name__ , args , kwargs ) LEVEL += 1 key = cls . _get_instance_key ( args , kwargs ) try : if cls . instance_...
Instantiate while applying automatic simplifications
62,896
def kwargs ( self ) : if hasattr ( self , '_has_kwargs' ) and self . _has_kwargs : raise NotImplementedError ( "Class %s does not provide a kwargs property" % str ( self . __class__ . __name__ ) ) return { }
The dictionary of keyword - only arguments for the instantiation of the Expression
62,897
def substitute ( self , var_map ) : if self in var_map : return var_map [ self ] return self . _substitute ( var_map )
Substitute sub - expressions
62,898
def apply_rules ( self , rules , recursive = True ) : if recursive : new_args = [ _apply_rules ( arg , rules ) for arg in self . args ] new_kwargs = { key : _apply_rules ( val , rules ) for ( key , val ) in self . kwargs . items ( ) } else : new_args = self . args new_kwargs = self . kwargs simplified = self . create (...
Rebuild the expression while applying a list of rules
62,899
def apply_rule ( self , pattern , replacement , recursive = True ) : return self . apply_rules ( [ ( pattern , replacement ) ] , recursive = recursive )
Apply a single rules to the expression