bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,100
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,101
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,102
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,103
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,104
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,105
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,106
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 472,107
|
def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s)
|
def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s)
| 472,108
|
def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s)
|
def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s)
| 472,109
|
def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s)
|
def vars_in_str(s): """ Given a string like 'mass/(length*time)', return the list ['mass', 'length', 'time']. INPUT: - `s` -- string OUTPUT: - list of strings (unit names) EXAMPLES:: sage: sage.symbolic.units.vars_in_str('mass/(length*time)') ['mass', 'length', 'time'] """ return re.findall('[a-z|_]+', s)
| 472,110
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,111
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,112
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,113
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,114
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,115
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,116
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
|
def unit_derivations_expr(v): """ Given derived units name, returns the corresponding units expression. For example, given 'acceleration' output the symbolic expression length/time^2. INPUT: - `v` -- string, name of a unit type such as 'area', 'volume', etc. OUTPUT: - symbolic expression EXAMPLES:: sage: sage.symbolic.units.unit_derivations_expr('volume') length^3 sage: sage.symbolic.units.unit_derivations_expr('electric_potential') length^2*mass/(current*time^3) If the unit name is unknown, a KeyError is raised:: sage: sage.symbolic.units.unit_derivations_expr('invalid') Traceback (most recent call last): ... KeyError: 'invalid' """ v = str(v) Z = unit_derivations[v] if isinstance(Z,str): d = dict([(x,str_to_unit(x)) for x in vars_in_str(Z)]) from sage.misc.all import sage_eval Z = sage_eval(Z, d) unit_derivations[v] = Z return Z
| 472,117
|
def _sage_doc_(self):
|
def _sage_doc_(self):
| 472,118
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
| 472,119
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
| 472,120
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
| 472,121
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
| 472,122
|
def __init__(self, data, name=''):
|
def __init__(self, data, name=''):
| 472,123
|
def __getstate__(self):
|
def __getstate__(self):
| 472,124
|
def __setstate__(self, state):
|
def __setstate__(self, state):
| 472,125
|
def __cmp__(self, other):
|
def __cmp__(self, other):
| 472,126
|
def trait_names(self):
|
def trait_names(self):
| 472,127
|
def __getattr__(self, name):
|
def __getattr__(self, name):
| 472,128
|
def __repr__(self):
|
def __repr__(self):
| 472,129
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
| 472,130
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
| 472,131
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
| 472,132
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
|
def unitdocs(unit): """ Returns docstring for the given unit. INPUT: - ``unit`` OUTPUT: - ``string`` EXAMPLES:: sage: sage.symbolic.units.unitdocs('meter') 'SI base unit of length.\nDefined to be the distance light travels in vacuum in 1/299792458 of a second.' sage: sage.symbolic.units.unitdocs('amu') 'Abbreviation for atomic mass unit.\nApproximately equal to 1.660538782*10^-27 kilograms.' Units not in the list unit_docs will raise a ValueError:: sage: sage.symbolic.units.unitdocs('earth') Traceback (most recent call last): ... ValueError: No documentation exists for the unit earth. """ if is_unit(unit): return unit_docs[unit_to_type[str(unit)]+"_docs"][str(unit)] else: raise ValueError, "No documentation exists for the unit %s."%unit
| 472,133
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
| 472,134
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
| 472,135
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
| 472,136
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
| 472,137
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
|
def is_unit(s): """ Returns a boolean when asked whether the input is in the list of units. INPUT: - `s` -- an object OUTPUT: - ``bool`` EXAMPLES:: sage: sage.symbolic.units.is_unit(1) False sage: sage.symbolic.units.is_unit(units.length.meter) True The square of a unit is not a unit:: sage: sage.symbolic.units.is_unit(units.length.meter^2) False You can also directly create units using var, though they won't have a nice docstring describing the unit:: sage: sage.symbolic.units.is_unit(var('meter')) True """ return unit_to_type.has_key(str(s))
| 472,138
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,139
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,140
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,141
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,142
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,143
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,144
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,145
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
|
def convert(expr, target): """ Converts units between expr and target. If target is None then converts to SI base units. INPUT: - `expr` -- the symbolic expression converting from - `target` -- (default None) the symbolic expression converting to OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.convert(units.length.foot, None) 381/1250*meter sage: sage.symbolic.units.convert(units.mass.kilogram, units.mass.pound) 100000000/45359237*pound Raises ValueError if expr and target are not convertible:: sage: sage.symbolic.units.convert(units.mass.kilogram, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units sage: sage.symbolic.units.convert(units.length.meter^2, units.length.foot) Traceback (most recent call last): ... ValueError: Incompatible units Recognizes derived unit relationships to base units and other derived units:: sage: sage.symbolic.units.convert(units.length.foot/units.time.second^2, units.acceleration.galileo) 762/25*galileo sage: sage.symbolic.units.convert(units.mass.kilogram*units.length.meter/units.time.second^2, units.force.newton) newton sage: sage.symbolic.units.convert(units.length.foot^3, units.area.acre*units.length.inch) 1/3630*acre*inch sage: sage.symbolic.units.convert(units.charge.coulomb, units.current.ampere*units.time.second) ampere*second sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch) 1290320000000/8896443230521*pounds_per_square_inch For decimal answers multiply 1.0:: sage: sage.symbolic.units.convert(units.pressure.pascal*units.si_prefixes.kilo, units.pressure.pounds_per_square_inch)*1.0 0.145037737730209*pounds_per_square_inch """ base_target = target z = {} tz = {} for x in expr.variables(): if is_unit(x): if unit_to_type[str(x)] == 'temperature': return convert_temperature(expr, target) else: z[x] = base_units(x) expr = expr.subs(z) if target is None: return expr else: for y in base_target.variables(): if is_unit(y): tz[y] = base_units(y) base_target = base_target.subs(tz) coeff = (expr/base_target).expand() if len(coeff.variables()) != 0: raise ValueError, "Incompatible units" return coeff*target
| 472,146
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,147
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,148
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,149
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,150
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,151
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,152
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,153
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,154
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
|
def base_units(unit): """ Converts unit to base SI units. INPUT: - ``unit`` OUTPUT: - `symbolic expression` EXAMPLES:: sage: sage.symbolic.units.base_units(units.length.foot) 381/1250*meter If unit is already a base unit, it just returns that unit:: sage: sage.symbolic.units.base_units(units.length.meter) meter Derived units get broken down into their base parts:: sage: sage.symbolic.units.base_units(units.force.newton) kilogram*meter/second^2 sage: sage.symbolic.units.base_units(units.volume.liter) 1/1000*meter^3 Returns variable if 'unit' is not a unit:: sage: sage.symbolic.units.base_units(var('x')) x """ from sage.misc.all import sage_eval if not unit_to_type.has_key(str(unit)): return unit elif unit_to_type[str(unit)] == 'si_prefixes' or unit_to_type[str(unit)] == 'unit_multipliers': return sage_eval(unitdict[unit_to_type[str(unit)]][str(unit)]) else: v = SR.var(unit_to_type[str(unit)]) if unit_derivations.has_key(str(v)): base = unit_derivations_expr(v) for i in base.variables(): base = base.subs({i:SR.var(value_to_unit[str(i)]['1'])}) return base*sage_eval(unitdict[str(v)][str(unit)]) else: base = SR.var(value_to_unit[str(v)]['1'])*sage_eval(unitdict[str(v)][str(unit)]) return base
| 472,155
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
| 472,156
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
| 472,157
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
| 472,158
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
| 472,159
|
sage: def cf():
|
sage: def cf():
| 472,160
|
sage: def cf():
|
sage: def cf():
| 472,161
|
sage: def cf():
|
sage: def cf():
| 472,162
|
sage: def cf():
|
sage: def cf():
| 472,163
|
sage: def cf():
|
sage: def cf():
| 472,164
|
sage: def cf():
|
sage: def cf():
| 472,165
|
sage: def cf():
|
sage: def cf():
| 472,166
|
sage: def cf():
|
sage: def cf():
| 472,167
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
| 472,168
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
| 472,169
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
| 472,170
|
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the upper mechanical word.
|
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the upper mechanical word.
| 472,171
|
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the upper mechanical word.
|
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the upper mechanical word.
| 472,172
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def subgraph_search(self, G, induced=False): r""" Returns an induced copy of `G` in self.
| 472,173
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,174
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,175
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,176
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,177
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,178
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,179
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,180
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,181
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,182
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,183
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
|
def induced_subgraph_search(self, G): r""" Returns an induced copy of `G` in self.
| 472,184
|
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays) from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
|
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
| 472,185
|
def equify(f): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x^2 - 2 sage: equify(x^2 > 2) -x^2 + 2 sage: equify(x*y > 1) -x*y + 1 sage: equify(y > 0) -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if op is operator.gt or op is operator.ge: return symbolic_expression(f.rhs() - f.lhs()) else: return symbolic_expression(f.lhs() - f.rhs())
|
def equify(f): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x^2 - 2 sage: equify(x^2 > 2) -x^2 + 2 sage: equify(x*y > 1) -x*y + 1 sage: equify(y > 0) -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if op is operator.gt or op is operator.ge: return symbolic_expression(f.rhs() - f.lhs()) else: return symbolic_expression(f.lhs() - f.rhs())
| 472,186
|
def basiclemmavec(self,M): """ Finds a vector where the value of the quadratic form is coprime to M. EXAMPLES: sage: Q = QuadraticForm(ZZ, 2, [2, 1, 5]) sage: Q.basiclemmavec(10) (6, 5) sage: Q(_) 227 """ V=FreeModule(self.base_ring(),self.dim()) mat = self.matrix() vec = [] mod = [] M0 = abs(M) if M0 == 1: return V(0) for i in range(self.dim()): M1 = prime_to_m_part(M0, self[i,i]) if M1 != 1: vec.append(V.gen(i)) mod.append(M1) M0 = M0/M1 if M0 == 1: return CRT_list(vec,mod) for i in range(self.dim()): for j in range(i): M1 = prime_to_m_part(M0, self[i,j]) if M1 != 1: vec.append(V.i + V.j) mod.append(M1) M0 = M0/M1 if M0 == 1: return __crt_list(vec,mod) raise ValueError, "not primitive form"
|
def basiclemmavec(self,M): """ Finds a vector where the value of the quadratic form is coprime to M. EXAMPLES: sage: Q = QuadraticForm(ZZ, 2, [2, 1, 5]) sage: Q.basiclemmavec(10) (6, 5) sage: Q(_) 227 """ V=FreeModule(self.base_ring(),self.dim()) mat = self.matrix() vec = [] mod = [] M0 = abs(M) if M0 == 1: return V(0) for i in range(self.dim()): M1 = prime_to_m_part(M0, self[i,i]) if M1 != 1: vec.append(V.gen(i)) mod.append(M1) M0 = M0/M1 if M0 == 1: return tuple(CRT_vectors(vec,mod)) for i in range(self.dim()): for j in range(i): M1 = prime_to_m_part(M0, self[i,j]) if M1 != 1: vec.append(V.i + V.j) mod.append(M1) M0 = M0/M1 if M0 == 1: return __crt_list(vec,mod) raise ValueError, "not primitive form"
| 472,187
|
def __init__(self, bb=False, delimiters=["(", ")"]): """ Define an object that holds LaTeX global preferences. """ self._option = {} self._option["blackboard_bold"] = bb self._option["matrix_delimiters"] = list(delimiters) self._option["vector_delimiters"] = list(delimiters) self._option["macros"] = "" self._option["preamble"] = "" self._option["pdflatex"] = False self._option["jsmath_avoid"] = []
|
def __init__(self, bb=False, delimiters=["(", ")"]): """ Define an object that holds LaTeX global preferences. """ self._option = {} self._option["blackboard_bold"] = bb self._option["matrix_delimiters"] = list(delimiters) self._option["vector_delimiters"] = list(delimiters) self._option["macros"] = "" self._option["preamble"] = "" self._option["engine"] = "latex" self._option["engine_name"] = "LaTeX" self._option["jsmath_avoid"] = []
| 472,188
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, engine=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,189
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if engine is either ``pdflatex`` or ``xelatex'') and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,190
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``engine`` - string: latex engine to use. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,191
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If engine is latex or None, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,192
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If engine is pdflatex or xelatex and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,193
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex or xelatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,194
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if engine is None: engine = _Latex_prefs._option["engine"] if not engine and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,195
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if engine and not have_pdflatex() and not have_xelatex(): print "Error: %s does not seem to be installed. Download it from" % _Latex_prefs._option["engine_name"] print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,196
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if (not engine or engine == "latex") and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,197
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX, PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,198
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif pdflatex and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
|
def _run_latex_(filename, debug=False, density=150, pdflatex=None, png=False, do_in_background=False): """ This runs LaTeX on the TeX file "filename.tex". It produces files "filename.dvi" (or "filename.pdf"` if ``pdflatex`` is ``True``) and if ``png`` is True, "filename.png". If ``png`` is True and dvipng can't convert the dvi file to png (because of postscript specials or other issues), then dvips is called, and the PS file is converted to a png file. INPUT: - ``filename`` - string: file to process, including full path - ``debug`` - bool (optional, default False): whether to print verbose debugging output - ``density`` - integer (optional, default 150): how big output image is. - ``pdflatex`` - bool (optional, default False): whether to use pdflatex. - ``png`` - bool (optional, default False): whether to produce a png file. - ``do_in_background`` - bool (optional, default False): whether to run in the background. OUTPUT: string, which could be a string starting with 'Error' (if there was a problem), or it could be 'pdf' or 'dvi'. If ``pdflatex`` is False, then a dvi file is created, but if there appear to be problems with it (because of PS special commands, for example), then a pdf file is created instead. The function returns 'dvi' or 'pdf' to indicate which type of file is created. (Detecting problems requires that dvipng be installed; if it is not, then the dvi file is not checked for problems and 'dvi' is returned.) If ``pdflatex`` is True and there are no errors, then 'pdf' is returned. .. warning:: If ``png`` is True, then when using latex (the default), you must have 'dvipng' (or 'dvips' and 'convert') installed on your operating system, or this command won't work. When using pdflatex, you must have 'convert' installed. EXAMPLES:: sage: from sage.misc.latex import _run_latex_, _latex_file_ sage: file = os.path.join(SAGE_TMP, "temp.tex") sage: O = open(file, 'w') sage: O.write(_latex_file_([ZZ[x], RR])); O.close() sage: _run_latex_(file) # random - depends on whether latex is installed 'dvi' """ if pdflatex is None: pdflatex = _Latex_prefs._option["pdflatex"] if not pdflatex and not have_latex(): print "Error: LaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" if pdflatex and not have_pdflatex(): print "Error: PDFLaTeX does not seem to be installed. Download it from" print "ctan.org and try again." return "Error" # if png output + latex, check to see if dvipng or convert is installed. if png: if not pdflatex and not (have_dvipng() or have_convert()): print "" print "Error: neither dvipng nor convert (from the ImageMagick suite)" print "appear to be installed. Displaying LaTeX or PDFLaTeX output" print "requires at least one of these programs, so please install" print "and try again." print "" print "Go to http://sourceforge.net/projects/dvipng/ and" print "http://www.imagemagick.org to download these programs." return "Error" # if png output + pdflatex, check to see if convert is installed. elif engine == "pdflatex" and not have_convert(): print "" print "Error: convert (from the ImageMagick suite) does not" print "appear to be installed. Displaying PDFLaTeX output" print "requires this program, so please install and try again." print "" print "Go to http://www.imagemagick.org to download it." return "Error" # check_validity: check to see if the dvi file is okay by trying # to convert to a png file. if this fails, return_suffix will be # set to "pdf". return_suffix is the return value for this # function. # # thus if not png output, check validity of dvi output if dvipng # or convert is installed. else: check_validity = have_dvipng() # set up filenames, other strings: base, filename = os.path.split(filename) filename = os.path.splitext(filename)[0] # get rid of extension if len(filename.split()) > 1: raise ValueError, "filename must contain no spaces" if not debug: redirect=' 2>/dev/null 1>/dev/null ' else: redirect='' if do_in_background: background = ' &' else: background = '' if pdflatex: command = "pdflatex" # 'suffix' is used in the string 'convert' ... suffix = "pdf" return_suffix = "pdf" else: command = "latex" suffix = "ps" return_suffix = "dvi" # Define the commands to be used: lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) # dvipng is run with the 'picky' option: this means that if # there are warnings, no png file is created. dvipng = 'cd "%s"&& sage-native-execute dvipng --picky -q -T tight -D %s %s.dvi -o %s.png'%(base, density, filename, filename) dvips = 'sage-native-execute dvips %s.dvi %s'%(filename, redirect) ps2pdf = 'sage-native-execute ps2pdf %s.ps %s'%(filename, redirect) # We seem to need a larger size when using convert compared to # when using dvipng: density = int(1.4 * density / 1.3) convert = 'sage-native-execute convert -density %sx%s -trim %s.%s %s.png %s '%\ (density,density, filename, suffix, filename, redirect) e = 1 # it is possible to get through the following commands # without running a program, so in that case we force error if pdflatex: if png: cmd = ' && '.join([lt, convert]) else: cmd = lt if debug: print cmd e = os.system(cmd + ' ' + redirect + background) else: # latex, not pdflatex if (png or check_validity): if have_dvipng(): cmd = ' && '.join([lt, dvipng]) if debug: print cmd e = os.system(cmd + ' ' + redirect) dvipng_error = not os.path.exists(base + '/' + filename + '.png') # If there is no png file, then either the latex # process failed or dvipng failed. Assume that dvipng # failed, and try running dvips and convert. (If the # latex process failed, then dvips and convert will # fail also, so we'll still catch the error.) if dvipng_error: if png: if have_convert(): cmd = ' && '.join(['cd "%s"'%(base,), dvips, convert]) if debug: print "'dvipng' failed; trying 'convert' instead..." print cmd e = os.system(cmd + ' ' + redirect + background) else: print "Error: 'dvipng' failed and 'convert' is not installed." return "Error: dvipng failed." else: # not png, i.e., check_validity return_suffix = "pdf" cmd = ' && '.join(['cd "%s"'%(base,), dvips, ps2pdf]) if debug: print "bad dvi file; running dvips and ps2pdf instead..." print cmd e = os.system(cmd) if e: # error running dvips and/or ps2pdf command = "pdflatex" lt = 'cd "%s"&& sage-native-execute %s \\\\nonstopmode \\\\input{%s.tex} %s'%(base, command, filename, redirect) if debug: print "error running dvips and ps2pdf; trying pdflatex instead..." print cmd e = os.system(cmd + background) else: # don't have dvipng, so must have convert. run latex, dvips, convert. cmd = ' && '.join([lt, dvips, convert]) if debug: print cmd e = os.system(cmd + ' ' + redirect + background) if e: print "An error occurred." try: print open(base + '/' + filename + '.log').read() except IOError: pass return "Error latexing slide." return return_suffix
| 472,199
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.