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' ) : other_index_symbols . update ( [ r . index_symbol for r in other . ranges ] ) else : other_index_symbols . update ( [ r . index_symbol for r in other ] ) except AttributeError : raise ValueError ( "Each element of other must be an an instance of IdxSym, " "IndexRangeBase, an object with a `ranges` attribute " "with a list of IndexRangeBase instances, or a list of" "IndexRangeBase objects." ) for r in self . ranges : index_symbol = r . index_symbol modified = False while index_symbol in other_index_symbols : modified = True index_symbol = index_symbol . incr_primed ( ) if modified : new = new . _substitute ( { r . index_symbol : index_symbol } , safe = True ) return new
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 CodeMirrorFieldBundleError ( msg . format ( field . config_name ) ) return bundle_name
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 CodeMirrorFieldBundleError ( msg . format ( field . config_name ) ) return bundle_name
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 ( config_name , varname , element_id ) output . write ( html ) content = output . getvalue ( ) output . close ( ) return mark_safe ( content )
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 , LocalSpace ) : QuantumExpression . _default_hs_cls = default_hs_cls else : raise TypeError ( "default_hs_cls must be a subclass of LocalSpace" )
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 ( settings . CODEMIRROR_SETTINGS [ name ] ) ) if 'css_bundle_name' not in parameters : css_template_name = settings . CODEMIRROR_BUNDLE_CSS_NAME parameters [ 'css_bundle_name' ] = css_template_name . format ( settings_name = name ) if 'js_bundle_name' not in parameters : js_template_name = settings . CODEMIRROR_BUNDLE_JS_NAME parameters [ 'js_bundle_name' ] = js_template_name . format ( settings_name = name ) self . registry [ name ] = parameters return parameters
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 " "conjugate" % str ( val ) ) return self . element_wise ( re )
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 " "conjugate" % str ( val ) ) return self . element_wise ( im )
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 : initial [ 'foo' ] = fp . read ( ) return initial
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 orderby in ORDER_BY_DESC ) or ( order or 'asc' ) . lower ( ) in ( 'desc' , 'descending' ) if is_desc : return map ( lambda name : '-' + name , db_fieldnames ) else : return db_fieldnames
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 . all ( ) if appsettings . FLUENT_BLOGS_FILTER_SITE_ID : queryset = queryset . parent_site ( settings . SITE_ID ) if not future : queryset = queryset . published ( ) if year : queryset = queryset . filter ( publication_date__year = year ) if month : queryset = queryset . filter ( publication_date__month = month ) if day : queryset = queryset . filter ( publication_date__day = day ) if category : if isinstance ( category , basestring ) : queryset = queryset . categories ( category ) elif isinstance ( category , ( int , long ) ) : queryset = queryset . filter ( categories = category ) else : raise ValueError ( "Expected slug or ID for the 'category' parameter" ) if category_slug : queryset = queryset . categories ( category ) if tag : if isinstance ( tag , basestring ) : queryset = queryset . tagged ( tag ) elif isinstance ( tag , ( int , long ) ) : queryset = queryset . filter ( tags = tag ) else : raise ValueError ( "Expected slug or ID for 'tag' parameter." ) if tag_slug : queryset = queryset . tagged ( tag ) if author : if isinstance ( author , basestring ) : queryset = queryset . authors ( author ) elif isinstance ( author , ( int , long ) ) : queryset = queryset . filter ( author = author ) else : raise ValueError ( "Expected slug or ID for 'author' parameter." ) if author_slug : queryset = queryset . authors ( author_slug ) if orderby : queryset = queryset . order_by ( * _get_order_by ( order , orderby , ENTRY_ORDER_BY_FIELDS ) ) else : queryset = queryset . order_by ( '-publication_date' ) if limit : queryset = queryset [ : limit ] return queryset
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 [ 'parent_site' ] = settings . SITE_ID entry_qs = EntryModel . objects . filter ( ** entry_filter ) . values_list ( 'pk' ) queryset = Tag . objects . filter ( taggit_taggeditem_items__content_type = ct , taggit_taggeditem_items__object_id__in = entry_qs ) . annotate ( count = Count ( 'taggit_taggeditem_items' ) ) if orderby : queryset = queryset . order_by ( * _get_order_by ( order , orderby , TAG_ORDER_BY_FIELDS ) ) else : queryset = queryset . order_by ( '-count' ) if limit : queryset = queryset [ : limit ] return queryset
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 , 0 , 0 , 0 , tzinfo = utc ) end = start + timedelta ( days = monthrange ( year , month ) [ 1 ] , microseconds = - 1 ) return ( start , end ) else : start = datetime ( year , month , day , 0 , 0 , 0 , tzinfo = utc ) end = start + timedelta ( days = 1 , microseconds = - 1 ) return ( start , end )
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 ( expr_or_pattern ) , repr ( expr ) ) return res
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 , Pattern ) : res . update ( val . wc_names ) return res
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 ImportError ( "{app_label}.{model_name} could not be imported." . format ( app_label = app_label , model_name = model_name ) ) if 'fluent_comments' in settings . INSTALLED_APPS and issubclass ( _EntryModel , CommentsEntryMixin ) : from fluent_comments . moderation import moderate_model moderate_model ( _EntryModel , publication_date_field = 'publication_date' , enable_comments_field = 'enable_comments' , ) if 'any_urlfield' in settings . INSTALLED_APPS : from any_urlfield . models import AnyUrlField from any_urlfield . forms . widgets import SimpleRawIdWidget AnyUrlField . register_model ( _EntryModel , widget = SimpleRawIdWidget ( _EntryModel ) ) return _EntryModel
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_BLOGS_CATEGORY_MODEL , str ( e ) ) )
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 = BC . operands [ 0 ] C = OperatorTimes . create ( * BC . operands [ 1 : ] ) return Commutator . create ( A , B ) * C + B * Commutator . create ( A , C ) def leibniz_left ( AB , C ) : A = AB . operands [ 0 ] B = OperatorTimes ( * AB . operands [ 1 : ] ) return A * Commutator . create ( B , C ) + Commutator . create ( A , C ) * B rules = OrderedDict ( [ ( 'leibniz1' , ( pattern ( Commutator , A , BC ) , lambda A , BC : recurse ( leibniz_right ( A , BC ) . expand ( ) ) ) ) , ( 'leibniz2' , ( pattern ( Commutator , AB , C ) , lambda AB , C : recurse ( leibniz_left ( AB , C ) . expand ( ) ) ) ) ] ) if expand_expr : res = _apply_rules ( expr . expand ( ) , rules ) . expand ( ) else : res = _apply_rules ( expr , rules ) return res
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' , '' ) == 'ascii' : sympy_init_printing ( use_unicode = False ) else : sympy_init_printing ( ) if 'inifile' in kwargs : invalid_kwargs = False if '_freeze' in kwargs : _freeze = kwargs [ '_freeze' ] if len ( kwargs ) != 2 : invalid_kwargs = True else : _freeze = False if len ( kwargs ) != 1 : invalid_kwargs = True if invalid_kwargs : raise TypeError ( "The `inifile` argument cannot be combined with any " "other keyword arguments" ) logger . debug ( "Initializating printing from INI file %s" , kwargs [ 'inifile' ] ) return _init_printing_from_file ( kwargs [ 'inifile' ] , _freeze = _freeze ) else : logger . debug ( "Initializating printing with direct settings: %s" , repr ( kwargs ) ) return _init_printing ( ** kwargs )
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 object in TrivialSpace to qutip. " "You may pass a non-trivial `full_space`" ) if mapping is not None : if expr in mapping : ret = mapping [ expr ] if isinstance ( ret , qutip . Qobj ) : return ret else : assert callable ( ret ) return ret ( expr ) if expr is IdentityOperator : local_spaces = full_space . local_factors if len ( local_spaces ) == 0 : raise ValueError ( "full_space %s does not have local factors" % full_space ) else : return qutip . tensor ( * [ qutip . qeye ( s . dimension ) for s in local_spaces ] ) elif expr is ZeroOperator : return qutip . tensor ( * [ qutip . Qobj ( csr_matrix ( ( s . dimension , s . dimension ) ) ) for s in full_space . local_factors ] ) elif isinstance ( expr , LocalOperator ) : return _convert_local_operator_to_qutip ( expr , full_space , mapping ) elif ( isinstance ( expr , Operator ) and isinstance ( expr , Operation ) ) : return _convert_operator_operation_to_qutip ( expr , full_space , mapping ) elif isinstance ( expr , OperatorTrace ) : raise NotImplementedError ( 'Cannot convert OperatorTrace to ' 'qutip' ) elif isinstance ( expr , State ) : return _convert_ket_to_qutip ( expr , full_space , mapping ) elif isinstance ( expr , SuperOperator ) : return _convert_superoperator_to_qutip ( expr , full_space , mapping ) elif isinstance ( expr , Operation ) : return _convert_state_operation_to_qutip ( expr , full_space , mapping ) elif isinstance ( expr , SLH ) : raise ValueError ( "SLH objects can only be converted using " "SLH_to_qutip routine" ) else : raise ValueError ( "Cannot convert '%s' of type %s" % ( str ( expr ) , type ( expr ) ) )
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_index ] ] + [ convert_to_qutip ( expr , expr . space , mapping = mapping ) , ] + [ qutip . qeye ( s . dimension ) for s in all_spaces [ own_space_index + 1 : ] ] ) ) if isinstance ( expr , Create ) : return qutip . create ( n ) elif isinstance ( expr , Jz ) : return qutip . jmat ( ( expr . space . dimension - 1 ) / 2. , "z" ) elif isinstance ( expr , Jplus ) : return qutip . jmat ( ( expr . space . dimension - 1 ) / 2. , "+" ) elif isinstance ( expr , Jminus ) : return qutip . jmat ( ( expr . space . dimension - 1 ) / 2. , "-" ) elif isinstance ( expr , Destroy ) : return qutip . destroy ( n ) elif isinstance ( expr , Phase ) : arg = complex ( expr . operands [ 1 ] ) * arange ( n ) d = np_cos ( arg ) + 1j * np_sin ( arg ) return qutip . Qobj ( np_diag ( d ) ) elif isinstance ( expr , Displace ) : alpha = expr . operands [ 1 ] return qutip . displace ( n , alpha ) elif isinstance ( expr , Squeeze ) : eta = expr . operands [ 1 ] return qutip . displace ( n , eta ) elif isinstance ( expr , LocalSigma ) : j = expr . j k = expr . k if isinstance ( j , str ) : j = expr . space . basis_labels . index ( j ) if isinstance ( k , str ) : k = expr . space . basis_labels . index ( k ) ket = qutip . basis ( n , j ) bra = qutip . basis ( n , k ) . dag ( ) return ket * bra else : raise ValueError ( "Cannot convert '%s' of type %s" % ( str ( expr ) , type ( expr ) ) )
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_symbol not in o . free_symbols : if len ( result ) == 0 : result . append ( convert_to_qutip ( o , full_space = full_space ) ) else : result [ 0 ] += convert_to_qutip ( o , full_space = full_space ) for o in op . operands : if time_symbol in o . free_symbols : result . append ( _time_dependent_to_qutip ( o , full_space , time_symbol , convert_as ) ) return result elif ( isinstance ( op , ScalarTimesOperator ) and isinstance ( op . coeff , ScalarValue ) ) : if convert_as == 'pyfunc' : func_no_args = lambdify ( time_symbol , op . coeff . val ) if { time_symbol , } == op . coeff . free_symbols : def func ( t , args ) : return func_no_args ( t ) else : def func ( t , args ) : return func_no_args ( t ) . subs ( args ) coeff = func elif convert_as == 'str' : coeff = re . sub ( "I" , "(1.0j)" , str ( op . coeff . val ) ) else : raise ValueError ( ( "Invalid value '%s' for `convert_as`, must " "be one of 'str', 'pyfunc'" ) % convert_as ) return [ convert_to_qutip ( op . term , full_space ) , coeff ] else : raise ValueError ( "op cannot be expressed in qutip. It must have " "the structure op = sum_i f_i(t) * op_i" ) else : return convert_to_qutip ( op , full_space = full_space )
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 ( "j is not an integer or sympy expression: %s" % type ( j ) ) if i == j : return One else : delta = sympy . KroneckerDelta ( i , j ) if simplify : delta = _simplify_delta ( delta ) return ScalarValue . create ( delta )
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 coeff_map : coeff_map [ term ] += coeff else : coeff_map [ term ] = coeff fops = [ ] for ( term , coeff ) in coeff_map . items ( ) : op = coeff * term if not op . is_zero : fops . append ( op ) if len ( fops ) == 0 : return cls . _zero elif len ( fops ) == 1 : return fops [ 0 ] else : return tuple ( fops ) , kwargs
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 ( ** match_dict ) if LOG : logger . debug ( "%sRule %s.%s: (%s, %s) -> %s" , ( " " * ( LEVEL ) ) , cls . __name__ , key , expr . args , expr . kwargs , replaced ) return replaced except CannotSimplify : if LOG_NO_MATCH : logger . debug ( "%sRule %s.%s: no match: CannotSimplify" , ( " " * ( LEVEL ) ) , cls . __name__ , key ) continue else : if LOG_NO_MATCH : logger . debug ( "%sRule %s.%s: no match: %s" , ( " " * ( LEVEL ) ) , cls . __name__ , key , match_dict . reason ) return None
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 isinstance ( r , cls ) : r = list ( r . args ) else : r = [ r , ] return _match_replace_binary_combine ( cls , _match_replace_binary_combine ( cls , a [ : - 1 ] , r ) , b [ 1 : ] )
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 not hs . isdisjoint ( hs_prev ) : return ops , kwargs hilbert_spaces . append ( hs ) return ZeroOperator
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 . term elif isinstance ( expr , ScalarValue ) : yield from _factors_for_expand_delta ( expr . val ) elif isinstance ( expr , sympy . Basic ) and expr . is_Mul : yield from expr . args else : 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_factor = _split_sympy_quantum_factor ( expr . coeff ) quantum_factor *= expr . term elif isinstance ( expr , ScalarValue ) : sympy_factor = expr . val quantum_factor = expr . _one elif isinstance ( expr , ScalarTimes ) : sympy_factor = sympy . S ( 1 ) quantum_factor = expr . _one for op in expr . operands : op_sympy , op_quantum = _split_sympy_quantum_factor ( op ) sympy_factor *= op_sympy quantum_factor *= op_quantum elif isinstance ( expr , sympy . Basic ) : sympy_factor = expr quantum_factor = One else : sympy_factor = sympy . S ( 1 ) quantum_factor = expr assert isinstance ( sympy_factor , sympy . Basic ) assert isinstance ( quantum_factor , QuantumExpression ) return sympy_factor , quantum_factor
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 is None : new_expr = expr else : new_expr = new_expr * quantum_factor if isinstance ( new_expr , ScalarValue . _val_types ) : new_expr = ScalarValue . create ( new_expr ) assert isinstance ( new_expr , QuantumExpression ) return delta , new_expr
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 = _extract_delta ( summands [ 0 ] , idx ) if not delta : return [ ( term , ranges ) ] , 2 solns = sympy . solve ( delta . args [ 0 ] - delta . args [ 1 ] , idx ) assert len ( solns ) > 0 if len ( solns ) != 1 : return [ ( term , ranges ) ] , 2 value = solns [ 0 ] new_term = expr . substitute ( { idx : value } ) if _RESOLVE_KRONECKER_WITH_PIECEWISE : new_term *= ranges [ i_range ] . piecewise_one ( value ) assert isinstance ( new_term , QuantumExpression ) return [ ( new_term , ranges [ : i_range ] + ranges [ i_range + 1 : ] ) ] , 1
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_end = max ( cycles [ 0 ] ) current_block_cycles = [ cycles [ 0 ] ] res_permutations = [ ] for c in cycles [ 1 : ] : if c [ 0 ] > current_block_end : res_permutations . append ( permutation_from_disjoint_cycles ( current_block_cycles , current_block_start ) ) assert sum ( map ( len , current_block_cycles ) ) == current_block_end - current_block_start + 1 current_block_start = c [ 0 ] current_block_end = max ( c ) current_block_cycles = [ c ] else : current_block_cycles . append ( c ) if max ( c ) > current_block_end : current_block_end = max ( c ) res_permutations . append ( permutation_from_disjoint_cycles ( current_block_cycles , current_block_start ) ) assert sum ( map ( len , current_block_cycles ) ) == current_block_end - current_block_start + 1 assert sum ( map ( len , res_permutations ) ) == len ( permutation ) return res_permutations
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 ( map ( min , images ) ) key_block_perm_inv = lambda block_index : images_mins [ block_index ] block_perm_inv = tuple ( sorted ( range ( nblocks ) , key = key_block_perm_inv ) ) block_perm = invert_permutation ( block_perm_inv ) assert images_mins [ block_perm_inv [ 0 ] ] == min ( images_mins ) assert images_mins [ block_perm_inv [ - 1 ] ] == max ( images_mins ) perms_within_blocks = [ ] for ( offset , length , image ) in zip ( offsets , block_structure , images ) : block_key = lambda elt_index : image [ elt_index ] within_inv = sorted ( range ( length ) , key = block_key ) within = invert_permutation ( tuple ( within_inv ) ) assert permutation [ within_inv [ 0 ] + offset ] == min ( image ) assert permutation [ within_inv [ - 1 ] + offset ] == max ( image ) perms_within_blocks . append ( within ) return block_perm , perms_within_blocks
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 ) ) if disjunct_space : spc = TrivialSpace for o in ops : if o . space & spc > TrivialSpace : raise OverlappingSpaces ( str ( ops ) ) spc *= o . space
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 = IndexOverFockSpace ( n , hs = self . _hs ) else : index_range = IndexOverRange ( n , 0 , max_terms - 1 ) term = ( ( self . ampl ** n / sympy . sqrt ( sympy . factorial ( n ) ) ) * BasisKet ( FockIndex ( n ) , hs = self . _hs ) ) return phase_factor * KetIndexedSum ( term , 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 . update ( check_rules_dict ( [ ( 'R001' , ( pattern_head ( a , b ) , lambda a , b : a * b ) ) , ( 'R002' , ( pattern_head ( x , x ) , lambda x : x ** 2 ) ) , ( 'R003' , ( pattern_head ( Zero , x ) , lambda x : Zero ) ) , ( 'R004' , ( pattern_head ( x , Zero ) , lambda x : Zero ) ) , ( 'R005' , ( pattern_head ( pattern ( ScalarPower , x , y ) , pattern ( ScalarPower , x , z ) ) , lambda x , y , z : x ** ( y + z ) ) ) , ( 'R006' , ( pattern_head ( x , pattern ( ScalarPower , x , - 1 ) ) , lambda x : One ) ) , ] ) ) ScalarPower . _rules . update ( check_rules_dict ( [ ( 'R001' , ( pattern_head ( a , b ) , lambda a , b : a ** b ) ) , ( 'R002' , ( pattern_head ( x , 0 ) , lambda x : One ) ) , ( 'R003' , ( pattern_head ( x , 1 ) , lambda x : x ) ) , ( 'R004' , ( pattern_head ( pattern ( ScalarPower , x , y ) , z ) , lambda x , y , z : x ** ( y * z ) ) ) , ] ) ) def pull_constfactor_from_sum ( x , y , indranges ) : bound_symbols = set ( [ r . index_symbol for r in indranges ] ) if len ( x . free_symbols . intersection ( bound_symbols ) ) == 0 : return x * ScalarIndexedSum . create ( y , * indranges ) else : raise CannotSimplify ( ) ScalarIndexedSum . _rules . update ( check_rules_dict ( [ ( 'R001' , ( pattern_head ( Zero , indranges__ ) , lambda indranges : Zero ) ) , ( 'R002' , ( pattern_head ( pattern ( ScalarTimes , x , y ) , indranges__ ) , lambda x , y , indranges : pull_constfactor_from_sum ( x , y , indranges ) ) ) , ] ) )
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_blocks ( res_struct ) , rhs . get_blocks ( res_struct ) ) parallel_series = [ SeriesProduct . create ( lb , rb ) for ( lb , rb ) in zip ( blocks , oblocks ) ] return Concatenation . create ( * parallel_series ) raise CannotSimplify ( )
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 ( residual_lhs , transformed_rhs , carried_through_lhs ) raise CannotSimplify ( )
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 normal form for circuit expression .
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 ( ( nbefore , nblock , nafter ) ) if before != cid ( nbefore ) or after != cid ( nafter ) : outer_lhs = before + cid ( nblock - 1 ) + after inner_lhs = cid ( nbefore ) + block + cid ( nafter ) return outer_lhs << Feedback . create ( SeriesProduct . create ( inner_lhs , * rest ) , out_port = out_port , in_port = in_port ) elif block == cid ( nblock ) : outer_lhs = before + cid ( nblock - 1 ) + after return outer_lhs << Feedback . create ( SeriesProduct . create ( * rest ) , out_port = out_port , in_port = in_port ) raise CannotSimplify ( )
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" % name ) if scalar_args : assert isinstance ( val , Scalar ) return val prop = property ( partial ( get_arg , name = arg_name ) ) doc = "The `%s` argument" % arg_name if scalar_args : doc += ", as a :class:`.Scalar` instance." else : doc += "." prop . __doc__ = doc setattr ( cls , arg_name , prop ) cls . _has_properties_for_args = True return cls
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's publication year." ) if '{month}' in appsettings . FLUENT_BLOGS_ENTRY_LINK_STYLE : date_kwargs [ 'month' ] = pubdate . month error_msg = _ ( "The slug is not unique within it's publication month." ) if '{day}' in appsettings . FLUENT_BLOGS_ENTRY_LINK_STYLE : date_kwargs [ 'day' ] = pubdate . day error_msg = _ ( "The slug is not unique within it's publication day." ) date_range = get_date_range ( ** date_kwargs ) dup_filters = self . get_unique_slug_filters ( cleaned_data ) if date_range : dup_filters [ 'publication_date__range' ] = date_range dup_qs = EntryModel . objects . filter ( ** dup_filters ) if self . instance and self . instance . pk : dup_qs = dup_qs . exclude ( pk = self . instance . pk ) if dup_qs . exists ( ) : raise ValidationError ( error_msg )
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_caching : instance = cls . _instances [ key ] if LOG : LEVEL -= 1 logger . debug ( "%s(cached)-> %s" , ( " " * LEVEL ) , instance ) return instance except KeyError : pass for i , simplification in enumerate ( cls . simplifications ) : if LOG : try : simpl_name = simplification . __name__ except AttributeError : simpl_name = "simpl%d" % i simplified = simplification ( cls , args , kwargs ) try : args , kwargs = simplified if LOG : logger . debug ( "%s(%s)-> args = %s, kwargs = %s" , ( " " * LEVEL ) , simpl_name , args , kwargs ) except ( TypeError , ValueError ) : if cls . instance_caching : cls . _instances [ key ] = simplified if cls . _create_idempotent and cls . instance_caching : try : key2 = simplified . _instance_key if key2 != key : cls . _instances [ key2 ] = simplified except AttributeError : pass if LOG : LEVEL -= 1 logger . debug ( "%s(%s)-> %s" , ( " " * LEVEL ) , simpl_name , simplified ) return simplified if len ( kwargs ) > 0 : cls . _has_kwargs = True instance = cls ( * args , ** kwargs ) if cls . instance_caching : cls . _instances [ key ] = instance if cls . _create_idempotent and cls . instance_caching : key2 = cls . _get_instance_key ( args , kwargs ) if key2 != key : cls . _instances [ key2 ] = instance if LOG : LEVEL -= 1 logger . debug ( "%s -> %s" , ( " " * LEVEL ) , instance ) return 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 ( * new_args , ** new_kwargs ) return _apply_rules_no_recurse ( simplified , rules )
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